diff --git a/.gitignore b/.gitignore index 7ff327c6..64c192b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,44 +1,44 @@ -### CRCE ### -/modules/conf/ -/modules/runner/ - -### Maven ### -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties - - -### NetBeans ### -nbactions.xml -nb-configuration.xml - -### Eclipse ### -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.settings/ -.loadpath - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - -# sbteclipse plugin -.target - -### IDEA ### -.idea/ -*.iml +### CRCE ### +/modules/conf/ +/modules/runner/ + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties + + +### NetBeans ### +nbactions.xml +nb-configuration.xml + +### Eclipse ### +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +### IDEA ### +.idea/ +*.iml diff --git a/README.md b/README.md index a5eb2ecf..a15de7a3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -# CRCE - Component Repository supporting Compatibility Evaluation - -CRCE is an experimental repository, designed to support research into component-based and modular systems undertaken by ReliSA research group at the Faculty of Applied Sciences, University of West Bohemia (http://relisa.kiv.zcu.cz). The project website is over at Assembla: https://www.assembla.com/spaces/crce/wiki . +# CRCE - Component Repository supporting Compatibility Evaluation + +CRCE is an experimental repository, designed to support research into component-based and modular systems undertaken by ReliSA research group at the Faculty of Applied Sciences, University of West Bohemia (http://relisa.kiv.zcu.cz). The project website is over at Assembla: https://www.assembla.com/spaces/crce/wiki . diff --git a/WEBSERVICES_DESCRIPTION_README.md b/WEBSERVICES_DESCRIPTION_README.md index 4b643aa2..2b809e9b 100644 --- a/WEBSERVICES_DESCRIPTION_README.md +++ b/WEBSERVICES_DESCRIPTION_README.md @@ -1,33 +1,33 @@ -# Branch-specific notes - -### Installation Instructions -1. Pull this branch and make use your own specific configuration as described in step no. 3 at https://www.assembla.com/spaces/crce/wiki -2. In order to prevent unsolved "maven store BUG" in this branch you need to disable maven store. Easiest way to do this is to set `store.uri` property of __conf/cz.zcu.kiv.crce.repository.maven-local.cfg__ to some non-existing directory. If you did this right you should not see a repository selection box in Web UI (since there is only filebased store active). -3. Build the repository by running `mvn -Dmaven.test.skip=true -Dfindbugs.skip=true -Dpmd.failOnViolation=false install` from project root folder. -4. Start the application by launching by `mvn pax:run` in the modules/ subfolder. -5. Web UI should now be accessible at http://localhost:8080/crce -6. Now you are able to use Webservices description module at http://localhost:8080/crce/resource?link=webservices - -### Examples of Webservice IDLs to index - - - JSON-WSP - - http://ladonize.org/python-demos/AlbumService/jsonwsp/description - - http://ladonize.org/python-demos/Calculator/jsonwsp/description - - http://grom.ijs.si:8001/MUSE_services_V3/jsonwsp/description - - WSDL - - http://ladonize.org/python-demos/Calculator/soap/description (simple IDL) - - http://ladonize.org/python-demos/AlbumService/soap/description (simple IDL) - - http://ladonize.org/python-demos/Calculator/soap11/description (simple IDL with more namespaces) - - http://ladonize.org/python-demos/AlbumService/soap11/description (simple IDL with more namespaces) - - http://www.webservicex.net/geoipservice.asmx?WSDL (more complex IDL) - - http://www.webservicex.com/globalweather.asmx?wsdl - - https://raw.githubusercontent.com/jkinred/psphere/master/psphere/wsdl/vim.wsdl (IDL will not be parsed, because this WSDL does not define any service elements in its concrete section thus no webservice descriptions to process) - - http://enterprise-demo.user.magentotrial.com/api?wsdl - - http://queue.amazonaws.com/doc/2009-02-01/QueueService.wsdl (multiple webservices in one IDL) - - https://raw.githubusercontent.com/geonetwork/ebrim/master/geonetwork-axis2-gen-ebrim/wsdl/wsdl%20from%20OGC%2007-110r2/OGC%2007-110r2%20WSDL2.0%20interface%20description.wsdl (WSDL 2.0 with no concrete section) - - WADL - - ftp://ftp.bgbilling.ru/pub/bgbilling/activemq/win/apache-activemq-5.4.2/webapps/camel/WEB-INF/classes/application.wadl - - http://spotlight.dbpedia.org/rest/application.wadl - - https://www.fueleconomy.gov/ws/rest/application.wadl - - http://api.dnbdirectapps.com/dev/DnBAPI-10/rest/application.wadl - - https://api.staging.launchpad.net/1.0/ (HTTP header is needed in GET -- Accept: application/vd.sun.wadl+xml) +# Branch-specific notes + +### Installation Instructions +1. Pull this branch and make use your own specific configuration as described in step no. 3 at https://www.assembla.com/spaces/crce/wiki +2. In order to prevent unsolved "maven store BUG" in this branch you need to disable maven store. Easiest way to do this is to set `store.uri` property of __conf/cz.zcu.kiv.crce.repository.maven-local.cfg__ to some non-existing directory. If you did this right you should not see a repository selection box in Web UI (since there is only filebased store active). +3. Build the repository by running `mvn -Dmaven.test.skip=true -Dfindbugs.skip=true -Dpmd.failOnViolation=false install` from project root folder. +4. Start the application by launching by `mvn pax:run` in the modules/ subfolder. +5. Web UI should now be accessible at http://localhost:8080/crce +6. Now you are able to use Webservices description module at http://localhost:8080/crce/resource?link=webservices + +### Examples of Webservice IDLs to index + + - JSON-WSP + - http://ladonize.org/python-demos/AlbumService/jsonwsp/description + - http://ladonize.org/python-demos/Calculator/jsonwsp/description + - http://grom.ijs.si:8001/MUSE_services_V3/jsonwsp/description + - WSDL + - http://ladonize.org/python-demos/Calculator/soap/description (simple IDL) + - http://ladonize.org/python-demos/AlbumService/soap/description (simple IDL) + - http://ladonize.org/python-demos/Calculator/soap11/description (simple IDL with more namespaces) + - http://ladonize.org/python-demos/AlbumService/soap11/description (simple IDL with more namespaces) + - http://www.webservicex.net/geoipservice.asmx?WSDL (more complex IDL) + - http://www.webservicex.com/globalweather.asmx?wsdl + - https://raw.githubusercontent.com/jkinred/psphere/master/psphere/wsdl/vim.wsdl (IDL will not be parsed, because this WSDL does not define any service elements in its concrete section thus no webservice descriptions to process) + - http://enterprise-demo.user.magentotrial.com/api?wsdl + - http://queue.amazonaws.com/doc/2009-02-01/QueueService.wsdl (multiple webservices in one IDL) + - https://raw.githubusercontent.com/geonetwork/ebrim/master/geonetwork-axis2-gen-ebrim/wsdl/wsdl%20from%20OGC%2007-110r2/OGC%2007-110r2%20WSDL2.0%20interface%20description.wsdl (WSDL 2.0 with no concrete section) + - WADL + - ftp://ftp.bgbilling.ru/pub/bgbilling/activemq/win/apache-activemq-5.4.2/webapps/camel/WEB-INF/classes/application.wadl + - http://spotlight.dbpedia.org/rest/application.wadl + - https://www.fueleconomy.gov/ws/rest/application.wadl + - http://api.dnbdirectapps.com/dev/DnBAPI-10/rest/application.wadl + - https://api.staging.launchpad.net/1.0/ (HTTP header is needed in GET -- Accept: application/vd.sun.wadl+xml) diff --git a/apiary.apib b/apiary.apib index 772e0635..4f634d64 100644 --- a/apiary.apib +++ b/apiary.apib @@ -1,230 +1,230 @@ -FORMAT: 1A - -# CRCE API -Web Service API specification for **C**omponent **R**epository supporting **C**ompabitility **E**valuation. - -Project URL: https://www.assembla.com/spaces/crce - -Source Code: http://github.com/ReliSA/crce/ - -# Group Resources -Resources of the CRCE API represent the actual component binaries. These endpoints allow browsing of -basic resource identification meta-data and the actual binary search and download. - -## Resource [/resources/{id}] -Concrete resource record identified by internal CRCE ID. - -+ Parameters - + id (required, string, `550e8400-e29b-41d4-a716-446655440000`) ... Internal CRCE identificator of the particular component.; - -### Download binary [GET] -Serves the client the binary associated with the id. Use /metadata/{id} to get resource's meta-data. - -+ Response 200 (application/octet-stream) - - + Headers - - Content-Disposition: attachement; filename="org-obcc-parking-gate-1.0.4.jar" - + Body - - ***component binary*** - -## Resources Collection [/resources] - -+ Model (application/xml) - - + Body - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -### List all Bundles [GET] -Returns list of all components in the repository with links to their binaries. Same view as /metadata collection, just from different -perspective. - -+ Response 200 - - [Resources Collection][] - -### Upload a Resource [POST] -+ Request (multipart/form-data) - - *Component binary file* - -+ Response 202 - -## Filtered Resources Collection [/resources/catalogue/{externalId}/{version}] - -+ Parameters - + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; - + version (optional, Version, `1.0.0-SNAPSHOT`) ... Version identificator having the major.minor.micro-qualifier schema; - -### List all Bundles [GET] -Returns list of all components fitting the given externalId and version, which can be found in the repository with links to their binaries. -Same view as /metadata collection, just from different perspective. - -+ Response 200 - - [Resources Collection][] - -# Group Meta-Data -Meta-Data describing bundles stored within the repository. Their capabilities, requirements and other vital pieces of information. - -## Meta-Data [/metadata/{id}] -A particular component revision. - -+ Model (application/xml) - - Model for meta-data of a single resource. - - + Body - - - - - - - -+ Parameters - + id (required, string, `550e8400-e29b-41d4-a716-446655440000`) ... Internal CRCE identificator of the particular component.; - -### Get Meta-Data for Bundle [GET] -+ Response 200 - - [Meta-Data][] - -## Meta-Data Collection [/metadata] - -+ Model (application/xml) - - Meta-Data Collection sample model. - - + Body - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -### List All Meta-Data [GET] -Returns list of all components in the repository with links to their meta-data. Same view as /resources collection, just from different -perspective. - -+ Response 200 - - [Meta-Data Collection][] - -## Filtered Meta-Data Collection [/metadata/catalogue/{externalId}/{version}] - -+ Parameters - + externalId (required, string, `org.obcc.parking.gate`) ... External ID of the particular component. E.g. OSGi "symbolic-name"; - + version (optional, Version, `1.0.0-SNAPSHOT`) ... Version identificator having the major.minor.micro-qualifier schema; - -### List Meta-Data [GET] -Returns list of all components fitting the externalId and version, which can be found in the repository with links to their meta-data. -Same view as /resources collection, just from different perspective. - -+ Response 200 - - [Meta-Data Collection][] - - -## Meta-Data describing differences between Bundles - not implemented [/meta-data/catalogue/{externalId}/{version}/diffs{?otherExternalId}{?otherVersion}] -Meta-Data with information about API differences between bundles. - -TODO: (externalId, version) might result in multiple resources. Need to extend the identification so that it is not ambiguous. - -+ Parameters - + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; - + version (required, Version, `1.0.4`) ... Version identifier; - + otherExternalId (optional, string, `com.kknd.park.gate`) ... Name of the other compared component; - + otherVersion (optional, Version, `1.0.0`) ... Version identifier of the second component; - - -### Get Diffs for Bundle [GET] -+ Response 200 (application/xml) - - - - - -## Meta-Data for a compatible Bundle - not implemented [/meta-data/catalogue/{externalId}/{version}/compatible{?operation}] -Returns meta-data for a bundle compatible with the one specified using `name` and `version` parameters. While -there might be many compatible bundles in the repository, at most one is returned. Rule, by which the bundle -is chosen is determined by the `operation` parameter, which can have the following values: - -- any any compatible bundle is returned, no specification of the relationship between the original and returned version -- lowest lowest compatible version is returned -- downgrade nearest compatible version lower than the original is returned -- upgrade (default) nearest compatible version higher than the original is returned -- highest highest compatible version is returned - -TODO: (externalId, version) might result in multiple resources. Need to extend the identification so that it is not ambiguous. - -+ Parameters - + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; - + version (required, Version, `1.0.4`) ... Version identifier; - + operation (optional, string) ... Specification of the operation you want the compatible bundle for; - -### Get Compatible Bundle Meta-Data [GET] -+ Response 200 - +FORMAT: 1A + +# CRCE API +Web Service API specification for **C**omponent **R**epository supporting **C**ompabitility **E**valuation. + +Project URL: https://www.assembla.com/spaces/crce + +Source Code: http://github.com/ReliSA/crce/ + +# Group Resources +Resources of the CRCE API represent the actual component binaries. These endpoints allow browsing of +basic resource identification meta-data and the actual binary search and download. + +## Resource [/resources/{id}] +Concrete resource record identified by internal CRCE ID. + ++ Parameters + + id (required, string, `550e8400-e29b-41d4-a716-446655440000`) ... Internal CRCE identificator of the particular component.; + +### Download binary [GET] +Serves the client the binary associated with the id. Use /metadata/{id} to get resource's meta-data. + ++ Response 200 (application/octet-stream) + + + Headers + + Content-Disposition: attachement; filename="org-obcc-parking-gate-1.0.4.jar" + + Body + + ***component binary*** + +## Resources Collection [/resources] + ++ Model (application/xml) + + + Body + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### List all Bundles [GET] +Returns list of all components in the repository with links to their binaries. Same view as /metadata collection, just from different +perspective. + ++ Response 200 + + [Resources Collection][] + +### Upload a Resource [POST] ++ Request (multipart/form-data) + + *Component binary file* + ++ Response 202 + +## Filtered Resources Collection [/resources/catalogue/{externalId}/{version}] + ++ Parameters + + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; + + version (optional, Version, `1.0.0-SNAPSHOT`) ... Version identificator having the major.minor.micro-qualifier schema; + +### List all Bundles [GET] +Returns list of all components fitting the given externalId and version, which can be found in the repository with links to their binaries. +Same view as /metadata collection, just from different perspective. + ++ Response 200 + + [Resources Collection][] + +# Group Meta-Data +Meta-Data describing bundles stored within the repository. Their capabilities, requirements and other vital pieces of information. + +## Meta-Data [/metadata/{id}] +A particular component revision. + ++ Model (application/xml) + + Model for meta-data of a single resource. + + + Body + + + + + + + ++ Parameters + + id (required, string, `550e8400-e29b-41d4-a716-446655440000`) ... Internal CRCE identificator of the particular component.; + +### Get Meta-Data for Bundle [GET] ++ Response 200 + + [Meta-Data][] + +## Meta-Data Collection [/metadata] + ++ Model (application/xml) + + Meta-Data Collection sample model. + + + Body + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### List All Meta-Data [GET] +Returns list of all components in the repository with links to their meta-data. Same view as /resources collection, just from different +perspective. + ++ Response 200 + + [Meta-Data Collection][] + +## Filtered Meta-Data Collection [/metadata/catalogue/{externalId}/{version}] + ++ Parameters + + externalId (required, string, `org.obcc.parking.gate`) ... External ID of the particular component. E.g. OSGi "symbolic-name"; + + version (optional, Version, `1.0.0-SNAPSHOT`) ... Version identificator having the major.minor.micro-qualifier schema; + +### List Meta-Data [GET] +Returns list of all components fitting the externalId and version, which can be found in the repository with links to their meta-data. +Same view as /resources collection, just from different perspective. + ++ Response 200 + + [Meta-Data Collection][] + + +## Meta-Data describing differences between Bundles - not implemented [/meta-data/catalogue/{externalId}/{version}/diffs{?otherExternalId}{?otherVersion}] +Meta-Data with information about API differences between bundles. + +TODO: (externalId, version) might result in multiple resources. Need to extend the identification so that it is not ambiguous. + ++ Parameters + + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; + + version (required, Version, `1.0.4`) ... Version identifier; + + otherExternalId (optional, string, `com.kknd.park.gate`) ... Name of the other compared component; + + otherVersion (optional, Version, `1.0.0`) ... Version identifier of the second component; + + +### Get Diffs for Bundle [GET] ++ Response 200 (application/xml) + + + + + +## Meta-Data for a compatible Bundle - not implemented [/meta-data/catalogue/{externalId}/{version}/compatible{?operation}] +Returns meta-data for a bundle compatible with the one specified using `name` and `version` parameters. While +there might be many compatible bundles in the repository, at most one is returned. Rule, by which the bundle +is chosen is determined by the `operation` parameter, which can have the following values: + +- any any compatible bundle is returned, no specification of the relationship between the original and returned version +- lowest lowest compatible version is returned +- downgrade nearest compatible version lower than the original is returned +- upgrade (default) nearest compatible version higher than the original is returned +- highest highest compatible version is returned + +TODO: (externalId, version) might result in multiple resources. Need to extend the identification so that it is not ambiguous. + ++ Parameters + + externalId (required, string, `org.obcc.parking.gate`) ... Fully qualified name of the partiuclar component. E.g. OSGi "symbolic-name"; + + version (required, Version, `1.0.4`) ... Version identifier; + + operation (optional, string) ... Specification of the operation you want the compatible bundle for; + +### Get Compatible Bundle Meta-Data [GET] ++ Response 200 + [Meta-Data][] \ No newline at end of file diff --git a/build/compiled/pom.xml b/build/compiled/pom.xml index c0ceda26..c0ad260a 100644 --- a/build/compiled/pom.xml +++ b/build/compiled/pom.xml @@ -1,130 +1,130 @@ - - - - - cz.zcu.kiv.crce - shared-build-settings - 2.1.2-SNAPSHOT - - - 4.0.0 - compiled-bundle-settings - - CRCE - Build - Compiled bundle instructions - - pom - - - - - src/main/resources - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.felix - maven-bundle-plugin - - - ${bundle.symbolicName} - ${project.version} - - !${bundle.namespace}.internal.*,${bundle.namespace}.*;version="${project.version}" - ${bundle.namespace}.internal.* - - <_include>-osgi.bnd - - - - - org.apache.maven.plugins - maven-pmd-plugin - - false - ${project.build.sourceEncoding} - 100 - ${version.jdk} - - - - verify - - check - - - - - - org.codehaus.mojo - findbugs-maven-plugin - - true - - - - verify - - check - - - - - - - - - - org.osgi - org.osgi.core - - - org.osgi - org.osgi.compendium - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.slf4j - slf4j-api - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - provided - - - com.google.code.findbugs - jsr305 - true - provided - - - com.google.code.findbugs - annotations - true - provided - - - - + + + + + cz.zcu.kiv.crce + shared-build-settings + 2.1.2-SNAPSHOT + + + 4.0.0 + compiled-bundle-settings + + CRCE - Build - Compiled bundle instructions + + pom + + + + + src/main/resources + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.felix + maven-bundle-plugin + + + ${bundle.symbolicName} + ${project.version} + + !${bundle.namespace}.internal.*,${bundle.namespace}.*;version="${project.version}" + ${bundle.namespace}.internal.* + + <_include>-osgi.bnd + + + + + org.apache.maven.plugins + maven-pmd-plugin + + false + ${project.build.sourceEncoding} + 100 + ${version.jdk} + + + + verify + + check + + + + + + org.codehaus.mojo + findbugs-maven-plugin + + true + + + + verify + + check + + + + + + + + + + org.osgi + org.osgi.core + + + org.osgi + org.osgi.compendium + + + org.apache.felix + org.apache.felix.dependencymanager + + + org.slf4j + slf4j-api + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + provided + + + com.google.code.findbugs + jsr305 + true + provided + + + com.google.code.findbugs + annotations + true + provided + + + + diff --git a/build/pom.xml b/build/pom.xml index 1dea9cd0..0276a700 100644 --- a/build/pom.xml +++ b/build/pom.xml @@ -1,676 +1,676 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - crce-parent - 2.1.0 - - - - shared-build-settings - 2.1.2-SNAPSHOT - - CRCE - Build - Shared build configuration - - pom - - - cz.zcu.kiv.crce - 1.7 - 3.0.4 - 2.11.3 - 0.8.1-incubator - 4.3.1 - 3.0.3 - 3.2.0 - 2.6.1 - 1.9.13 - 1.7.7 - - - - https://github.com/ReliSA/crce/tree/master/build - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - wrappers - compiled - - - - - - - org.ops4j - maven-pax-plugin - 1.5 - - - - org.ops4j.pax.exam - exam-maven-plugin - 4.3.0 - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18 - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.18 - - - org.apache.servicemix.tooling - depends-maven-plugin - 1.2 - - - org.apache.felix - maven-bundle-plugin - 2.5.3 - true - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - ${version.jdk} - ${version.jdk} - ${project.build.sourceEncoding} - - - - org.apache.maven.plugins - maven-enforcer-plugin - 1.3.1 - - - enforce-versions - - enforce - - - - - ${version.jdk} - - - ${version.maven} - - - - - - - - maven-war-plugin - 2.5 - - - org.apache.maven.plugins - maven-pmd-plugin - 3.1 - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.0 - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - ${version.org.apache.felix.dependencymanager} - - - - scan - - - info - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.9 - - - org.apache.cxf - cxf-xjc-plugin - 3.0.2 - - - - - - - - - - - - - org.ops4j.pax.runner - pax-runner - 1.8.6 - provided - - - - - - org.osgi - org.osgi.core - ${version.org.osgi} - provided - true - - - - org.osgi - org.osgi.compendium - ${version.org.osgi} - provided - true - - - - - - org.ops4j.pax.web - pax-web-extender-war - ${version.org.ops4j.pax.web} - provided - - - org.ops4j.pax.web - pax-web-jetty-bundle - ${version.org.ops4j.pax.web} - provided - - - org.ops4j.pax.web - pax-web-jsp - ${version.org.ops4j.pax.web} - provided - - - org.ops4j.pax.web - pax-web-spi - ${version.org.ops4j.pax.web} - provided - - - - - - - org.slf4j - slf4j-api - ${version.org.slf4j} - provided - - - - - org.slf4j - osgi-over-slf4j - ${version.org.slf4j} - provided - - - org.slf4j - log4j-over-slf4j - ${version.org.slf4j} - provided - - - org.slf4j - jcl-over-slf4j - ${version.org.slf4j} - provided - - - org.slf4j - jul-to-slf4j - ${version.org.slf4j} - provided - - - - - ch.qos.logback - logback-core - 1.1.2 - provided - - - ch.qos.logback - logback-classic - 1.1.2 - provided - - - - - - org.apache.felix - org.apache.felix.framework - 4.0.3 - - - org.apache.felix - org.apache.felix.eventadmin - 1.4.2 - provided - - - org.apache.felix - org.apache.felix.dependencymanager - ${version.org.apache.felix.dependencymanager} - provided - - - org.apache.felix - org.apache.felix.dependencymanager.shell - ${version.org.apache.felix.dependencymanager} - - provided - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - ${version.org.apache.felix.dependencymanager} - compile - - - biz.aQute - bndlib - - - - - org.apache.felix - org.apache.felix.dependencymanager.runtime - ${version.org.apache.felix.dependencymanager} - provided - - - org.apache.felix - org.apache.felix.configadmin - 1.8.0 - provided - - - org.apache.felix - org.apache.felix.bundlerepository - 2.0.2 - provided - - - org.apache.felix - org.osgi.service.obr - 1.0.2 - provided - - - org.apache.felix - org.apache.felix.scr - 1.8.2 - provided - - - org.apache.felix - org.apache.felix.webconsole - 4.2.2 - provided - - - org.apache.felix - org.apache.felix.shell - 1.4.3 - provided - - - org.apache.felix - org.apache.felix.fileinstall - 3.4.2 - provided - - - - - - - log4j - log4j - 1.2.17 - true - - - org.slf4j - slf4j-log4j12 - 1.7.7 - true - - - - - - javax.servlet - servlet-api - 2.5 - provided - - - javax.servlet - jsp-api - 2.0 - provided - - - - - org.apache.ace - org.apache.ace.httplistener - ${version.org.apache.ace} - provided - - - org.apache.ace - org.apache.ace.obr.metadata - ${version.org.apache.ace} - provided - - - org.apache.ace - org.apache.ace.obr.storage - ${version.org.apache.ace} - provided - - - org.apache.ace - org.apache.ace.obr.servlet - ${version.org.apache.ace} - provided - - - - - - org.mybatis - mybatis - 3.2.2 - provided - - - com.h2database - h2 - 1.3.176 - provided - - - com.googlecode.flyway - flyway-core - 2.3.1 - compile - - - - org.mongodb - mongo-java-driver - ${version.mongodb} - provided - - - - - - org.codehaus.plexus - plexus-utils - 3.0.15 - provided - - - org.apache.commons - commons-io - 1.3.2 - jar - provided - - - - commons-beanutils - commons-beanutils - 1.9.1 - provided - - - org.apache.commons - commons-lang3 - 3.3.2 - provided - - - - org.apache.felix - org.apache.felix.utils - 1.6.0 - jar - compile - - - - asm - asm-all - 3.3.1 - provided - - - org.ow2.asm - asm-all - 4.1 - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.commons-vfs - 1.0_6 - provided - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.bcel - 5.2_4 - provided - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.jaxp-ri - 1.4.5_1 - provided - - - com.google.code.gson - gson - 2.2.4 - provided - - - org.codehaus.groovy - groovy-all - 2.2.1 - provided - - - commons-fileupload - commons-fileupload - 1.3.1 - provided - - - commons-io - commons-io - 2.4 - provided - - - commons-net - commons-net - 3.3 - provided - - - de.twentyeleven.skysail - org.json-osgi - 20080701 - provided - - - org.apache.xbean - xbean-finder - 3.13 - - provided - - - org.apache.xbean - xbean-bundleutils - 3.13 - - - - com.google.code.findbugs - jsr305 - 3.0.0 - true - - - com.google.code.findbugs - annotations - 3.0.0 - true - - - com.fasterxml.jackson.core - jackson-core - ${version.com.fasterxml.jackson} - compile - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - ${version.com.fasterxml.jackson} - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-xml-provider - ${version.com.fasterxml.jackson} - - - com.fasterxml.jackson.core - jackson-databind - ${version.com.fasterxml.jackson} - compile - - - com.fasterxml.jackson.core - jackson-annotations - ${version.com.fasterxml.jackson} - compile - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - ${version.com.fasterxml.jackson} - compile - - - org.codehaus.jackson - jackson-core-asl - ${version.org.codehaus.jackson} - - - org.codehaus.jackson - jackson-jaxrs - ${version.org.codehaus.jackson} - - - org.codehaus.jackson - jackson-mapper-asl - ${version.org.codehaus.jackson} - - - org.codehaus.jackson - jackson-xc - ${version.org.codehaus.jackson} - - - org.codehaus.jettison - jettison - 1.3.6 - - - - - - junit - junit - 4.11 - test - - - org.skyscreamer - jsonassert - 1.2.3 - test - - - org.mockito - mockito-core - 1.9.5 - test - - - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + crce-parent + 2.1.0 + + + + shared-build-settings + 2.1.2-SNAPSHOT + + CRCE - Build - Shared build configuration + + pom + + + cz.zcu.kiv.crce + 1.7 + 3.0.4 + 2.11.3 + 0.8.1-incubator + 4.3.1 + 3.0.3 + 3.2.0 + 2.6.1 + 1.9.13 + 1.7.7 + + + + https://github.com/ReliSA/crce/tree/master/build + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + wrappers + compiled + + + + + + + org.ops4j + maven-pax-plugin + 1.5 + + + + org.ops4j.pax.exam + exam-maven-plugin + 4.3.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18 + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.18 + + + org.apache.servicemix.tooling + depends-maven-plugin + 1.2 + + + org.apache.felix + maven-bundle-plugin + 2.5.3 + true + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + ${version.jdk} + ${version.jdk} + ${project.build.sourceEncoding} + + + + org.apache.maven.plugins + maven-enforcer-plugin + 1.3.1 + + + enforce-versions + + enforce + + + + + ${version.jdk} + + + ${version.maven} + + + + + + + + maven-war-plugin + 2.5 + + + org.apache.maven.plugins + maven-pmd-plugin + 3.1 + + + org.codehaus.mojo + findbugs-maven-plugin + 3.0.0 + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + ${version.org.apache.felix.dependencymanager} + + + + scan + + + info + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.9 + + + org.apache.cxf + cxf-xjc-plugin + 3.0.2 + + + + + + + + + + + + + org.ops4j.pax.runner + pax-runner + 1.8.6 + provided + + + + + + org.osgi + org.osgi.core + ${version.org.osgi} + provided + true + + + + org.osgi + org.osgi.compendium + ${version.org.osgi} + provided + true + + + + + + org.ops4j.pax.web + pax-web-extender-war + ${version.org.ops4j.pax.web} + provided + + + org.ops4j.pax.web + pax-web-jetty-bundle + ${version.org.ops4j.pax.web} + provided + + + org.ops4j.pax.web + pax-web-jsp + ${version.org.ops4j.pax.web} + provided + + + org.ops4j.pax.web + pax-web-spi + ${version.org.ops4j.pax.web} + provided + + + + + + + org.slf4j + slf4j-api + ${version.org.slf4j} + provided + + + + + org.slf4j + osgi-over-slf4j + ${version.org.slf4j} + provided + + + org.slf4j + log4j-over-slf4j + ${version.org.slf4j} + provided + + + org.slf4j + jcl-over-slf4j + ${version.org.slf4j} + provided + + + org.slf4j + jul-to-slf4j + ${version.org.slf4j} + provided + + + + + ch.qos.logback + logback-core + 1.1.2 + provided + + + ch.qos.logback + logback-classic + 1.1.2 + provided + + + + + + org.apache.felix + org.apache.felix.framework + 4.0.3 + + + org.apache.felix + org.apache.felix.eventadmin + 1.4.2 + provided + + + org.apache.felix + org.apache.felix.dependencymanager + ${version.org.apache.felix.dependencymanager} + provided + + + org.apache.felix + org.apache.felix.dependencymanager.shell + ${version.org.apache.felix.dependencymanager} + + provided + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + ${version.org.apache.felix.dependencymanager} + compile + + + biz.aQute + bndlib + + + + + org.apache.felix + org.apache.felix.dependencymanager.runtime + ${version.org.apache.felix.dependencymanager} + provided + + + org.apache.felix + org.apache.felix.configadmin + 1.8.0 + provided + + + org.apache.felix + org.apache.felix.bundlerepository + 2.0.2 + provided + + + org.apache.felix + org.osgi.service.obr + 1.0.2 + provided + + + org.apache.felix + org.apache.felix.scr + 1.8.2 + provided + + + org.apache.felix + org.apache.felix.webconsole + 4.2.2 + provided + + + org.apache.felix + org.apache.felix.shell + 1.4.3 + provided + + + org.apache.felix + org.apache.felix.fileinstall + 3.4.2 + provided + + + + + + + log4j + log4j + 1.2.17 + true + + + org.slf4j + slf4j-log4j12 + 1.7.7 + true + + + + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.servlet + jsp-api + 2.0 + provided + + + + + org.apache.ace + org.apache.ace.httplistener + ${version.org.apache.ace} + provided + + + org.apache.ace + org.apache.ace.obr.metadata + ${version.org.apache.ace} + provided + + + org.apache.ace + org.apache.ace.obr.storage + ${version.org.apache.ace} + provided + + + org.apache.ace + org.apache.ace.obr.servlet + ${version.org.apache.ace} + provided + + + + + + org.mybatis + mybatis + 3.2.2 + provided + + + com.h2database + h2 + 1.3.176 + provided + + + com.googlecode.flyway + flyway-core + 2.3.1 + compile + + + + org.mongodb + mongo-java-driver + ${version.mongodb} + provided + + + + + + org.codehaus.plexus + plexus-utils + 3.0.15 + provided + + + org.apache.commons + commons-io + 1.3.2 + jar + provided + + + + commons-beanutils + commons-beanutils + 1.9.1 + provided + + + org.apache.commons + commons-lang3 + 3.3.2 + provided + + + + org.apache.felix + org.apache.felix.utils + 1.6.0 + jar + compile + + + + asm + asm-all + 3.3.1 + provided + + + org.ow2.asm + asm-all + 4.1 + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-vfs + 1.0_6 + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.bcel + 5.2_4 + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.jaxp-ri + 1.4.5_1 + provided + + + com.google.code.gson + gson + 2.2.4 + provided + + + org.codehaus.groovy + groovy-all + 2.2.1 + provided + + + commons-fileupload + commons-fileupload + 1.3.1 + provided + + + commons-io + commons-io + 2.4 + provided + + + commons-net + commons-net + 3.3 + provided + + + de.twentyeleven.skysail + org.json-osgi + 20080701 + provided + + + org.apache.xbean + xbean-finder + 3.13 + + provided + + + org.apache.xbean + xbean-bundleutils + 3.13 + + + + com.google.code.findbugs + jsr305 + 3.0.0 + true + + + com.google.code.findbugs + annotations + 3.0.0 + true + + + com.fasterxml.jackson.core + jackson-core + ${version.com.fasterxml.jackson} + compile + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + ${version.com.fasterxml.jackson} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider + ${version.com.fasterxml.jackson} + + + com.fasterxml.jackson.core + jackson-databind + ${version.com.fasterxml.jackson} + compile + + + com.fasterxml.jackson.core + jackson-annotations + ${version.com.fasterxml.jackson} + compile + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + ${version.com.fasterxml.jackson} + compile + + + org.codehaus.jackson + jackson-core-asl + ${version.org.codehaus.jackson} + + + org.codehaus.jackson + jackson-jaxrs + ${version.org.codehaus.jackson} + + + org.codehaus.jackson + jackson-mapper-asl + ${version.org.codehaus.jackson} + + + org.codehaus.jackson + jackson-xc + ${version.org.codehaus.jackson} + + + org.codehaus.jettison + jettison + 1.3.6 + + + + + + junit + junit + 4.11 + test + + + org.skyscreamer + jsonassert + 1.2.3 + test + + + org.mockito + mockito-core + 1.9.5 + test + + + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/build/wrappers/pom.xml b/build/wrappers/pom.xml index 21bd6e4f..7ce3634d 100644 --- a/build/wrappers/pom.xml +++ b/build/wrappers/pom.xml @@ -1,57 +1,57 @@ - - - - - cz.zcu.kiv.crce - shared-build-settings - 2.1.2-SNAPSHOT - - - 4.0.0 - wrapper-bundle-settings - - CRCE - Build - Wrapper bundle instructions - - - - - - Simple OSGi wrapper around third-party jar(s) - - - - - - - pom - - - - - - org.apache.felix - maven-bundle-plugin - - - ${bundle.symbolicName} - ${wrapped.version} - - <_exportcontents>* - !* - - <_include>-osgi.bnd - - - - - - - + + + + + cz.zcu.kiv.crce + shared-build-settings + 2.1.2-SNAPSHOT + + + 4.0.0 + wrapper-bundle-settings + + CRCE - Build - Wrapper bundle instructions + + + + + + Simple OSGi wrapper around third-party jar(s) + + + + + + + pom + + + + + + org.apache.felix + maven-bundle-plugin + + + ${bundle.symbolicName} + ${wrapped.version} + + <_exportcontents>* + !* + + <_include>-osgi.bnd + + + + + + + diff --git a/core/crce-core/pom.xml b/core/crce-core/pom.xml index 697729ed..47cad445 100644 --- a/core/crce-core/pom.xml +++ b/core/crce-core/pom.xml @@ -1,119 +1,119 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - crce-parent - 2.1.0 - - - - cz.zcu.kiv.crce - crce-core - 3.0.0-SNAPSHOT - pom - - CRCE - Core - - - https://github.com/ReliSA/crce/tree/master/core/crce-core - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-dao-api - 3.0.0-SNAPSHOT - - - ${project.groupId} - crce-metadata-dao-impl - 3.1.0-SNAPSHOT - - - ${project.groupId} - crce-metadata-impl - 3.0.0 - - - ${project.groupId} - crce-metadata-indexer-impl - 2.1.0 - - - ${project.groupId} - crce-metadata-indexer-api - 2.1.0 - - - ${project.groupId} - crce-metadata-json-api - 2.1.0 - - - ${project.groupId} - crce-metadata-json-impl - 3.0.0 - - - ${project.groupId} - crce-metadata-service-api - 3.0.0 - - - ${project.groupId} - crce-metadata-service-impl - 3.0.0 - - - ${project.groupId} - crce-plugin-api - 2.1.0 - - - ${project.groupId} - crce-repository-api - 2.2.0-SNAPSHOT - - - ${project.groupId} - crce-repository-impl - 2.2.0-SNAPSHOT - - - ${project.groupId} - crce-resolver-api - 2.2.0-SNAPSHOT - - - ${project.groupId} - crce-resolver-impl - 2.2.0-SNAPSHOT - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + crce-parent + 2.1.0 + + + + cz.zcu.kiv.crce + crce-core + 3.0.0-SNAPSHOT + pom + + CRCE - Core + + + https://github.com/ReliSA/crce/tree/master/core/crce-core + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-dao-api + 3.0.0-SNAPSHOT + + + ${project.groupId} + crce-metadata-dao-impl + 3.1.0-SNAPSHOT + + + ${project.groupId} + crce-metadata-impl + 3.0.0 + + + ${project.groupId} + crce-metadata-indexer-impl + 2.1.0 + + + ${project.groupId} + crce-metadata-indexer-api + 2.1.0 + + + ${project.groupId} + crce-metadata-json-api + 2.1.0 + + + ${project.groupId} + crce-metadata-json-impl + 3.0.0 + + + ${project.groupId} + crce-metadata-service-api + 3.0.0 + + + ${project.groupId} + crce-metadata-service-impl + 3.0.0 + + + ${project.groupId} + crce-plugin-api + 2.1.0 + + + ${project.groupId} + crce-repository-api + 2.2.0-SNAPSHOT + + + ${project.groupId} + crce-repository-impl + 2.2.0-SNAPSHOT + + + ${project.groupId} + crce-resolver-api + 2.2.0-SNAPSHOT + + + ${project.groupId} + crce-resolver-impl + 2.2.0-SNAPSHOT + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-api/osgi.bnd b/core/crce-metadata-api/osgi.bnd index 45e2fbac..7b6d3f4c 100644 --- a/core/crce-metadata-api/osgi.bnd +++ b/core/crce-metadata-api/osgi.bnd @@ -1,3 +1,3 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- diff --git a/core/crce-metadata-api/pom.xml b/core/crce-metadata-api/pom.xml index 303c5ec3..992f7cdd 100644 --- a/core/crce-metadata-api/pom.xml +++ b/core/crce-metadata-api/pom.xml @@ -1,67 +1,67 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-api - 3.0.1-SNAPSHOT - bundle - - CRCE - Core - Metadata API - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.api - ${namespace}.metadata - - - - - junit - junit - - - - - - - org.apache.maven.plugins - maven-pmd-plugin - - - **/legacy/*.java - **/internal/*.java - - - - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-api + 3.0.1-SNAPSHOT + bundle + + CRCE - Core - Metadata API + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.api + ${namespace}.metadata + + + + + junit + junit + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + + + **/legacy/*.java + **/internal/*.java + + + + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Attribute.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Attribute.java index 7cc85472..4d7fef71 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Attribute.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Attribute.java @@ -1,29 +1,29 @@ -package cz.zcu.kiv.crce.metadata; - -import javax.annotation.Nonnull; - -/** - * - * @param - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Attribute extends Entity { - - @Nonnull - String getName(); - - @Nonnull - Class getType(); - - @Nonnull - T getValue(); - - @Nonnull - String getStringValue(); - - @Nonnull - AttributeType getAttributeType(); - - @Nonnull - Operator getOperator(); -} +package cz.zcu.kiv.crce.metadata; + +import javax.annotation.Nonnull; + +/** + * + * @param + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Attribute extends Entity { + + @Nonnull + String getName(); + + @Nonnull + Class getType(); + + @Nonnull + T getValue(); + + @Nonnull + String getStringValue(); + + @Nonnull + AttributeType getAttributeType(); + + @Nonnull + Operator getOperator(); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeProvider.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeProvider.java index c3ad5f99..70066835 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeProvider.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeProvider.java @@ -1,49 +1,49 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Common interface for subclasses that can provide Attributes. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface AttributeProvider extends Serializable { - - @CheckForNull - Attribute getAttribute(AttributeType type); - - @CheckForNull - T getAttributeValue(AttributeType type); - - @CheckForNull - String getAttributeStringValue(AttributeType type); - - boolean setAttribute(AttributeType type, T value); - - boolean setAttribute(AttributeType type, T value, Operator operator); - - boolean setAttribute(String name, Class type, T value); - - boolean setAttribute(String name, Class type, T value, Operator operator); - - boolean setAttribute(Attribute attribute); - - boolean removeAttribute(Attribute attribute); - - boolean removeAttribute(AttributeType type); - - boolean removeAttribute(String name); - - @Nonnull - List> getAttributes(); - - @Nonnull - Map> getAttributesMap(); -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Common interface for subclasses that can provide Attributes. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface AttributeProvider extends Serializable { + + @CheckForNull + Attribute getAttribute(AttributeType type); + + @CheckForNull + T getAttributeValue(AttributeType type); + + @CheckForNull + String getAttributeStringValue(AttributeType type); + + boolean setAttribute(AttributeType type, T value); + + boolean setAttribute(AttributeType type, T value, Operator operator); + + boolean setAttribute(String name, Class type, T value); + + boolean setAttribute(String name, Class type, T value, Operator operator); + + boolean setAttribute(Attribute attribute); + + boolean removeAttribute(Attribute attribute); + + boolean removeAttribute(AttributeType type); + + boolean removeAttribute(String name); + + @Nonnull + List> getAttributes(); + + @Nonnull + Map> getAttributesMap(); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeType.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeType.java index eeae0c92..2e4e3f99 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeType.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/AttributeType.java @@ -1,19 +1,19 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; - -import javax.annotation.Nonnull; - -/** - * - * @param - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface AttributeType extends Serializable { - - @Nonnull - String getName(); - - @Nonnull - Class getType(); -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; + +import javax.annotation.Nonnull; + +/** + * + * @param + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface AttributeType extends Serializable { + + @Nonnull + String getName(); + + @Nonnull + Class getType(); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Capability.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Capability.java index f798a017..c04d4b70 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Capability.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Capability.java @@ -1,29 +1,29 @@ -package cz.zcu.kiv.crce.metadata; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Represents an Capability. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface Capability - extends AttributeProvider, DirectiveProvider, PropertyProvider, RequirementProvider, EqualityComparable, Entity { - - @Nonnull - String getId(); - - @Nonnull - String getNamespace(); - - boolean addChild(Capability capability); - - boolean removeChild(Capability capability); - - @Nonnull - List getChildren(); -} +package cz.zcu.kiv.crce.metadata; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Represents an Capability. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface Capability + extends AttributeProvider, DirectiveProvider, PropertyProvider, RequirementProvider, EqualityComparable, Entity { + + @Nonnull + String getId(); + + @Nonnull + String getNamespace(); + + boolean addChild(Capability capability); + + boolean removeChild(Capability capability); + + @Nonnull + List getChildren(); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/DirectiveProvider.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/DirectiveProvider.java index dda94af9..36e3f3ae 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/DirectiveProvider.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/DirectiveProvider.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; -import java.util.Map; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface DirectiveProvider extends Serializable { - - @CheckForNull - String getDirective(String name); - - @Nonnull - Map getDirectives(); - - boolean setDirective(String name, String directive); - - boolean unsetDirective(String name); -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; +import java.util.Map; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface DirectiveProvider extends Serializable { + + @CheckForNull + String getDirective(String name); + + @Nonnull + Map getDirectives(); + + boolean setDirective(String name, String directive); + + boolean unsetDirective(String name); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Entity.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Entity.java index 50e980e5..297ae4d1 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Entity.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Entity.java @@ -1,11 +1,11 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; - -/** - * Marker interface for Metadata entities. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Entity extends Serializable { -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; + +/** + * Marker interface for Metadata entities. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Entity extends Serializable { +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/EqualityComparable.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/EqualityComparable.java index 581f69ba..d16b8b73 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/EqualityComparable.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/EqualityComparable.java @@ -1,24 +1,24 @@ -package cz.zcu.kiv.crce.metadata; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -/** - * This interface allows comparison of implementing entities for their equality - * with custom level of equality depth. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - * @param - * @see EqualityLevel Explanation of equality levels. - */ -public interface EqualityComparable { - - /** - * Indicates whether some other object is "equal to" this one - * with custom level of comparison depth. - * @param other - * @param level - * @return - */ - boolean equalsTo(@CheckForNull T other, @Nonnull EqualityLevel level); -} +package cz.zcu.kiv.crce.metadata; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; + +/** + * This interface allows comparison of implementing entities for their equality + * with custom level of equality depth. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + * @param + * @see EqualityLevel Explanation of equality levels. + */ +public interface EqualityComparable { + + /** + * Indicates whether some other object is "equal to" this one + * with custom level of comparison depth. + * @param other + * @param level + * @return + */ + boolean equalsTo(@CheckForNull T other, @Nonnull EqualityLevel level); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/MetadataFactory.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/MetadataFactory.java index 13f3be89..0b3c1ee8 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/MetadataFactory.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/MetadataFactory.java @@ -1,107 +1,107 @@ -package cz.zcu.kiv.crce.metadata; - - -import java.net.URI; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Creates empty metadata entities. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface MetadataFactory { - - /** - * Creates an empty resource with generated unique ID. - * @return An empty resource. - */ - @Nonnull - Resource createResource(); - - /** - * Creates an empty resource with the given ID. - * @param id Unique identifier. - * @return An empty resource. - */ - @Nonnull - Resource createResource(String id); - - /** - * Creates an empty requirement with given name. - * @param namespace Name of created requirement. - * @return An empty capability. - */ - @Nonnull - Requirement createRequirement(String namespace); - - /** - * Creates an empty requirement with given name. - * @param namespace Name of created requirement. - * @param id - * @return An empty capability. - */ - @Nonnull - Requirement createRequirement(String namespace, String id); - - @Nonnull - Capability createCapability(String namespace); - - @Nonnull - Capability createCapability(String namespace, String id); - - @Nonnull - Property createProperty(String namespace); - - @Nonnull - Property createProperty(String namespace, String id); - - Attribute createAttribute(AttributeType type, T value); - - Attribute createAttribute(AttributeType type, T value, Operator operator); - - Attribute createAttribute(String name, Class type, T value); - - Attribute createAttribute(String name, Class type, T value, Operator operator); - - @Nonnull - Repository createRepository(URI uri); - - @Nonnull - Repository createRepository(URI uri, String id); - - /** - * Clone the given resource and return it's deep copy. - * - *

Don't forget about that the implementation of the given resource - * could be various, so you don't know whether the given resource is a plain - * resource or some kind of combined resource (more resources acting as one - * resource). The clone made by this method (if concrete implementation does - * not specify it differently) is a plain resource so the inner structure - * could be another then the structure of the given resource. Use this - * method only if you are sure that you want to get a plain resource. - * - * @param resource Resource to be clonned. - * @return deep copy of resource. - */ - @Nonnull - Resource cloneResource(Resource resource); - - /** - * Creates an empty capability with given name. - * @param capability Cloned capability. - * @return An empty capability. - */ - @Nonnull - Capability cloneCapability(Capability capability); - - @Nonnull - Requirement cloneRequirement(Requirement requirement); - - Attribute cloneAttribute(Attribute attribute); - - @Nonnull - Property cloneProperty(Property property); -} +package cz.zcu.kiv.crce.metadata; + + +import java.net.URI; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Creates empty metadata entities. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface MetadataFactory { + + /** + * Creates an empty resource with generated unique ID. + * @return An empty resource. + */ + @Nonnull + Resource createResource(); + + /** + * Creates an empty resource with the given ID. + * @param id Unique identifier. + * @return An empty resource. + */ + @Nonnull + Resource createResource(String id); + + /** + * Creates an empty requirement with given name. + * @param namespace Name of created requirement. + * @return An empty capability. + */ + @Nonnull + Requirement createRequirement(String namespace); + + /** + * Creates an empty requirement with given name. + * @param namespace Name of created requirement. + * @param id + * @return An empty capability. + */ + @Nonnull + Requirement createRequirement(String namespace, String id); + + @Nonnull + Capability createCapability(String namespace); + + @Nonnull + Capability createCapability(String namespace, String id); + + @Nonnull + Property createProperty(String namespace); + + @Nonnull + Property createProperty(String namespace, String id); + + Attribute createAttribute(AttributeType type, T value); + + Attribute createAttribute(AttributeType type, T value, Operator operator); + + Attribute createAttribute(String name, Class type, T value); + + Attribute createAttribute(String name, Class type, T value, Operator operator); + + @Nonnull + Repository createRepository(URI uri); + + @Nonnull + Repository createRepository(URI uri, String id); + + /** + * Clone the given resource and return it's deep copy. + * + *

Don't forget about that the implementation of the given resource + * could be various, so you don't know whether the given resource is a plain + * resource or some kind of combined resource (more resources acting as one + * resource). The clone made by this method (if concrete implementation does + * not specify it differently) is a plain resource so the inner structure + * could be another then the structure of the given resource. Use this + * method only if you are sure that you want to get a plain resource. + * + * @param resource Resource to be clonned. + * @return deep copy of resource. + */ + @Nonnull + Resource cloneResource(Resource resource); + + /** + * Creates an empty capability with given name. + * @param capability Cloned capability. + * @return An empty capability. + */ + @Nonnull + Capability cloneCapability(Capability capability); + + @Nonnull + Requirement cloneRequirement(Requirement requirement); + + Attribute cloneAttribute(Attribute attribute); + + @Nonnull + Property cloneProperty(Property property); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Property.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Property.java index 2e79f3d3..15845180 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Property.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Property.java @@ -1,17 +1,17 @@ -package cz.zcu.kiv.crce.metadata; - - -import javax.annotation.Nonnull; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Property extends AttributeProvider, EqualityComparable, Entity { - - @Nonnull - String getId(); - - @Nonnull - String getNamespace(); -} +package cz.zcu.kiv.crce.metadata; + + +import javax.annotation.Nonnull; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Property extends AttributeProvider, EqualityComparable, Entity { + + @Nonnull + String getId(); + + @Nonnull + String getNamespace(); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/PropertyProvider.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/PropertyProvider.java index 5e0c43ed..d8a08c38 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/PropertyProvider.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/PropertyProvider.java @@ -1,27 +1,27 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface PropertyProvider extends Entity, Serializable { - - @Nonnull - List getProperties(); - - @Nonnull - List getProperties(String namespace); - - boolean hasProperty(Property property); - - void addProperty(Property property); - - void removeProperty(Property property); -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface PropertyProvider extends Entity, Serializable { + + @Nonnull + List getProperties(); + + @Nonnull + List getProperties(String namespace); + + boolean hasProperty(Property property); + + void addProperty(Property property); + + void removeProperty(Property property); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Repository.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Repository.java index 35959d49..9c317c86 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Repository.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Repository.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.metadata; - -import java.net.URI; - -import javax.annotation.Nonnull; - -/** - * Descriptor of resources storage. - * - * PENDING Attributes and directives could be added instead of hard-coded ones like URI. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Repository extends Entity { - - @Nonnull - String getId(); - - /** - * Return the associated URL for the repository. - * - * @return - */ - @Nonnull - URI getUri(); +package cz.zcu.kiv.crce.metadata; + +import java.net.URI; + +import javax.annotation.Nonnull; + +/** + * Descriptor of resources storage. + * + * PENDING Attributes and directives could be added instead of hard-coded ones like URI. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Repository extends Entity { + + @Nonnull + String getId(); + + /** + * Return the associated URL for the repository. + * + * @return + */ + @Nonnull + URI getUri(); } \ No newline at end of file diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Requirement.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Requirement.java index 820e1aaf..cbc6204b 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Requirement.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Requirement.java @@ -1,49 +1,49 @@ -package cz.zcu.kiv.crce.metadata; - -import java.util.List; -import java.util.Map; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Represents a requirement to a capability with the same name. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface Requirement extends DirectiveProvider, EqualityComparable, Entity { - - @Nonnull - String getId(); - - @Nonnull - String getNamespace(); - - boolean addChild(Requirement requirement); - - boolean removeChild(Requirement requirement); - - @Nonnull - List getChildren(); - - @Nonnull - List> getAttributes(); - - @Nonnull - Map>> getAttributesMap(); - - @Nonnull - List> getAttributes(AttributeType type); - - boolean addAttribute(AttributeType type, T value); - - boolean addAttribute(AttributeType type, T value, Operator operator); - - // TODO is this method AttributeType implementation-safe? - boolean addAttribute(String name, Class type, T value); - - boolean addAttribute(String name, Class type, T value, Operator operator); - - boolean addAttribute(Attribute attribute); -} +package cz.zcu.kiv.crce.metadata; + +import java.util.List; +import java.util.Map; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Represents a requirement to a capability with the same name. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface Requirement extends DirectiveProvider, EqualityComparable, Entity { + + @Nonnull + String getId(); + + @Nonnull + String getNamespace(); + + boolean addChild(Requirement requirement); + + boolean removeChild(Requirement requirement); + + @Nonnull + List getChildren(); + + @Nonnull + List> getAttributes(); + + @Nonnull + Map>> getAttributesMap(); + + @Nonnull + List> getAttributes(AttributeType type); + + boolean addAttribute(AttributeType type, T value); + + boolean addAttribute(AttributeType type, T value, Operator operator); + + // TODO is this method AttributeType implementation-safe? + boolean addAttribute(String name, Class type, T value); + + boolean addAttribute(String name, Class type, T value, Operator operator); + + boolean addAttribute(Attribute attribute); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/RequirementProvider.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/RequirementProvider.java index 2211c702..2b9c674f 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/RequirementProvider.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/RequirementProvider.java @@ -1,25 +1,25 @@ -package cz.zcu.kiv.crce.metadata; - -import java.io.Serializable; -import java.util.List; - -import javax.annotation.Nonnull; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface RequirementProvider extends Entity, Serializable { - - @Nonnull - List getRequirements(); - - @Nonnull - List getRequirements(String namespace); - - boolean hasRequirement(Requirement requirement); - - void addRequirement(Requirement requirement); - - void removeRequirement(Requirement requirement); -} +package cz.zcu.kiv.crce.metadata; + +import java.io.Serializable; +import java.util.List; + +import javax.annotation.Nonnull; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface RequirementProvider extends Entity, Serializable { + + @Nonnull + List getRequirements(); + + @Nonnull + List getRequirements(String namespace); + + boolean hasRequirement(Requirement requirement); + + void addRequirement(Requirement requirement); + + void removeRequirement(Requirement requirement); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Resource.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Resource.java index 7f3d9fcc..29eb56ee 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Resource.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/Resource.java @@ -1,55 +1,55 @@ -package cz.zcu.kiv.crce.metadata; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Resource represents an artifact and it's metadata. - * - *

An unique identificator of a resource is ID. - * - *

Resource have capabilities, requirements, properties and categories. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface Resource extends PropertyProvider, RequirementProvider, EqualityComparable, Entity { - - @Nonnull - String getId(); - - @Nonnull - List getCapabilities(); - - @Nonnull - List getCapabilities(String namespace); - - @Nonnull - List getRootCapabilities(); - - @Nonnull - List getRootCapabilities(String namespace); - - boolean hasCapability(Capability capability); - - /* --- setters --- */ - - /** - * Adds the given capability to the list of all capabilities. - *

Note: This method doesn't add the capability to the list of root capabilities. - * @param capability Capability to be added. - */ - void addCapability(Capability capability); - - /** - * Adds the given capability to the list of root capabilities. - * @param capability Capability to be added. - */ - void addRootCapability(Capability capability); - - void removeCapability(Capability capability); - - void removeRootCapability(Capability capability); -} +package cz.zcu.kiv.crce.metadata; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Resource represents an artifact and it's metadata. + * + *

An unique identificator of a resource is ID. + * + *

Resource have capabilities, requirements, properties and categories. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface Resource extends PropertyProvider, RequirementProvider, EqualityComparable, Entity { + + @Nonnull + String getId(); + + @Nonnull + List getCapabilities(); + + @Nonnull + List getCapabilities(String namespace); + + @Nonnull + List getRootCapabilities(); + + @Nonnull + List getRootCapabilities(String namespace); + + boolean hasCapability(Capability capability); + + /* --- setters --- */ + + /** + * Adds the given capability to the list of all capabilities. + *

Note: This method doesn't add the capability to the list of root capabilities. + * @param capability Capability to be added. + */ + void addCapability(Capability capability); + + /** + * Adds the given capability to the list of root capabilities. + * @param capability Capability to be added. + */ + void addRootCapability(Capability capability); + + void removeCapability(Capability capability); + + void removeRootCapability(Capability capability); +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/GenericAttributeType.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/GenericAttributeType.java index 76370362..b5fde2ce 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/GenericAttributeType.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/GenericAttributeType.java @@ -1,90 +1,90 @@ -package cz.zcu.kiv.crce.metadata.impl; - -import java.net.URI; -import java.util.List; -import java.util.Objects; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class GenericAttributeType implements AttributeType { - - private static final long serialVersionUID = -4513168310428826310L; - - private String name; - private Class type; - - public GenericAttributeType(String name, String type) { - this.name = name; - switch (type) { - default: - case "String": - case "java.lang.String": - this.type = String.class; - break; - - case "Long": - case "java.lang.Long": - this.type = Long.class; - break; - - case "Double": - case "java.lang.Double": - this.type = Double.class; - break; - - case "Version": - case "cz.zcu.kiv.crce.metadata.type.Version": - this.type = Version.class; - break; - - case "List": - case "java.util.List": - this.type = List.class; - break; - - case "URI": - case "java.net.URI": - this.type = URI.class; - break; - } - } - - @Override - public String getName() { - return name; - } - - @Override - @SuppressWarnings("unchecked") - public Class getType() { - return (Class) type; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 29 * hash + Objects.hashCode(this.name); - hash = 29 * hash + Objects.hashCode(this.type); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AttributeType)) { - return false; - } - final AttributeType other = (AttributeType) obj; - if (!Objects.equals(this.name, other.getName())) { - return false; - } - return Objects.equals(this.type, other.getType()); - } -} +package cz.zcu.kiv.crce.metadata.impl; + +import java.net.URI; +import java.util.List; +import java.util.Objects; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class GenericAttributeType implements AttributeType { + + private static final long serialVersionUID = -4513168310428826310L; + + private String name; + private Class type; + + public GenericAttributeType(String name, String type) { + this.name = name; + switch (type) { + default: + case "String": + case "java.lang.String": + this.type = String.class; + break; + + case "Long": + case "java.lang.Long": + this.type = Long.class; + break; + + case "Double": + case "java.lang.Double": + this.type = Double.class; + break; + + case "Version": + case "cz.zcu.kiv.crce.metadata.type.Version": + this.type = Version.class; + break; + + case "List": + case "java.util.List": + this.type = List.class; + break; + + case "URI": + case "java.net.URI": + this.type = URI.class; + break; + } + } + + @Override + public String getName() { + return name; + } + + @Override + @SuppressWarnings("unchecked") + public Class getType() { + return (Class) type; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 29 * hash + Objects.hashCode(this.name); + hash = 29 * hash + Objects.hashCode(this.type); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof AttributeType)) { + return false; + } + final AttributeType other = (AttributeType) obj; + if (!Objects.equals(this.name, other.getName())) { + return false; + } + return Objects.equals(this.type, other.getType()); + } +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/ListAttributeType.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/ListAttributeType.java index cbf641bd..9abbe504 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/ListAttributeType.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/ListAttributeType.java @@ -1,56 +1,56 @@ -package cz.zcu.kiv.crce.metadata.impl; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import java.util.List; -import java.util.Objects; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ListAttributeType implements AttributeType> { - - private static final long serialVersionUID = -8744638498345181727L; - - private final String name; - private final Class> type; - - @SuppressWarnings("unchecked") - public ListAttributeType(String name) { - this.name = name; - this.type = (Class>) (Class) List.class; - } - - @Override - public String getName() { - return name; - } - - @Override - public Class> getType() { - return type; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 29 * hash + Objects.hashCode(this.name); - hash = 29 * hash + Objects.hashCode(this.type); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AttributeType)) { - return false; - } - final AttributeType other = (AttributeType) obj; - if (!Objects.equals(this.name, other.getName())) { - return false; - } - return Objects.equals(this.type, other.getType()); - } -} +package cz.zcu.kiv.crce.metadata.impl; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import java.util.List; +import java.util.Objects; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ListAttributeType implements AttributeType> { + + private static final long serialVersionUID = -8744638498345181727L; + + private final String name; + private final Class> type; + + @SuppressWarnings("unchecked") + public ListAttributeType(String name) { + this.name = name; + this.type = (Class>) (Class) List.class; + } + + @Override + public String getName() { + return name; + } + + @Override + public Class> getType() { + return type; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 29 * hash + Objects.hashCode(this.name); + hash = 29 * hash + Objects.hashCode(this.type); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof AttributeType)) { + return false; + } + final AttributeType other = (AttributeType) obj; + if (!Objects.equals(this.name, other.getName())) { + return false; + } + return Objects.equals(this.type, other.getType()); + } +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/SimpleAttributeType.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/SimpleAttributeType.java index fbc726c7..44e673b8 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/SimpleAttributeType.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/impl/SimpleAttributeType.java @@ -1,58 +1,58 @@ -package cz.zcu.kiv.crce.metadata.impl; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import java.util.Objects; - -/** - * - * @param Data type of property. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class SimpleAttributeType implements AttributeType { - - private static final long serialVersionUID = 3314060433636463265L; - - private String name; - private Class type; - - public SimpleAttributeType(String name, Class type) { - if (name == null) { - throw new IllegalArgumentException("Name must be specified."); - } - this.name = name; - this.type = type; - } - - @Override - public String getName() { - return name; - } - - @Override - public Class getType() { - return type; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 29 * hash + Objects.hashCode(this.name); - hash = 29 * hash + Objects.hashCode(this.type); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AttributeType)) { - return false; - } - final AttributeType other = (AttributeType) obj; - if (!Objects.equals(this.name, other.getName())) { - return false; - } - return Objects.equals(this.type, other.getType()); - } -} +package cz.zcu.kiv.crce.metadata.impl; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import java.util.Objects; + +/** + * + * @param Data type of property. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class SimpleAttributeType implements AttributeType { + + private static final long serialVersionUID = 3314060433636463265L; + + private String name; + private Class type; + + public SimpleAttributeType(String name, Class type) { + if (name == null) { + throw new IllegalArgumentException("Name must be specified."); + } + this.name = name; + this.type = type; + } + + @Override + public String getName() { + return name; + } + + @Override + public Class getType() { + return type; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 29 * hash + Objects.hashCode(this.name); + hash = 29 * hash + Objects.hashCode(this.type); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof AttributeType)) { + return false; + } + final AttributeType other = (AttributeType) obj; + if (!Objects.equals(this.name, other.getName())) { + return false; + } + return Objects.equals(this.type, other.getType()); + } +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/internal/Example.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/internal/Example.java index e8ccda5c..31e713f5 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/internal/Example.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/internal/Example.java @@ -1,65 +1,65 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.List; -import java.util.Map; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * Not working demonstration of API usage. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value={"DLS_DEAD_LOCAL_STORE", "NP_ALWAYS_NULL"}, justification="Just a non-runnable example.") -public class Example { - - private static final AttributeType ATTRIBUTE_A = new SimpleAttributeType<>("long.attribute", Long.class); - private static final AttributeType ATTRIBUTE_B = new SimpleAttributeType<>("double.attribute", Double.class); - - - @SuppressWarnings({"null", "ConstantConditions"}) - public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - - Capability capability = null; - - // get attribute - type safe - Attribute attribute = capability.getAttribute(ATTRIBUTE_A); - Long value = attribute.getValue(); - AttributeType type = attribute.getAttributeType(); - Class type1 = type.getType(); - - // get attribute value directly - type safe - value = capability.getAttributeValue(ATTRIBUTE_A); - - String attributeStringValue = capability.getAttributeStringValue(ATTRIBUTE_A); - - // set attribute - type safe - capability.setAttribute(ATTRIBUTE_B, new Double("0.0")); - capability.setAttribute(ATTRIBUTE_B, 1.); - - // iteration - unknown data types - for (Attribute attr : capability.getAttributes()) { - attr.getAttributeType(); - Attribute attribute1 = capability.getAttribute(attr.getAttributeType()); - } - // map of attributes - unknown data types - Map> map = capability.getAttributesMap(); - Attribute attribute2 = map.get(ATTRIBUTE_A.getName()); - Object value2 = attribute2.getValue(); - - // a similar for requirements - Requirement requirement = null; - - List> attribute3 = requirement.getAttributes(ATTRIBUTE_B); - - Operator operator = attribute3.get(0).getOperator(); - - // etc. - - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.List; +import java.util.Map; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * Not working demonstration of API usage. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value={"DLS_DEAD_LOCAL_STORE", "NP_ALWAYS_NULL"}, justification="Just a non-runnable example.") +public class Example { + + private static final AttributeType ATTRIBUTE_A = new SimpleAttributeType<>("long.attribute", Long.class); + private static final AttributeType ATTRIBUTE_B = new SimpleAttributeType<>("double.attribute", Double.class); + + + @SuppressWarnings({"null", "ConstantConditions"}) + public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + + Capability capability = null; + + // get attribute - type safe + Attribute attribute = capability.getAttribute(ATTRIBUTE_A); + Long value = attribute.getValue(); + AttributeType type = attribute.getAttributeType(); + Class type1 = type.getType(); + + // get attribute value directly - type safe + value = capability.getAttributeValue(ATTRIBUTE_A); + + String attributeStringValue = capability.getAttributeStringValue(ATTRIBUTE_A); + + // set attribute - type safe + capability.setAttribute(ATTRIBUTE_B, new Double("0.0")); + capability.setAttribute(ATTRIBUTE_B, 1.); + + // iteration - unknown data types + for (Attribute attr : capability.getAttributes()) { + attr.getAttributeType(); + Attribute attribute1 = capability.getAttribute(attr.getAttributeType()); + } + // map of attributes - unknown data types + Map> map = capability.getAttributesMap(); + Attribute attribute2 = map.get(ATTRIBUTE_A.getName()); + Object value2 = attribute2.getValue(); + + // a similar for requirements + Requirement requirement = null; + + List> attribute3 = requirement.getAttributes(ATTRIBUTE_B); + + Operator operator = attribute3.get(0).getOperator(); + + // etc. + + } +} diff --git a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/namespace/NsCrceIdentity.java b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/namespace/NsCrceIdentity.java index fdef00a2..08cc6baa 100644 --- a/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/namespace/NsCrceIdentity.java +++ b/core/crce-metadata-api/src/main/java/cz/zcu/kiv/crce/metadata/namespace/NsCrceIdentity.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.metadata.namespace; - -import java.net.URI; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * CRCE metadata namespace for managing resource identity and internal CRCE information. - * - * Date: 10.5.15 - * - * @author Jakub Danek - * @since 3.0.0 - * @version 3.0.0 - */ -public final class NsCrceIdentity { - - public static final String NAMESPACE__CRCE_IDENTITY = "crce.identity"; - - public static final AttributeType ATTRIBUTE__EXTERNAL_ID = new SimpleAttributeType<>("external-id", String.class); - public static final AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); - public static final AttributeType ATTRIBUTE__URI = new SimpleAttributeType<>("uri", URI.class); - public static final AttributeType ATTRIBUTE__FILE_NAME = new SimpleAttributeType<>("file-name", String.class); - public static final AttributeType ATTRIBUTE__SIZE = new SimpleAttributeType<>("size", Long.class); - public static final AttributeType ATTRIBUTE__VERSION = new SimpleAttributeType<>("version", Version.class); - - public static final AttributeType> ATTRIBUTE__TYPES = new ListAttributeType("types"); - public static final AttributeType> ATTRIBUTE__CATEGORIES = new ListAttributeType("categories"); - - private NsCrceIdentity() { - } -} +package cz.zcu.kiv.crce.metadata.namespace; + +import java.net.URI; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * CRCE metadata namespace for managing resource identity and internal CRCE information. + * + * Date: 10.5.15 + * + * @author Jakub Danek + * @since 3.0.0 + * @version 3.0.0 + */ +public final class NsCrceIdentity { + + public static final String NAMESPACE__CRCE_IDENTITY = "crce.identity"; + + public static final AttributeType ATTRIBUTE__EXTERNAL_ID = new SimpleAttributeType<>("external-id", String.class); + public static final AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); + public static final AttributeType ATTRIBUTE__URI = new SimpleAttributeType<>("uri", URI.class); + public static final AttributeType ATTRIBUTE__FILE_NAME = new SimpleAttributeType<>("file-name", String.class); + public static final AttributeType ATTRIBUTE__SIZE = new SimpleAttributeType<>("size", Long.class); + public static final AttributeType ATTRIBUTE__VERSION = new SimpleAttributeType<>("version", Version.class); + + public static final AttributeType> ATTRIBUTE__TYPES = new ListAttributeType("types"); + public static final AttributeType> ATTRIBUTE__CATEGORIES = new ListAttributeType("categories"); + + private NsCrceIdentity() { + } +} diff --git a/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd b/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd index d035a1e2..d63b63f4 100644 --- a/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd +++ b/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd @@ -1,257 +1,257 @@ - - - - - - - - - - - - - - - The name of the repository. The name may contain - spaces and punctuation. - - - - - - - An indication of when the repository was last changed. Clients can - check whether the repository has been updated by checking this increment value. - - - - - - - CRCE ID of the repository. - - - - - - - - - - Describes a general resource with requirements and capabilities. - - - - - - - - - - - - CRCE ID of the resource. - - - - - - - - - A named set of type attributes and directives. A capability can be - used to resolve a requirement if the resource is included. - - - - - - - - - - - - - Name space of the capability. Only requirements with the - same name space must be able to match this capability. - - - - - - - CRCE ID of the capability. - - - - - - - - - - A filter on a named set of capability attributes. - - - - - - - - - - - - Name space of the requirement. Only capabilities within the - same name space must be able to match this requirement. - - - - - - - CRCE ID of the requirement. - - - - - - - - - - A filter on a named set of property attributes. - - - - - - - - - - - - - Name space of the property. - - - - - - - CRCE ID of the property. - - - - - - - - - - A named value with an optional type that decorates - a requirement or capability. - - - - - - - - - The name of the attribute. - - - - - - - The value of the attribute. - - - - - - - The type of the attribute. - - - - - - - The operator of the attribute. - - - - - - - - - - A named value of type string that instructs a resolver - how to process a requirement or capability. - - - - - - - - - The name of the directive. - - - - - - - The value of the directive. - - - - - - - - - - A link. - - - - - - - - - The link relationship. - - - - - - - The link type. - - - - - - - The link name. - - - - - - - + + + + + + + + + + + + + + + The name of the repository. The name may contain + spaces and punctuation. + + + + + + + An indication of when the repository was last changed. Clients can + check whether the repository has been updated by checking this increment value. + + + + + + + CRCE ID of the repository. + + + + + + + + + + Describes a general resource with requirements and capabilities. + + + + + + + + + + + + CRCE ID of the resource. + + + + + + + + + A named set of type attributes and directives. A capability can be + used to resolve a requirement if the resource is included. + + + + + + + + + + + + + Name space of the capability. Only requirements with the + same name space must be able to match this capability. + + + + + + + CRCE ID of the capability. + + + + + + + + + + A filter on a named set of capability attributes. + + + + + + + + + + + + Name space of the requirement. Only capabilities within the + same name space must be able to match this requirement. + + + + + + + CRCE ID of the requirement. + + + + + + + + + + A filter on a named set of property attributes. + + + + + + + + + + + + + Name space of the property. + + + + + + + CRCE ID of the property. + + + + + + + + + + A named value with an optional type that decorates + a requirement or capability. + + + + + + + + + The name of the attribute. + + + + + + + The value of the attribute. + + + + + + + The type of the attribute. + + + + + + + The operator of the attribute. + + + + + + + + + + A named value of type string that instructs a resolver + how to process a requirement or capability. + + + + + + + + + The name of the directive. + + + + + + + The value of the directive. + + + + + + + + + + A link. + + + + + + + + + The link relationship. + + + + + + + The link type. + + + + + + + The link name. + + + + + + + diff --git a/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.1.0.xsd b/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.1.0.xsd index 16974a05..fb70d1dc 100644 --- a/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.1.0.xsd +++ b/core/crce-metadata-api/src/main/resources/cz/zcu/kiv/crce/metadata/schema/metadata-1.1.0.xsd @@ -1,258 +1,258 @@ - - - - - - - - - - - - - - - The name of the repository. The name may contain - spaces and punctuation. - - - - - - - An indication of when the repository was last changed. Clients can - check whether the repository has been updated by checking this increment value. - - - - - - - CRCE ID of the repository. - - - - - - - - - - Describes a general resource with requirements and capabilities. - - - - - - - - - - - - CRCE ID of the resource. - - - - - - - - - A named set of type attributes and directives. A capability can be - used to resolve a requirement if the resource is included. - - - - - - - - - - - - - - Name space of the capability. Only requirements with the - same name space must be able to match this capability. - - - - - - - CRCE ID of the capability. - - - - - - - - - - A filter on a named set of capability attributes. - - - - - - - - - - - - Name space of the requirement. Only capabilities within the - same name space must be able to match this requirement. - - - - - - - CRCE ID of the requirement. - - - - - - - - - - A filter on a named set of property attributes. - - - - - - - - - - - - - Name space of the property. - - - - - - - CRCE ID of the property. - - - - - - - - - - A named value with an optional type that decorates - a requirement or capability. - - - - - - - - - The name of the attribute. - - - - - - - The value of the attribute. - - - - - - - The type of the attribute. - - - - - - - The operator of the attribute. - - - - - - - - - - A named value of type string that instructs a resolver - how to process a requirement or capability. - - - - - - - - - The name of the directive. - - - - - - - The value of the directive. - - - - - - - - - - A link. - - - - - - - - - The link relationship. - - - - - - - The link type. - - - - - - - The link name. - - - - - - - + + + + + + + + + + + + + + + The name of the repository. The name may contain + spaces and punctuation. + + + + + + + An indication of when the repository was last changed. Clients can + check whether the repository has been updated by checking this increment value. + + + + + + + CRCE ID of the repository. + + + + + + + + + + Describes a general resource with requirements and capabilities. + + + + + + + + + + + + CRCE ID of the resource. + + + + + + + + + A named set of type attributes and directives. A capability can be + used to resolve a requirement if the resource is included. + + + + + + + + + + + + + + Name space of the capability. Only requirements with the + same name space must be able to match this capability. + + + + + + + CRCE ID of the capability. + + + + + + + + + + A filter on a named set of capability attributes. + + + + + + + + + + + + Name space of the requirement. Only capabilities within the + same name space must be able to match this requirement. + + + + + + + CRCE ID of the requirement. + + + + + + + + + + A filter on a named set of property attributes. + + + + + + + + + + + + + Name space of the property. + + + + + + + CRCE ID of the property. + + + + + + + + + + A named value with an optional type that decorates + a requirement or capability. + + + + + + + + + The name of the attribute. + + + + + + + The value of the attribute. + + + + + + + The type of the attribute. + + + + + + + The operator of the attribute. + + + + + + + + + + A named value of type string that instructs a resolver + how to process a requirement or capability. + + + + + + + + + The name of the directive. + + + + + + + The value of the directive. + + + + + + + + + + A link. + + + + + + + + + The link relationship. + + + + + + + The link type. + + + + + + + The link name. + + + + + + + diff --git a/core/crce-metadata-api/src/test/java/cz/zcu/kiv/crce/metadata/impl/AttributeTypesTest.java b/core/crce-metadata-api/src/test/java/cz/zcu/kiv/crce/metadata/impl/AttributeTypesTest.java index 49b80c7b..2fe2aa49 100644 --- a/core/crce-metadata-api/src/test/java/cz/zcu/kiv/crce/metadata/impl/AttributeTypesTest.java +++ b/core/crce-metadata-api/src/test/java/cz/zcu/kiv/crce/metadata/impl/AttributeTypesTest.java @@ -1,66 +1,66 @@ -package cz.zcu.kiv.crce.metadata.impl; - -import static org.junit.Assert.*; - -import java.util.List; -import org.junit.Test; - -import cz.zcu.kiv.crce.metadata.AttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class AttributeTypesTest { - - private static final AttributeType SIMPLE_LONG_A = new SimpleAttributeType<>("long.a", Long.class); - private static final AttributeType SIMPLE_LONG_A_1 = new SimpleAttributeType<>("long.a", Long.class); - private static final AttributeType SIMPLE_LONG_A_DBL = new SimpleAttributeType<>("long.a", Double.class); - private static final AttributeType SIMPLE_LONG_B = new SimpleAttributeType<>("long.b", Long.class); - - private static final AttributeType GENERIC_LONG_A = new GenericAttributeType("long.a", "Long"); - private static final AttributeType GENERIC_LONG_A_1 = new GenericAttributeType("long.a", "Long"); - private static final AttributeType GENERIC_LONG_A_DBL = new GenericAttributeType("long.a", "Double"); - private static final AttributeType GENERIC_LONG_B = new GenericAttributeType("long.b", "Long"); - - private static final AttributeType> LIST_A = new ListAttributeType("list.a"); - private static final AttributeType> LIST_A_1 = new ListAttributeType("list.a"); - private static final AttributeType> LIST_LONG_A = new ListAttributeType("long.a"); - private static final AttributeType> LIST_B = new ListAttributeType("list.b"); - - @Test - public void testSimpleAttributeTypesByName() { - assertEquals(SIMPLE_LONG_A, SIMPLE_LONG_A_1); - assertNotEquals(SIMPLE_LONG_A, SIMPLE_LONG_B); - } - - @Test - public void testSimpleAttributeTypesByType() { - assertNotEquals(SIMPLE_LONG_A, SIMPLE_LONG_A_DBL); - } - - @Test - public void testGenericAttributeTypesByName() { - assertEquals(GENERIC_LONG_A, GENERIC_LONG_A_1); - assertNotEquals(GENERIC_LONG_A, GENERIC_LONG_B); - } - - @Test - public void testGenericAttributeTypesByType() { - assertNotEquals(GENERIC_LONG_A, GENERIC_LONG_A_DBL); - } - - @Test - public void testListAttributeTypesByName() { - assertEquals(LIST_A, LIST_A_1); - assertNotEquals(LIST_A, LIST_B); - } - - @Test - public void testAttributeTypesTogether() { - assertEquals(SIMPLE_LONG_A, GENERIC_LONG_A); - assertNotEquals(SIMPLE_LONG_A, GENERIC_LONG_A_DBL); - assertNotEquals(SIMPLE_LONG_A, LIST_LONG_A); - assertNotEquals(GENERIC_LONG_A, LIST_LONG_A); - } -} +package cz.zcu.kiv.crce.metadata.impl; + +import static org.junit.Assert.*; + +import java.util.List; +import org.junit.Test; + +import cz.zcu.kiv.crce.metadata.AttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class AttributeTypesTest { + + private static final AttributeType SIMPLE_LONG_A = new SimpleAttributeType<>("long.a", Long.class); + private static final AttributeType SIMPLE_LONG_A_1 = new SimpleAttributeType<>("long.a", Long.class); + private static final AttributeType SIMPLE_LONG_A_DBL = new SimpleAttributeType<>("long.a", Double.class); + private static final AttributeType SIMPLE_LONG_B = new SimpleAttributeType<>("long.b", Long.class); + + private static final AttributeType GENERIC_LONG_A = new GenericAttributeType("long.a", "Long"); + private static final AttributeType GENERIC_LONG_A_1 = new GenericAttributeType("long.a", "Long"); + private static final AttributeType GENERIC_LONG_A_DBL = new GenericAttributeType("long.a", "Double"); + private static final AttributeType GENERIC_LONG_B = new GenericAttributeType("long.b", "Long"); + + private static final AttributeType> LIST_A = new ListAttributeType("list.a"); + private static final AttributeType> LIST_A_1 = new ListAttributeType("list.a"); + private static final AttributeType> LIST_LONG_A = new ListAttributeType("long.a"); + private static final AttributeType> LIST_B = new ListAttributeType("list.b"); + + @Test + public void testSimpleAttributeTypesByName() { + assertEquals(SIMPLE_LONG_A, SIMPLE_LONG_A_1); + assertNotEquals(SIMPLE_LONG_A, SIMPLE_LONG_B); + } + + @Test + public void testSimpleAttributeTypesByType() { + assertNotEquals(SIMPLE_LONG_A, SIMPLE_LONG_A_DBL); + } + + @Test + public void testGenericAttributeTypesByName() { + assertEquals(GENERIC_LONG_A, GENERIC_LONG_A_1); + assertNotEquals(GENERIC_LONG_A, GENERIC_LONG_B); + } + + @Test + public void testGenericAttributeTypesByType() { + assertNotEquals(GENERIC_LONG_A, GENERIC_LONG_A_DBL); + } + + @Test + public void testListAttributeTypesByName() { + assertEquals(LIST_A, LIST_A_1); + assertNotEquals(LIST_A, LIST_B); + } + + @Test + public void testAttributeTypesTogether() { + assertEquals(SIMPLE_LONG_A, GENERIC_LONG_A); + assertNotEquals(SIMPLE_LONG_A, GENERIC_LONG_A_DBL); + assertNotEquals(SIMPLE_LONG_A, LIST_LONG_A); + assertNotEquals(GENERIC_LONG_A, LIST_LONG_A); + } +} diff --git a/core/crce-metadata-dao-api/osgi.bnd b/core/crce-metadata-dao-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-metadata-dao-api/osgi.bnd +++ b/core/crce-metadata-dao-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-metadata-dao-api/pom.xml b/core/crce-metadata-dao-api/pom.xml index 483bcd54..4297b1a4 100644 --- a/core/crce-metadata-dao-api/pom.xml +++ b/core/crce-metadata-dao-api/pom.xml @@ -1,56 +1,56 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1-SNAPSHOT - - - - crce-metadata-dao-api - 3.0.0-SNAPSHOT - bundle - - CRCE - Core - Metadata DAO API - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-dao-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.dao.api - ${namespace}.metadata.dao - - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1-SNAPSHOT + + + + crce-metadata-dao-api + 3.0.0-SNAPSHOT + bundle + + CRCE - Core - Metadata DAO API + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-dao-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.dao.api + ${namespace}.metadata.dao + + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/RepositoryDAO.java b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/RepositoryDAO.java index 58c6aa01..64eed13d 100644 --- a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/RepositoryDAO.java +++ b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/RepositoryDAO.java @@ -1,43 +1,43 @@ -package cz.zcu.kiv.crce.metadata.dao; - -import java.io.IOException; -import java.net.URI; - -import javax.annotation.CheckForNull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Repository; - -/** - * This type of plugin defines DAO class for reading and storing the metadata of - * a repository. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface RepositoryDAO { - - /** - * Reads metadata of resources stored in repository on the given URI. - * @param uri Path to repository or a repository identificator. - * @return Loaded repository or null if such repository doesn't exist. - * @throws IOException - */ - @CheckForNull - Repository loadRepository(URI uri) throws IOException; - - /** - * Deletes existing repository (if it exists) including all contained resources. - * @param repository - * @throws IOException - */ - void deleteRepository(Repository repository) throws IOException; - - /** - * Stores metadata of resources stored in the given repository. Typical - * target is a repository.xml in the root folder of the repository. - * @param repository - * @throws IOException - */ - void saveRepository(Repository repository) throws IOException; -} +package cz.zcu.kiv.crce.metadata.dao; + +import java.io.IOException; +import java.net.URI; + +import javax.annotation.CheckForNull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Repository; + +/** + * This type of plugin2 defines DAO class for reading and storing the metadata of + * a repository. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface RepositoryDAO { + + /** + * Reads metadata of resources stored in repository on the given URI. + * @param uri Path to repository or a repository identificator. + * @return Loaded repository or null if such repository doesn't exist. + * @throws IOException + */ + @CheckForNull + Repository loadRepository(URI uri) throws IOException; + + /** + * Deletes existing repository (if it exists) including all contained resources. + * @param repository + * @throws IOException + */ + void deleteRepository(Repository repository) throws IOException; + + /** + * Stores metadata of resources stored in the given repository. Typical + * target is a repository.xml in the root folder of the repository. + * @param repository + * @throws IOException + */ + void saveRepository(Repository repository) throws IOException; +} diff --git a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/ResourceDAO.java b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/ResourceDAO.java index 795afea7..7608ab64 100644 --- a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/ResourceDAO.java +++ b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/ResourceDAO.java @@ -1,70 +1,70 @@ -package cz.zcu.kiv.crce.metadata.dao; - -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; - -/** - * Plugin implementing this class manages retrieving and storing metadata of an - * artifact. - * - *

Typical usage of ResourceDAO plugin is in repository core to - * manipulate and manage metadata resource while uploading artifacts, retrieving - * them, copying etc. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ResourceDAO { - - /** - * Returns Resource object for the given resource. Returns - * null if Resource object can not be created - * (e.g. resource not exists). - * @param uri URI - * @return - * @throws IOException - */ - @CheckForNull - Resource loadResource(URI uri) throws IOException; - - @Nonnull - List loadResources(Repository repository) throws IOException; - - /** - * Loads all resources in the given repository and whose capabilities match the given filter (at least one capability must match). - * @param repository - * @param filter - * @return - * @throws IOException - */ - @Nonnull - List loadResources(Repository repository, ResourceDAOFilter filter) throws IOException; - - /** - * Saves metadata of Resource. - * - * @param resource - * @throws IOException - */ - void saveResource(Resource resource) throws IOException; - - /** - * Removes metadata of Resource. - * @param uri - * @throws IOException - */ - void deleteResource(URI uri) throws IOException; - - boolean existsResource(URI uri) throws IOException; - - boolean existsResource(URI uri, Repository repository) throws IOException; -} +package cz.zcu.kiv.crce.metadata.dao; + +import java.io.IOException; +import java.net.URI; +import java.util.List; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; + +/** + * Plugin implementing this class manages retrieving and storing metadata of an + * artifact. + * + *

Typical usage of ResourceDAO plugin2 is in repository core to + * manipulate and manage metadata resource while uploading artifacts, retrieving + * them, copying etc. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ResourceDAO { + + /** + * Returns Resource object for the given resource. Returns + * null if Resource object can not be created + * (e.g. resource not exists). + * @param uri URI + * @return + * @throws IOException + */ + @CheckForNull + Resource loadResource(URI uri) throws IOException; + + @Nonnull + List loadResources(Repository repository) throws IOException; + + /** + * Loads all resources in the given repository and whose capabilities match the given filter (at least one capability must match). + * @param repository + * @param filter + * @return + * @throws IOException + */ + @Nonnull + List loadResources(Repository repository, ResourceDAOFilter filter) throws IOException; + + /** + * Saves metadata of Resource. + * + * @param resource + * @throws IOException + */ + void saveResource(Resource resource) throws IOException; + + /** + * Removes metadata of Resource. + * @param uri + * @throws IOException + */ + void deleteResource(URI uri) throws IOException; + + boolean existsResource(URI uri) throws IOException; + + boolean existsResource(URI uri, Repository repository) throws IOException; +} diff --git a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/CapabilityFilter.java b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/CapabilityFilter.java index ad85fe5b..72b2dc70 100644 --- a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/CapabilityFilter.java +++ b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/CapabilityFilter.java @@ -1,94 +1,94 @@ -package cz.zcu.kiv.crce.metadata.dao.filter; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.Attribute; - -/** - * Date: 10.3.16 - * - * @author Jakub Danek - */ -public class CapabilityFilter { - - /** - * Operator used to join attribute constraints - */ - private Operator operator; - - private final String namespace; - /** - * Attributes are joined using #operator value - */ - private final List> attributes; - /** - * Sub filters are always joined using AND - */ - private final List subFilters; - - public CapabilityFilter(String namespace) { - this.namespace = namespace; - - this.attributes = new LinkedList<>(); - this.subFilters = new LinkedList<>(); - } - - public void addAttribute(Attribute attribute) { - this.attributes.add(attribute); - } - - public void addAttributes(Collection> attributes) { - this.attributes.addAll(attributes); - } - - public List> getAttributes() { - return attributes; - } - - public void addSubFilter(CapabilityFilter subFilter) { - this.subFilters.add(subFilter); - } - - public void addSubFilters(List subFilters) { - this.subFilters.addAll(subFilters); - } - - public List getSubFilters() { - return subFilters; - } - - public String getNamespace() { - return namespace; - } - - public Operator getOperator() { - return operator; - } - - public void setOperator(Operator operator) { - this.operator = operator; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CapabilityFilter)) return false; - - CapabilityFilter that = (CapabilityFilter) o; - - if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) return false; - if (!attributes.equals(that.attributes)) return false; - return subFilters.equals(that.subFilters); - - } - - @Override - public int hashCode() { - int result = namespace != null ? namespace.hashCode() : 0; - result = 31 * result + attributes.hashCode(); - result = 31 * result + subFilters.hashCode(); - return result; - } -} +package cz.zcu.kiv.crce.metadata.dao.filter; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.Attribute; + +/** + * Date: 10.3.16 + * + * @author Jakub Danek + */ +public class CapabilityFilter { + + /** + * Operator used to join attribute constraints + */ + private Operator operator; + + private final String namespace; + /** + * Attributes are joined using #operator value + */ + private final List> attributes; + /** + * Sub filters are always joined using AND + */ + private final List subFilters; + + public CapabilityFilter(String namespace) { + this.namespace = namespace; + + this.attributes = new LinkedList<>(); + this.subFilters = new LinkedList<>(); + } + + public void addAttribute(Attribute attribute) { + this.attributes.add(attribute); + } + + public void addAttributes(Collection> attributes) { + this.attributes.addAll(attributes); + } + + public List> getAttributes() { + return attributes; + } + + public void addSubFilter(CapabilityFilter subFilter) { + this.subFilters.add(subFilter); + } + + public void addSubFilters(List subFilters) { + this.subFilters.addAll(subFilters); + } + + public List getSubFilters() { + return subFilters; + } + + public String getNamespace() { + return namespace; + } + + public Operator getOperator() { + return operator; + } + + public void setOperator(Operator operator) { + this.operator = operator; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CapabilityFilter)) return false; + + CapabilityFilter that = (CapabilityFilter) o; + + if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) return false; + if (!attributes.equals(that.attributes)) return false; + return subFilters.equals(that.subFilters); + + } + + @Override + public int hashCode() { + int result = namespace != null ? namespace.hashCode() : 0; + result = 31 * result + attributes.hashCode(); + result = 31 * result + subFilters.hashCode(); + return result; + } +} diff --git a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/Operator.java b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/Operator.java index fd91b626..90e17a47 100644 --- a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/Operator.java +++ b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/Operator.java @@ -1,21 +1,21 @@ -package cz.zcu.kiv.crce.metadata.dao.filter; - -/** - * Date: 10.3.16 - * - * @author Jakub Danek - */ -public enum Operator { - AND("AND"), - OR("OR"); - - private final String sql; - - Operator(String sql) { - this.sql = sql; - } - - public String sql() { - return sql; - } -} +package cz.zcu.kiv.crce.metadata.dao.filter; + +/** + * Date: 10.3.16 + * + * @author Jakub Danek + */ +public enum Operator { + AND("AND"), + OR("OR"); + + private final String sql; + + Operator(String sql) { + this.sql = sql; + } + + public String sql() { + return sql; + } +} diff --git a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/ResourceDAOFilter.java b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/ResourceDAOFilter.java index a89300dc..1849600f 100644 --- a/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/ResourceDAOFilter.java +++ b/core/crce-metadata-dao-api/src/main/java/cz/zcu/kiv/crce/metadata/dao/filter/ResourceDAOFilter.java @@ -1,47 +1,47 @@ -package cz.zcu.kiv.crce.metadata.dao.filter; - -import java.util.ArrayList; -import java.util.List; - -/** - * Date: 10.3.16 - * - * @author Jakub Danek - */ -public class ResourceDAOFilter { - - /** - * Operator to be used to joing the filters - */ - private Operator operator; - private final List capabilityFilters; - - public ResourceDAOFilter() { - this.capabilityFilters = new ArrayList<>(); - } - - public void addCapabilityFilter(CapabilityFilter filter) { - this.capabilityFilters.add(filter); - } - - public List getCapabilityFilters() { - return capabilityFilters; - } - - public Operator getOperator() { - return operator; - } - - public void setOperator(Operator operator) { - this.operator = operator; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ResourceDAOFilter{"); - sb.append("operator=").append(operator); - sb.append(", capabilityFilters=").append(capabilityFilters); - sb.append('}'); - return sb.toString(); - } -} +package cz.zcu.kiv.crce.metadata.dao.filter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Date: 10.3.16 + * + * @author Jakub Danek + */ +public class ResourceDAOFilter { + + /** + * Operator to be used to joing the filters + */ + private Operator operator; + private final List capabilityFilters; + + public ResourceDAOFilter() { + this.capabilityFilters = new ArrayList<>(); + } + + public void addCapabilityFilter(CapabilityFilter filter) { + this.capabilityFilters.add(filter); + } + + public List getCapabilityFilters() { + return capabilityFilters; + } + + public Operator getOperator() { + return operator; + } + + public void setOperator(Operator operator) { + this.operator = operator; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ResourceDAOFilter{"); + sb.append("operator=").append(operator); + sb.append(", capabilityFilters=").append(capabilityFilters); + sb.append('}'); + return sb.toString(); + } +} diff --git a/core/crce-metadata-dao-impl/osgi.bnd b/core/crce-metadata-dao-impl/osgi.bnd index cecd2278..d023697f 100644 --- a/core/crce-metadata-dao-impl/osgi.bnd +++ b/core/crce-metadata-dao-impl/osgi.bnd @@ -1,17 +1,17 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Export-Package: - -DynamicImport-Package: * - -Embed-Dependency: flyway-core - -Import-Package: \ - !org.jboss.vfs, \ - !org.springframework.jdbc.core, \ - !org.springframework.jdbc.datasource, \ - * +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Export-Package: + +DynamicImport-Package: * + +Embed-Dependency: flyway-core + +Import-Package: \ + !org.jboss.vfs, \ + !org.springframework.jdbc.core, \ + !org.springframework.jdbc.datasource, \ + * diff --git a/core/crce-metadata-dao-impl/pom.xml b/core/crce-metadata-dao-impl/pom.xml index 84a14837..a6912c14 100644 --- a/core/crce-metadata-dao-impl/pom.xml +++ b/core/crce-metadata-dao-impl/pom.xml @@ -1,113 +1,113 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-dao-impl - 3.1.0-SNAPSHOT - bundle - - CRCE - Core - Metadata DAO Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-dao-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.dao.impl - ${namespace}.metadata.dao - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - org.apache.felix - org.osgi.service.obr - - - - - - org.mybatis - mybatis - - - com.googlecode.flyway - flyway-core - true - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-service-api - 3.0.0 - - - ${project.groupId} - crce-metadata-dao-api - 3.0.0-SNAPSHOT - - - - - - junit - junit - - - cz.zcu.kiv.crce - crce-metadata-impl - 2.1.0 - test - - - - org.mockito - mockito-core - - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-dao-impl + 3.1.0-SNAPSHOT + bundle + + CRCE - Core - Metadata DAO Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-dao-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.dao.impl + ${namespace}.metadata.dao + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + org.apache.felix + org.osgi.service.obr + + + + + + org.mybatis + mybatis + + + com.googlecode.flyway + flyway-core + true + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-service-api + 3.0.0 + + + ${project.groupId} + crce-metadata-dao-api + 3.0.0-SNAPSHOT + + + + + + junit + junit + + + cz.zcu.kiv.crce + crce-metadata-impl + 2.1.0 + test + + + + org.mockito + mockito-core + + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/Activator.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/Activator.java index 4204a7af..f2848178 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/Activator.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/Activator.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.metadata.dao.internal; - -import org.osgi.framework.BundleContext; -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; - - - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase { - - public static final String PID = "cz.zcu.kiv.crce.metadata.dao"; - - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - // TODO logging - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - // TODO logging - } -} +package cz.zcu.kiv.crce.metadata.dao.internal; + +import org.osgi.framework.BundleContext; +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; + + + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase { + + public static final String PID = "cz.zcu.kiv.crce.metadata.dao"; + + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + // TODO logging + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + // TODO logging + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/MetadataMapping.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/MetadataMapping.java index 78320164..4544dd97 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/MetadataMapping.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/MetadataMapping.java @@ -1,332 +1,332 @@ -package cz.zcu.kiv.crce.metadata.dao.internal; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbAttribute; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbCapability; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbDirective; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbProperty; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRequirement; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; -import cz.zcu.kiv.crce.metadata.dao.internal.type.DbAttributeType; -import cz.zcu.kiv.crce.metadata.dao.internal.type.DbOperator; -import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class MetadataMapping { - - static DbResource mapResource2DbResource(Resource resource, MetadataService metadataService) { - DbResource dbResource = new DbResource(); - - URI uri = metadataService.getUri(resource); -// Repository repository = resource.getRepository(); - - dbResource.setId(resource.getId()); - dbResource.setUri(uri.toString()); -// dbResource.setRepository_uri(repository != null ? repository.getURI().toString() : ""); - - return dbResource; - } - - static DbCapability mapCapability2DbCapability(Capability capability, MetadataService metadataService) { - DbCapability dbCapability = new DbCapability(); - - dbCapability.setId(capability.getId()); - dbCapability.setNamespace(capability.getNamespace()); - - return dbCapability; - } - - static DbRequirement mapRequirement2DbRequirement(Requirement requirement, MetadataService metadataService) { - DbRequirement dbRequirement = new DbRequirement(); - - dbRequirement.setId(requirement.getId()); - dbRequirement.setNamespace(requirement.getNamespace()); - - return dbRequirement; - } - - static DbProperty mapProperty2DbProperty(Property property, long propertyId, long parentId, MetadataService metadataService) { - DbProperty dbProperty = new DbProperty(); - - dbProperty.setPropertyId(propertyId); - dbProperty.setParentId(parentId); - dbProperty.setId(property.getId()); - dbProperty.setNamespace(property.getNamespace()); - - return dbProperty; - } - - static List mapAttributes2DbAttributes(List> attributes, long entityId) { - return mapAttributes2DbAttributes(attributes, entityId, false); - } - - static List mapAttributes2DbAttributes(List> attributes, long entityId, boolean multipleAttributes) { - List result = new ArrayList<>(attributes.size()); - - Map attributeIndexes = new HashMap<>(); - - for (Attribute attribute : attributes) { - DbAttributeType dbAttributeType = DbAttributeType.fromClass(attribute.getAttributeType().getType()); - - String name = attribute.getAttributeType().getName(); - - Short attributeIndex = null; - if (multipleAttributes) { - attributeIndex = attributeIndexes.get(name); - if (attributeIndex == null) { - attributeIndex = 0; - } else { - attributeIndex++; - } - attributeIndexes.put(name, attributeIndex); - } - - if (DbAttributeType.LIST.equals(dbAttributeType)) { - @SuppressWarnings("unchecked") - List list = (List) attribute.getValue(); - - short operator = DbOperator.getDbValue(attribute.getOperator()); - - short i = 0; - for (String entry : list) { - DbAttribute dbAttribute = new DbAttribute(); - - dbAttribute.setEntityId(entityId); - dbAttribute.setName(name); - dbAttribute.setOperator(operator); - dbAttribute.setType(dbAttributeType.getDbValue()); - dbAttribute.setStringValue(entry); - dbAttribute.setListIndex(i++); - dbAttribute.setAttributeIndex(attributeIndex); - - result.add(dbAttribute); - } - } else { - DbAttribute dbAttribute = new DbAttribute(); - - dbAttribute.setEntityId(entityId); - dbAttribute.setName(name); - dbAttribute.setOperator(DbOperator.getDbValue(attribute.getOperator())); - dbAttribute.setType(dbAttributeType.getDbValue()); - dbAttribute.setListIndex((short) 0); - dbAttribute.setAttributeIndex(attributeIndex); - - switch (dbAttributeType) { - case STRING: - dbAttribute.setStringValue((String) attribute.getValue()); - break; - - case LONG: - dbAttribute.setLongValue((Long) attribute.getValue()); - break; - - case DOUBLE: - dbAttribute.setDoubleValue((Double) attribute.getValue()); - break; - - case VERSION: - Version version = (Version) attribute.getValue(); - dbAttribute.setVersionMajorValue(version.getMajor()); - dbAttribute.setVersionMinorValue(version.getMinor()); - dbAttribute.setVersionMicroValue(version.getMicro()); - dbAttribute.setStringValue(version.getQualifier()); - break; - - case URI: - dbAttribute.setStringValue(attribute.getValue().toString()); - break; - - case BOOLEAN: - dbAttribute.setBooleanValue((Boolean) attribute.getValue()); - break; - - default: - throw new IllegalArgumentException("Unexpected attribute type: " + dbAttributeType); - } - - result.add(dbAttribute); - } - } - - return result; - } - - static void mapDbAttributes2Requirement(List dbAttributes, final Requirement requirement) { - mapDbAttributes2Entity(dbAttributes, new Entity() { - - @Override - public void setAttribute(AttributeType type, T value, Operator operator) { - requirement.addAttribute(type, value, operator); - } - }, true); - } - - static void mapDbAttributes2Capability(List dbAttributes, final Capability capability) { - mapDbAttributes2Entity(dbAttributes, new Entity() { - - @Override - public void setAttribute(AttributeType type, T value, Operator operator) { - capability.setAttribute(type, value, operator); - } - }, false); - } - - static void mapDbAttributes2Property(List dbAttributes, final Property property) { - mapDbAttributes2Entity(dbAttributes, new Entity() { - - @Override - public void setAttribute(AttributeType type, T value, Operator operator) { - property.setAttribute(type, value, operator); - } - }, false); - } - - static void mapDbDirectives2Capability(List dbDirectives, Capability capability) { - for (DbDirective dbDirective : dbDirectives) { - capability.setDirective(dbDirective.getName(), dbDirective.getValue()); - } - } - - static void mapDbDirectives2Requirement(List dbDirectives, Requirement requirement) { - for (DbDirective dbDirective : dbDirectives) { - requirement.setDirective(dbDirective.getName(), dbDirective.getValue()); - } - } - - private interface Entity { - - void setAttribute(@Nonnull AttributeType type, @Nonnull T value, @Nonnull Operator operator); - } - - private static void mapDbAttributes2Entity(List dbAttributes, Entity entity, boolean multipleAttributes) { - - // temporary fields for processing list attributes in a loop - List list = null; - String listName = null; - Short operator = null; - Short attributeIndex = null; - - for (DbAttribute dbAttribute : dbAttributes) { - DbAttributeType dbAttributeType = DbAttributeType.fromDbValue(dbAttribute.getType()); - - if (DbAttributeType.LIST.equals(dbAttributeType)) { - if (!dbAttribute.getName().equals(listName) - && (!multipleAttributes || !Objects.equals(dbAttribute.getAttributeIndex(), attributeIndex))) { // a new list attribute - // save previous list, if any - if (listName != null && list != null) { - entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); - } - // - list = new ArrayList<>(); - list.add(dbAttribute.getStringValue()); - listName = dbAttribute.getName(); - operator = dbAttribute.getOperator(); - if (multipleAttributes) { - attributeIndex = dbAttribute.getAttributeIndex(); - } - } else { // another element of the current list attribute - assert list != null; - - list.add(dbAttribute.getStringValue()); - } - } else { - // save previous list attribute, if any - if (listName != null && list != null) { - entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); - list = null; - listName = null; - if (multipleAttributes) { - attributeIndex = null; - } - } - - switch (dbAttributeType) { - case DOUBLE: - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Double.class), - dbAttribute.getDoubleValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); - break; - - case LONG: - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Long.class), - dbAttribute.getLongValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); - break; - - case STRING: - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), String.class), - dbAttribute.getStringValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); - break; - - case URI: - try { - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), URI.class), - new URI(dbAttribute.getStringValue()), DbOperator.getOperatorValue(dbAttribute.getOperator())); - } catch (URISyntaxException e) { - throw new IllegalStateException("Invalid URI for attribute " + dbAttribute.getName(), e); - } - break; - - case BOOLEAN: - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Boolean.class), - dbAttribute.getBooleanValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); - break; - - case VERSION: - entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Version.class), - new Version( - dbAttribute.getVersionMajorValue(), - dbAttribute.getVersionMinorValue(), - dbAttribute.getVersionMicroValue(), - dbAttribute.getStringValue()), - DbOperator.getOperatorValue(dbAttribute.getOperator())); - break; - - default: - throw new IllegalArgumentException("Unexpected attribute type: " + dbAttributeType); - } - - } - } - // save unsaved list attribute, if any - if (listName != null && list != null) { - entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); - } - } - - public static List mapDirectives2DbDirectives(Map directives, long entityId) { - List result = new ArrayList<>(directives.size()); - - for (Map.Entry entry : directives.entrySet()) { - DbDirective dbDirective = new DbDirective(); - - dbDirective.setEntityId(entityId); - dbDirective.setName(entry.getKey()); - dbDirective.setValue(entry.getValue()); - - result.add(dbDirective); - } - - return result; - } -} +package cz.zcu.kiv.crce.metadata.dao.internal; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbAttribute; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbCapability; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbDirective; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbProperty; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRequirement; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; +import cz.zcu.kiv.crce.metadata.dao.internal.type.DbAttributeType; +import cz.zcu.kiv.crce.metadata.dao.internal.type.DbOperator; +import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class MetadataMapping { + + static DbResource mapResource2DbResource(Resource resource, MetadataService metadataService) { + DbResource dbResource = new DbResource(); + + URI uri = metadataService.getUri(resource); +// Repository repository = resource.getRepository(); + + dbResource.setId(resource.getId()); + dbResource.setUri(uri.toString()); +// dbResource.setRepository_uri(repository != null ? repository.getURI().toString() : ""); + + return dbResource; + } + + static DbCapability mapCapability2DbCapability(Capability capability, MetadataService metadataService) { + DbCapability dbCapability = new DbCapability(); + + dbCapability.setId(capability.getId()); + dbCapability.setNamespace(capability.getNamespace()); + + return dbCapability; + } + + static DbRequirement mapRequirement2DbRequirement(Requirement requirement, MetadataService metadataService) { + DbRequirement dbRequirement = new DbRequirement(); + + dbRequirement.setId(requirement.getId()); + dbRequirement.setNamespace(requirement.getNamespace()); + + return dbRequirement; + } + + static DbProperty mapProperty2DbProperty(Property property, long propertyId, long parentId, MetadataService metadataService) { + DbProperty dbProperty = new DbProperty(); + + dbProperty.setPropertyId(propertyId); + dbProperty.setParentId(parentId); + dbProperty.setId(property.getId()); + dbProperty.setNamespace(property.getNamespace()); + + return dbProperty; + } + + static List mapAttributes2DbAttributes(List> attributes, long entityId) { + return mapAttributes2DbAttributes(attributes, entityId, false); + } + + static List mapAttributes2DbAttributes(List> attributes, long entityId, boolean multipleAttributes) { + List result = new ArrayList<>(attributes.size()); + + Map attributeIndexes = new HashMap<>(); + + for (Attribute attribute : attributes) { + DbAttributeType dbAttributeType = DbAttributeType.fromClass(attribute.getAttributeType().getType()); + + String name = attribute.getAttributeType().getName(); + + Short attributeIndex = null; + if (multipleAttributes) { + attributeIndex = attributeIndexes.get(name); + if (attributeIndex == null) { + attributeIndex = 0; + } else { + attributeIndex++; + } + attributeIndexes.put(name, attributeIndex); + } + + if (DbAttributeType.LIST.equals(dbAttributeType)) { + @SuppressWarnings("unchecked") + List list = (List) attribute.getValue(); + + short operator = DbOperator.getDbValue(attribute.getOperator()); + + short i = 0; + for (String entry : list) { + DbAttribute dbAttribute = new DbAttribute(); + + dbAttribute.setEntityId(entityId); + dbAttribute.setName(name); + dbAttribute.setOperator(operator); + dbAttribute.setType(dbAttributeType.getDbValue()); + dbAttribute.setStringValue(entry); + dbAttribute.setListIndex(i++); + dbAttribute.setAttributeIndex(attributeIndex); + + result.add(dbAttribute); + } + } else { + DbAttribute dbAttribute = new DbAttribute(); + + dbAttribute.setEntityId(entityId); + dbAttribute.setName(name); + dbAttribute.setOperator(DbOperator.getDbValue(attribute.getOperator())); + dbAttribute.setType(dbAttributeType.getDbValue()); + dbAttribute.setListIndex((short) 0); + dbAttribute.setAttributeIndex(attributeIndex); + + switch (dbAttributeType) { + case STRING: + dbAttribute.setStringValue((String) attribute.getValue()); + break; + + case LONG: + dbAttribute.setLongValue((Long) attribute.getValue()); + break; + + case DOUBLE: + dbAttribute.setDoubleValue((Double) attribute.getValue()); + break; + + case VERSION: + Version version = (Version) attribute.getValue(); + dbAttribute.setVersionMajorValue(version.getMajor()); + dbAttribute.setVersionMinorValue(version.getMinor()); + dbAttribute.setVersionMicroValue(version.getMicro()); + dbAttribute.setStringValue(version.getQualifier()); + break; + + case URI: + dbAttribute.setStringValue(attribute.getValue().toString()); + break; + + case BOOLEAN: + dbAttribute.setBooleanValue((Boolean) attribute.getValue()); + break; + + default: + throw new IllegalArgumentException("Unexpected attribute type: " + dbAttributeType); + } + + result.add(dbAttribute); + } + } + + return result; + } + + static void mapDbAttributes2Requirement(List dbAttributes, final Requirement requirement) { + mapDbAttributes2Entity(dbAttributes, new Entity() { + + @Override + public void setAttribute(AttributeType type, T value, Operator operator) { + requirement.addAttribute(type, value, operator); + } + }, true); + } + + static void mapDbAttributes2Capability(List dbAttributes, final Capability capability) { + mapDbAttributes2Entity(dbAttributes, new Entity() { + + @Override + public void setAttribute(AttributeType type, T value, Operator operator) { + capability.setAttribute(type, value, operator); + } + }, false); + } + + static void mapDbAttributes2Property(List dbAttributes, final Property property) { + mapDbAttributes2Entity(dbAttributes, new Entity() { + + @Override + public void setAttribute(AttributeType type, T value, Operator operator) { + property.setAttribute(type, value, operator); + } + }, false); + } + + static void mapDbDirectives2Capability(List dbDirectives, Capability capability) { + for (DbDirective dbDirective : dbDirectives) { + capability.setDirective(dbDirective.getName(), dbDirective.getValue()); + } + } + + static void mapDbDirectives2Requirement(List dbDirectives, Requirement requirement) { + for (DbDirective dbDirective : dbDirectives) { + requirement.setDirective(dbDirective.getName(), dbDirective.getValue()); + } + } + + private interface Entity { + + void setAttribute(@Nonnull AttributeType type, @Nonnull T value, @Nonnull Operator operator); + } + + private static void mapDbAttributes2Entity(List dbAttributes, Entity entity, boolean multipleAttributes) { + + // temporary fields for processing list attributes in a loop + List list = null; + String listName = null; + Short operator = null; + Short attributeIndex = null; + + for (DbAttribute dbAttribute : dbAttributes) { + DbAttributeType dbAttributeType = DbAttributeType.fromDbValue(dbAttribute.getType()); + + if (DbAttributeType.LIST.equals(dbAttributeType)) { + if (!dbAttribute.getName().equals(listName) + && (!multipleAttributes || !Objects.equals(dbAttribute.getAttributeIndex(), attributeIndex))) { // a new list attribute + // save previous list, if any + if (listName != null && list != null) { + entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); + } + // + list = new ArrayList<>(); + list.add(dbAttribute.getStringValue()); + listName = dbAttribute.getName(); + operator = dbAttribute.getOperator(); + if (multipleAttributes) { + attributeIndex = dbAttribute.getAttributeIndex(); + } + } else { // another element of the current list attribute + assert list != null; + + list.add(dbAttribute.getStringValue()); + } + } else { + // save previous list attribute, if any + if (listName != null && list != null) { + entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); + list = null; + listName = null; + if (multipleAttributes) { + attributeIndex = null; + } + } + + switch (dbAttributeType) { + case DOUBLE: + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Double.class), + dbAttribute.getDoubleValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); + break; + + case LONG: + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Long.class), + dbAttribute.getLongValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); + break; + + case STRING: + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), String.class), + dbAttribute.getStringValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); + break; + + case URI: + try { + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), URI.class), + new URI(dbAttribute.getStringValue()), DbOperator.getOperatorValue(dbAttribute.getOperator())); + } catch (URISyntaxException e) { + throw new IllegalStateException("Invalid URI for attribute " + dbAttribute.getName(), e); + } + break; + + case BOOLEAN: + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Boolean.class), + dbAttribute.getBooleanValue(), DbOperator.getOperatorValue(dbAttribute.getOperator())); + break; + + case VERSION: + entity.setAttribute(new SimpleAttributeType<>(dbAttribute.getName(), Version.class), + new Version( + dbAttribute.getVersionMajorValue(), + dbAttribute.getVersionMinorValue(), + dbAttribute.getVersionMicroValue(), + dbAttribute.getStringValue()), + DbOperator.getOperatorValue(dbAttribute.getOperator())); + break; + + default: + throw new IllegalArgumentException("Unexpected attribute type: " + dbAttributeType); + } + + } + } + // save unsaved list attribute, if any + if (listName != null && list != null) { + entity.setAttribute(new ListAttributeType(listName), list, DbOperator.getOperatorValue(operator)); + } + } + + public static List mapDirectives2DbDirectives(Map directives, long entityId) { + List result = new ArrayList<>(directives.size()); + + for (Map.Entry entry : directives.entrySet()) { + DbDirective dbDirective = new DbDirective(); + + dbDirective.setEntityId(entityId); + dbDirective.setName(entry.getKey()); + dbDirective.setValue(entry.getValue()); + + result.add(dbDirective); + } + + return result; + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/RepositoryDAOImpl.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/RepositoryDAOImpl.java index d6a147d4..c2f02b87 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/RepositoryDAOImpl.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/RepositoryDAOImpl.java @@ -1,153 +1,153 @@ -package cz.zcu.kiv.crce.metadata.dao.internal; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; -import org.apache.felix.dm.annotation.api.Start; -import org.apache.felix.dm.annotation.api.Stop; -import org.apache.ibatis.exceptions.PersistenceException; -import org.apache.ibatis.session.SqlSession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRepository; -import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides={RepositoryDAO.class, RepositoryDAOImpl.class}) -public class RepositoryDAOImpl implements RepositoryDAO { - - private static final Logger logger = LoggerFactory.getLogger(RepositoryDAOImpl.class); - - private static final String REPOSITORY_MAPPER = "cz.zcu.kiv.crce.metadata.dao.internal.mapper.RepositoryMapper."; - - @ServiceDependency private volatile MetadataFactory metadataFactory; - @ServiceDependency private volatile MetadataService metadataService; // NOPMD - @ServiceDependency private volatile SessionManager sessionManager; - - @Start - void start() { - logger.info("CRCE Metadata DAO RepositoryDAO started."); - } - - @Stop - synchronized void stop() { - logger.info("CRCE Metadata DAO RepositoryDAO finished."); - } - - @Override - public Repository loadRepository(URI uri) throws IOException { - logger.debug("loadRepository(uri={})", uri); - - Repository repository; - try (SqlSession session = sessionManager.getSession()) { - repository = loadRepository(uri, session); - } catch (PersistenceException e) { - throw new IOException(e); - } - - logger.debug("loadRepository(uri={}) returns {}", uri, repository); - - return repository; - } - - @CheckForNull - private Repository loadRepository(@Nonnull URI uri, @Nonnull SqlSession session) { - Repository repository = null; - DbRepository dbRepository = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryByUri", uri.toString()); - if (dbRepository != null) { - try { - repository = metadataFactory.createRepository(new URI(dbRepository.getUri()), dbRepository.getId()); - } catch (URISyntaxException ex) { - throw new IllegalArgumentException("Invalid URI: " + dbRepository.getUri(), ex); - } - } - return repository; - } - - @Override - public void deleteRepository(Repository repository) throws IOException { - logger.debug("deleteRepository(repository={})", repository); - - try (SqlSession session = sessionManager.getSession()) { - session.delete(REPOSITORY_MAPPER + "deleteRepository", repository.getUri().toString()); - } - - logger.debug("deleteRepository(repository={}) returns", repository); - } - - @Override - public void saveRepository(Repository repository) throws IOException { - logger.debug("saveRepository(repository={})", repository); - - try (SqlSession session = sessionManager.getSession()) { - if (loadRepository(repository.getUri()) == null) { - SequenceMapper seqMapper = session.getMapper(SequenceMapper.class); - - DbRepository dbRepository = new DbRepository(); - - long repositoryId = seqMapper.nextVal("resource_seq"); - - dbRepository.setRepositoryId(repositoryId); - dbRepository.setUri(repository.getUri().toString()); - dbRepository.setId(repository.getId()); - - session.insert(REPOSITORY_MAPPER + "insertRepository", dbRepository); - - session.commit(); - } else { - logger.info("Saved repository already exists, saving skipped (update not implemented)."); - } - } - - logger.debug("saveRepository(repository={}) returns", repository); - } - - /* Internal public methods */ - - @CheckForNull - public Long getRepositoryId(@Nonnull String uuid, @Nonnull SqlSession session) { - logger.debug("getRepositoryId(uuid={})", uuid); - - Long repositoryId = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryId", uuid); - - logger.debug("getRepositoryId(uuid={}) returns {}", uuid, repositoryId); - - return repositoryId; - } - - @CheckForNull - public Repository loadRepository(long repositoryId, @Nonnull SqlSession session) throws IOException { - logger.debug("getRepository(repositoryId={})", repositoryId); - - Repository repository = null; - - DbRepository dbRepository = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryByRepositoryId", repositoryId); - if (dbRepository != null) { - try { - repository = metadataFactory.createRepository(new URI(dbRepository.getUri()), dbRepository.getId()); - } catch (URISyntaxException e) { - throw new IOException("Invalid URI syntax of repository with ID: " + repositoryId + ", URI: " + dbRepository.getUri(), e); - } - } - - logger.debug("getRepository(repositoryId={}) returns {}", repositoryId, repository); - - return repository; - } - -} +package cz.zcu.kiv.crce.metadata.dao.internal; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; +import org.apache.felix.dm.annotation.api.Start; +import org.apache.felix.dm.annotation.api.Stop; +import org.apache.ibatis.exceptions.PersistenceException; +import org.apache.ibatis.session.SqlSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRepository; +import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides={RepositoryDAO.class, RepositoryDAOImpl.class}) +public class RepositoryDAOImpl implements RepositoryDAO { + + private static final Logger logger = LoggerFactory.getLogger(RepositoryDAOImpl.class); + + private static final String REPOSITORY_MAPPER = "cz.zcu.kiv.crce.metadata.dao.internal.mapper.RepositoryMapper."; + + @ServiceDependency private volatile MetadataFactory metadataFactory; + @ServiceDependency private volatile MetadataService metadataService; // NOPMD + @ServiceDependency private volatile SessionManager sessionManager; + + @Start + void start() { + logger.info("CRCE Metadata DAO RepositoryDAO started."); + } + + @Stop + synchronized void stop() { + logger.info("CRCE Metadata DAO RepositoryDAO finished."); + } + + @Override + public Repository loadRepository(URI uri) throws IOException { + logger.debug("loadRepository(uri={})", uri); + + Repository repository; + try (SqlSession session = sessionManager.getSession()) { + repository = loadRepository(uri, session); + } catch (PersistenceException e) { + throw new IOException(e); + } + + logger.debug("loadRepository(uri={}) returns {}", uri, repository); + + return repository; + } + + @CheckForNull + private Repository loadRepository(@Nonnull URI uri, @Nonnull SqlSession session) { + Repository repository = null; + DbRepository dbRepository = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryByUri", uri.toString()); + if (dbRepository != null) { + try { + repository = metadataFactory.createRepository(new URI(dbRepository.getUri()), dbRepository.getId()); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid URI: " + dbRepository.getUri(), ex); + } + } + return repository; + } + + @Override + public void deleteRepository(Repository repository) throws IOException { + logger.debug("deleteRepository(repository={})", repository); + + try (SqlSession session = sessionManager.getSession()) { + session.delete(REPOSITORY_MAPPER + "deleteRepository", repository.getUri().toString()); + } + + logger.debug("deleteRepository(repository={}) returns", repository); + } + + @Override + public void saveRepository(Repository repository) throws IOException { + logger.debug("saveRepository(repository={})", repository); + + try (SqlSession session = sessionManager.getSession()) { + if (loadRepository(repository.getUri()) == null) { + SequenceMapper seqMapper = session.getMapper(SequenceMapper.class); + + DbRepository dbRepository = new DbRepository(); + + long repositoryId = seqMapper.nextVal("resource_seq"); + + dbRepository.setRepositoryId(repositoryId); + dbRepository.setUri(repository.getUri().toString()); + dbRepository.setId(repository.getId()); + + session.insert(REPOSITORY_MAPPER + "insertRepository", dbRepository); + + session.commit(); + } else { + logger.info("Saved repository already exists, saving skipped (update not implemented)."); + } + } + + logger.debug("saveRepository(repository={}) returns", repository); + } + + /* Internal public methods */ + + @CheckForNull + public Long getRepositoryId(@Nonnull String uuid, @Nonnull SqlSession session) { + logger.debug("getRepositoryId(uuid={})", uuid); + + Long repositoryId = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryId", uuid); + + logger.debug("getRepositoryId(uuid={}) returns {}", uuid, repositoryId); + + return repositoryId; + } + + @CheckForNull + public Repository loadRepository(long repositoryId, @Nonnull SqlSession session) throws IOException { + logger.debug("getRepository(repositoryId={})", repositoryId); + + Repository repository = null; + + DbRepository dbRepository = session.selectOne(REPOSITORY_MAPPER + "selectRepositoryByRepositoryId", repositoryId); + if (dbRepository != null) { + try { + repository = metadataFactory.createRepository(new URI(dbRepository.getUri()), dbRepository.getId()); + } catch (URISyntaxException e) { + throw new IOException("Invalid URI syntax of repository with ID: " + repositoryId + ", URI: " + dbRepository.getUri(), e); + } + } + + logger.debug("getRepository(repositoryId={}) returns {}", repositoryId, repository); + + return repository; + } + +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/ResourceDAOImpl.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/ResourceDAOImpl.java index 42a395bb..28c1a0c8 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/ResourceDAOImpl.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/ResourceDAOImpl.java @@ -1,573 +1,573 @@ -package cz.zcu.kiv.crce.metadata.dao.internal; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.annotation.Nonnull; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; -import org.apache.felix.dm.annotation.api.Start; -import org.apache.felix.dm.annotation.api.Stop; -import org.apache.ibatis.exceptions.PersistenceException; -import org.apache.ibatis.session.SqlSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbAttribute; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbCapability; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbDirective; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbProperty; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRequirement; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; -import cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResolvingMapper; -import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - * @author Jan Dyrczyk (dyrczyk@students.zcu.cz) - * @author Pavel Cihlář - */ -@Component(provides={ResourceDAO.class}) -public class ResourceDAOImpl implements ResourceDAO { - - private static final Logger logger = LoggerFactory.getLogger(ResourceDAOImpl.class); - - private static final String RESOURCE_MAPPER = "cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResourceMapper."; - - @ServiceDependency private volatile MetadataFactory metadataFactory; - @ServiceDependency private volatile MetadataService metadataService; - @ServiceDependency private volatile SessionManager sessionManager; - @ServiceDependency private volatile RepositoryDAOImpl repositoryDAOImpl; - - @Start - void start() { - logger.info("CRCE Metadata DAO ResourceDAO started."); - } - - @Stop - synchronized void stop() { - logger.info("CRCE Metadata DAO ResourceDAO finished."); - } - - @Override - public synchronized Resource loadResource(URI uri) throws IOException { // TODO, only an URI as an argument is not nice - logger.debug("loadResource(uri={})", uri); - - Resource result = null; - - try (SqlSession session = sessionManager.getSession()) { - DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); - - if (dbResource != null) { - result = loadResource(dbResource, session); - } - } catch (PersistenceException e) { - throw new IOException("Could not load resource.", e); - } - - logger.debug("loadResource(uri) returns {}", result); - return result; - } - - private Resource loadResource(@Nonnull DbResource dbResource, @Nonnull SqlSession session) { - Resource resource = metadataFactory.createResource(dbResource.getId()); - // loaded from DB as part of capabilities: -// metadataService.setUri(resource, dbResource.getUri()); -// metadataService.getSingletonCapability(resource, metadataService.getIdentityNamespace()) -// .setAttribute("repository-id", String.class, dbResource.getRepositoryUuid()); - Map requirements = loadRequirements(resource, dbResource.getResourceId(), session); - loadCapabilities(resource, dbResource.getResourceId(), requirements, session); - loadProperties(resource, dbResource.getResourceId(), session); - - try { - assert dbResource.getUri() != null && new URI(dbResource.getUri()).equals(metadataService.getUri(resource)); - } catch (URISyntaxException ex) { - throw new IllegalStateException("Illegal URI in resource table.", ex); - } - - return resource; - } - - - Map loadRequirements(Resource resource, long resourceId, SqlSession session) { - List dbRequirements = session.selectList(RESOURCE_MAPPER + "selectRequirements", resourceId); - - Map requirements = new HashMap<>(dbRequirements.size()); - Map capabilityRequirements = new HashMap<>(dbRequirements.size()); - Map unprocessedRequirements = new HashMap<>(dbRequirements.size()); // K: requirement ID, V: requirement parent ID - - for (DbRequirement dbRequirement : dbRequirements) { - Requirement requirement = metadataFactory.createRequirement(dbRequirement.getNamespace(), dbRequirement.getId()); - - loadRequirementAttributes(requirement, dbRequirement.getRequirementId(), session); - loadRequirementDirectives(requirement, dbRequirement.getRequirementId(), session); - - requirements.put(dbRequirement.getRequirementId(), requirement); - - if (dbRequirement.getRequirementId() == dbRequirement.getParentRequirementId()) { - assert dbRequirement.getLevel() == 0; - - if (dbRequirement.getCapabilityId() != null) { - capabilityRequirements.put(dbRequirement.getCapabilityId(), requirement); - } else { - resource.addRequirement(requirement); - } - } else { - Requirement parent = requirements.get(dbRequirement.getParentRequirementId()); - if (parent != null) { - parent.addChild(requirement); - } else { - logger.warn("There is unprocessed requirement (missing parent) for resource {}, ID: {}, parent ID: {}.", - resourceId, dbRequirement.getRequirementId(), dbRequirement.getParentRequirementId()); - unprocessedRequirements.put(dbRequirement.getRequirementId(), dbRequirement.getParentRequirementId()); - } - } - } - - assert unprocessedRequirements.isEmpty(); - - while (!unprocessedRequirements.isEmpty()) { - Iterator> iterator = unprocessedRequirements.entrySet().iterator(); - while (iterator.hasNext()) { - Entry entry = iterator.next(); - Requirement parent = requirements.get(entry.getValue()); - if (parent != null) { - Requirement requirement = requirements.get(entry.getKey()); - parent.addChild(requirement); - iterator.remove(); - } - } - } - - return capabilityRequirements; - } - - void loadCapabilities(Resource resource, long resourceId, Map requirements, SqlSession session) { - List dbCapabilities = session.selectList(RESOURCE_MAPPER + "selectCapabilities", resourceId); - - Map capabilities = new HashMap<>(dbCapabilities.size()); - Map unprocessedCapabilities = new HashMap<>(dbCapabilities.size()); // K: capability ID, V: capability parent ID - - for (DbCapability dbCapability : dbCapabilities) { - Capability capability = metadataFactory.createCapability(dbCapability.getNamespace(), dbCapability.getId()); - - loadCapabilityAttributes(capability, dbCapability.getCapabilityId(), session); - loadCapabilityDirectives(capability, dbCapability.getCapabilityId(), session); - loadProperties(capability, dbCapability.getCapabilityId(), session); - - Requirement requirement = requirements.get(dbCapability.getCapabilityId()); - if (requirement != null) { - capability.addRequirement(requirement); - } - - resource.addCapability(capability); - - capabilities.put(dbCapability.getCapabilityId(), capability); - - if (dbCapability.getCapabilityId() == dbCapability.getParentCapabilityId()) { - assert dbCapability.getLevel() == 0; - - resource.addRootCapability(capability); - } else { - Capability parent = capabilities.get(dbCapability.getParentCapabilityId()); - if (parent != null) { - parent.addChild(capability); - } else { - logger.warn("There is unprocessed capability (missing parent) for resource {}, ID: {}, parent ID: {}.", - resourceId, dbCapability.getCapabilityId(), dbCapability.getParentCapabilityId()); - unprocessedCapabilities.put(dbCapability.getCapabilityId(), dbCapability.getParentCapabilityId()); - } - } - } - - assert unprocessedCapabilities.isEmpty(); - - // Reconstruct capability tree structure - this would be optimized by MPTT or hierarchy leveling or: - // http://www.codeproject.com/Articles/8355/Trees-in-SQL-databases - while (!unprocessedCapabilities.isEmpty()) { - Iterator> iterator = unprocessedCapabilities.entrySet().iterator(); - while (iterator.hasNext()) { - Entry entry = iterator.next(); - Capability parent = capabilities.get(entry.getValue()); - if (parent != null) { - Capability capability = capabilities.get(entry.getKey()); - parent.addChild(capability); - iterator.remove(); - } - } - } - } - - void loadProperties(Resource resource, long resourceId, SqlSession session) { - List dbProperties = session.selectList(RESOURCE_MAPPER + "selectResourceProperties", resourceId); - - for (DbProperty dbProperty : dbProperties) { - Property property = metadataFactory.createProperty(dbProperty.getNamespace(), dbProperty.getId()); - - loadResourcePropertyAttributes(property, dbProperty.getPropertyId(), session); - - resource.addProperty(property); - } - } - - void loadProperties(Capability capability, long resourceId, SqlSession session) { - List dbProperties = session.selectList(RESOURCE_MAPPER + "selectCapabilityProperties", resourceId); - - for (DbProperty dbProperty : dbProperties) { - Property property = metadataFactory.createProperty(dbProperty.getNamespace(), dbProperty.getId()); - - loadCapabilityPropertyAttributes(property, dbProperty.getPropertyId(), session); - - capability.addProperty(property); - } - } - - void loadCapabilityAttributes(Capability capability, long capabilityId, SqlSession session) { - List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectCapabilityAttributes", capabilityId); - - MetadataMapping.mapDbAttributes2Capability(dbAttributes, capability); - } - - void loadCapabilityDirectives(Capability capability, long capabilityId, SqlSession session) { - List dbDirectives = session.selectList(RESOURCE_MAPPER + "selectCapabilityDirectives", capabilityId); - - MetadataMapping.mapDbDirectives2Capability(dbDirectives, capability); - } - - void loadRequirementAttributes(Requirement requirement, long requirementId, SqlSession session) { - List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectRequirementAttributes", requirementId); - - MetadataMapping.mapDbAttributes2Requirement(dbAttributes, requirement); - } - - void loadRequirementDirectives(Requirement requirement, long requirementId, SqlSession session) { - List dbDirectives = session.selectList(RESOURCE_MAPPER + "selectRequirementDirectives", requirementId); - - MetadataMapping.mapDbDirectives2Requirement(dbDirectives, requirement); - } - - void loadResourcePropertyAttributes(Property property, long propertyId, SqlSession session) { - List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectResourcePropertyAttributes", propertyId); - - MetadataMapping.mapDbAttributes2Property(dbAttributes, property); - } - - void loadCapabilityPropertyAttributes(Property property, long propertyId, SqlSession session) { - List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectCapabilityPropertyAttributes", propertyId); - - MetadataMapping.mapDbAttributes2Property(dbAttributes, property); - } - - @Override - public synchronized List loadResources(Repository repository) throws IOException { - logger.debug("loadResources(repository={})", repository); - - List result = Collections.emptyList(); - try (SqlSession session = sessionManager.getSession()) { - Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); - - if (repositoryId != null) { - List dbResources = session.selectList(RESOURCE_MAPPER + "selectResourcesByRepositoryId", repositoryId); - if (dbResources != null && !dbResources.isEmpty()) { - result = new ArrayList<>(dbResources.size()); - for (DbResource dbResource : dbResources) { - // TODO optimize - select in loop - Resource resource = loadResource(dbResource, session); - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - result.add(resource); - } - } - } - } catch (PersistenceException e) { - throw new IOException("Could not load resources.", e); - } - - if (logger.isTraceEnabled()) { - logger.trace("loadResources(repository={}) returns {}", repository, result); - } else { - logger.debug("loadResources(repository={) returns {}", repository, result.size()); - } - - return result; - } - - @Override - public List loadResources(@Nonnull Repository repository, @Nonnull ResourceDAOFilter filter) throws IOException { - logger.debug("loadResources(repository={}, filter={})", repository, - logger.isTraceEnabled() ? filter.toString() : "(" + filter.getCapabilityFilters().size() + ")"); - - List result = Collections.emptyList(); - try (SqlSession session = sessionManager.getSession()) { - Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); - - if (repositoryId != null) { - List dbResources = session.getMapper(ResolvingMapper.class).getResources(repositoryId, filter); - - if (dbResources != null && !dbResources.isEmpty()) { - result = new ArrayList<>(dbResources.size()); - for (DbResource dbResource : dbResources) { - // TODO optimize - select in loop - Resource resource = loadResource(dbResource, session); - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - result.add(resource); - } - } - } - - } catch (PersistenceException e) { - throw new IOException("Could not load resources.", e); - } - - if (logger.isTraceEnabled()) { - logger.trace("loadResources(repository={}, filter={}) returns {}", - repository, filter.toString() + "(" + filter.getCapabilityFilters().size() + ")", result); - } else { - logger.debug("loadResources(repository={}, filter={}) returns {}", - repository, "(" + filter.getCapabilityFilters().size() + ")", result.size()); - } - - return result; - } - - @Override - public synchronized void saveResource(Resource resource) throws IOException { - logger.debug("saveResource(resource={})", resource); - - try (SqlSession session = sessionManager.getSession()) { - /* - * Workaround for updating of existing resources: Resource is deleted and then re-inserted - * until some update solution will be implemented. This solution wastes internal unique IDs, - * because a new ID is generated on each insertion. - */ - if (existsResource(resource.getId())) { - session.delete(RESOURCE_MAPPER + "deleteResourceById", resource.getId()); - logger.trace("Update workaround: existing resource {} was deleted before insert.", resource.getId()); - } - - SequenceMapper seqMapper = session.getMapper(SequenceMapper.class); - - DbResource dbResource = MetadataMapping.mapResource2DbResource(resource, metadataService); - - long resourceId = seqMapper.nextVal("resource_seq"); - dbResource.setResourceId(resourceId); - - String repositoryUuid = metadataService.getIdentity(resource) - .getAttributeValue(new SimpleAttributeType<>("repository-id", String.class)); - - if (repositoryUuid == null) { - throw new IllegalArgumentException("Repository is not set on resource: " + resource.getId()); - } - - Long repositoryId = repositoryDAOImpl.getRepositoryId(repositoryUuid, session); - if (repositoryId == null) { - throw new IllegalArgumentException("Repository doesn't exist: " + repositoryUuid); - } - - dbResource.setRepositoryId(repositoryId); - - session.insert(RESOURCE_MAPPER + "insertResource", dbResource); - - // capabilities - for (Capability capability : resource.getRootCapabilities()) { - saveCapabilityRecursive(capability, resourceId, null, 0, session, seqMapper); - } - - // requirements - for (Requirement requirement : resource.getRequirements()) { - saveRequirementRecursive(requirement, resourceId, null, null, 0, session, seqMapper); - } - - // properties - for (Property property : resource.getProperties()) { - saveResourceProperty(property, resourceId, session, seqMapper); - } - - session.commit(); - } catch (PersistenceException e) { - throw new IOException("Could not save resource.", e); - } - - logger.debug("saveResource(resource) returns", resource); - } - - private void saveCapabilityRecursive(Capability capability, long resourceId, Long parentId, int level, - SqlSession session, SequenceMapper seqMapper) { - - DbCapability dbCapability = MetadataMapping.mapCapability2DbCapability(capability, metadataService); - dbCapability.setResourceId(resourceId); - dbCapability.setLevel(level); - - long capabilityId = seqMapper.nextVal("capability_seq"); - dbCapability.setCapabilityId(capabilityId); - dbCapability.setParentCapabilityId(parentId != null ? parentId : capabilityId); - - session.insert(RESOURCE_MAPPER + "insertCapability", dbCapability); - - List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(capability.getAttributes(), capabilityId); - if (!dbAttributes.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertCapabilityAttributes", dbAttributes); - } - - List dbDirectives = MetadataMapping.mapDirectives2DbDirectives(capability.getDirectives(), capabilityId); - if (!dbDirectives.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertCapabilityDirectives", dbDirectives); - } - - for (Requirement requirement : capability.getRequirements()) { - saveRequirementRecursive(requirement, resourceId, null, capabilityId, 0, session, seqMapper); - } - - for (Property property : capability.getProperties()) { - saveCapabilityProperty(property, capabilityId, session, seqMapper); - } - - for (Capability child : capability.getChildren()) { - saveCapabilityRecursive(child, resourceId, capabilityId, level + 1, session, seqMapper); - } - } - - private void saveRequirementRecursive(Requirement requirement, long resourceId, Long parentId, Long capabilityId, int level, - SqlSession session, SequenceMapper seqMapper) { - - DbRequirement dbRequirement = MetadataMapping.mapRequirement2DbRequirement(requirement, metadataService); - dbRequirement.setResourceId(resourceId); - dbRequirement.setCapabilityId(capabilityId); - dbRequirement.setLevel(level); - - long requirementId = seqMapper.nextVal("requirement_seq"); - dbRequirement.setRequirementId(requirementId); - dbRequirement.setParentRequirementId(parentId != null ? parentId : requirementId); - - session.insert(RESOURCE_MAPPER + "insertRequirement", dbRequirement); - - List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(requirement.getAttributes(), requirementId, true); - if (!dbAttributes.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertRequirementAttributes", dbAttributes); - } - - List dbDirectives = MetadataMapping.mapDirectives2DbDirectives(requirement.getDirectives(), requirementId); - if (!dbDirectives.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertRequirementDirectives", dbDirectives); - } - - for (Requirement child : requirement.getChildren()) { - saveRequirementRecursive(child, resourceId, requirementId, capabilityId, level + 1, session, seqMapper); - } - } - - private void saveResourceProperty(Property property, long resourceId, SqlSession session, SequenceMapper seqMapper) { - long propertyId = seqMapper.nextVal("resource_property_seq"); - DbProperty dbProperty = MetadataMapping.mapProperty2DbProperty(property, propertyId, resourceId, metadataService); - - session.insert(RESOURCE_MAPPER + "insertResourceProperty", dbProperty); - - List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(property.getAttributes(), propertyId); - if (!dbAttributes.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertResourcePropertyAttributes", dbAttributes); - } - } - - private void saveCapabilityProperty(Property property, long capabilityId, SqlSession session, SequenceMapper seqMapper) { - long propertyId = seqMapper.nextVal("capability_property_seq"); - DbProperty dbProperty = MetadataMapping.mapProperty2DbProperty(property, propertyId, capabilityId, metadataService); - - session.insert(RESOURCE_MAPPER + "insertCapabilityProperty", dbProperty); - - List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(property.getAttributes(), propertyId); - if (!dbAttributes.isEmpty()) { - session.insert(RESOURCE_MAPPER + "insertCapabilityPropertyAttributes", dbAttributes); - } - } - - @Override - public synchronized void deleteResource(URI uri) throws IOException { - logger.debug("deleteResource(uri={})", uri); - - try (SqlSession session = sessionManager.getSession()) { - DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); - - if (dbResource != null) { - long resourceId = dbResource.getResourceId(); - session.delete(RESOURCE_MAPPER + "deleteResourceByResourceId", resourceId); - session.commit(); - } - } catch (PersistenceException e) { - throw new IOException("Could not delete resource.", e); - } - - logger.debug("deleteResource(uri) returns"); - } - - @Override - public synchronized boolean existsResource(URI uri) throws IOException { // TODO just simple select, check if return null - logger.debug("existsResource(uri={})", uri); - - boolean result = false; - try (SqlSession session = sessionManager.getSession()) { - if (session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()) != null) { - result = true; - } - } catch (PersistenceException e) { - throw new IOException("Could not check presence of resource.", e); - } - - logger.debug("existsResource(uri) returns {}", result); - - return result; - } - - @Override - public boolean existsResource(URI uri, Repository repository) throws IOException { // not needed - logger.debug("existsResource(uri={}, repository={})", uri, repository); - - boolean result = false; - try (SqlSession session = sessionManager.getSession()) { - Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); - - DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); - if (dbResource != null && dbResource.getRepositoryId() == repositoryId) { - result = true; - } - } catch (PersistenceException e) { - throw new IOException("Could not check presence of resource.", e); - } - - logger.debug("existsResource(uri, repository) returns {}", result); - - return result; - } - - private boolean existsResource(@Nonnull String id) throws IOException { - boolean result = false; - - try (SqlSession session = sessionManager.getSession()) { - if (session.selectOne(RESOURCE_MAPPER + "selectResourceById", id) != null) { - result = true; - } - } catch (PersistenceException e) { - throw new IOException("Could not check presence of resource.", e); - } - - return result; - } -} +package cz.zcu.kiv.crce.metadata.dao.internal; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.annotation.Nonnull; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; +import org.apache.felix.dm.annotation.api.Start; +import org.apache.felix.dm.annotation.api.Stop; +import org.apache.ibatis.exceptions.PersistenceException; +import org.apache.ibatis.session.SqlSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbAttribute; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbCapability; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbDirective; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbProperty; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbRequirement; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; +import cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResolvingMapper; +import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + * @author Jan Dyrczyk (dyrczyk@students.zcu.cz) + * @author Pavel Cihlář + */ +@Component(provides={ResourceDAO.class}) +public class ResourceDAOImpl implements ResourceDAO { + + private static final Logger logger = LoggerFactory.getLogger(ResourceDAOImpl.class); + + private static final String RESOURCE_MAPPER = "cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResourceMapper."; + + @ServiceDependency private volatile MetadataFactory metadataFactory; + @ServiceDependency private volatile MetadataService metadataService; + @ServiceDependency private volatile SessionManager sessionManager; + @ServiceDependency private volatile RepositoryDAOImpl repositoryDAOImpl; + + @Start + void start() { + logger.info("CRCE Metadata DAO ResourceDAO started."); + } + + @Stop + synchronized void stop() { + logger.info("CRCE Metadata DAO ResourceDAO finished."); + } + + @Override + public synchronized Resource loadResource(URI uri) throws IOException { // TODO, only an URI as an argument is not nice + logger.debug("loadResource(uri={})", uri); + + Resource result = null; + + try (SqlSession session = sessionManager.getSession()) { + DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); + + if (dbResource != null) { + result = loadResource(dbResource, session); + } + } catch (PersistenceException e) { + throw new IOException("Could not load resource.", e); + } + + logger.debug("loadResource(uri) returns {}", result); + return result; + } + + private Resource loadResource(@Nonnull DbResource dbResource, @Nonnull SqlSession session) { + Resource resource = metadataFactory.createResource(dbResource.getId()); + // loaded from DB as part of capabilities: +// metadataService.setUri(resource, dbResource.getUri()); +// metadataService.getSingletonCapability(resource, metadataService.getIdentityNamespace()) +// .setAttribute("repository-id", String.class, dbResource.getRepositoryUuid()); + Map requirements = loadRequirements(resource, dbResource.getResourceId(), session); + loadCapabilities(resource, dbResource.getResourceId(), requirements, session); + loadProperties(resource, dbResource.getResourceId(), session); + + try { + assert dbResource.getUri() != null && new URI(dbResource.getUri()).equals(metadataService.getUri(resource)); + } catch (URISyntaxException ex) { + throw new IllegalStateException("Illegal URI in resource table.", ex); + } + + return resource; + } + + + Map loadRequirements(Resource resource, long resourceId, SqlSession session) { + List dbRequirements = session.selectList(RESOURCE_MAPPER + "selectRequirements", resourceId); + + Map requirements = new HashMap<>(dbRequirements.size()); + Map capabilityRequirements = new HashMap<>(dbRequirements.size()); + Map unprocessedRequirements = new HashMap<>(dbRequirements.size()); // K: requirement ID, V: requirement parent ID + + for (DbRequirement dbRequirement : dbRequirements) { + Requirement requirement = metadataFactory.createRequirement(dbRequirement.getNamespace(), dbRequirement.getId()); + + loadRequirementAttributes(requirement, dbRequirement.getRequirementId(), session); + loadRequirementDirectives(requirement, dbRequirement.getRequirementId(), session); + + requirements.put(dbRequirement.getRequirementId(), requirement); + + if (dbRequirement.getRequirementId() == dbRequirement.getParentRequirementId()) { + assert dbRequirement.getLevel() == 0; + + if (dbRequirement.getCapabilityId() != null) { + capabilityRequirements.put(dbRequirement.getCapabilityId(), requirement); + } else { + resource.addRequirement(requirement); + } + } else { + Requirement parent = requirements.get(dbRequirement.getParentRequirementId()); + if (parent != null) { + parent.addChild(requirement); + } else { + logger.warn("There is unprocessed requirement (missing parent) for resource {}, ID: {}, parent ID: {}.", + resourceId, dbRequirement.getRequirementId(), dbRequirement.getParentRequirementId()); + unprocessedRequirements.put(dbRequirement.getRequirementId(), dbRequirement.getParentRequirementId()); + } + } + } + + assert unprocessedRequirements.isEmpty(); + + while (!unprocessedRequirements.isEmpty()) { + Iterator> iterator = unprocessedRequirements.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + Requirement parent = requirements.get(entry.getValue()); + if (parent != null) { + Requirement requirement = requirements.get(entry.getKey()); + parent.addChild(requirement); + iterator.remove(); + } + } + } + + return capabilityRequirements; + } + + void loadCapabilities(Resource resource, long resourceId, Map requirements, SqlSession session) { + List dbCapabilities = session.selectList(RESOURCE_MAPPER + "selectCapabilities", resourceId); + + Map capabilities = new HashMap<>(dbCapabilities.size()); + Map unprocessedCapabilities = new HashMap<>(dbCapabilities.size()); // K: capability ID, V: capability parent ID + + for (DbCapability dbCapability : dbCapabilities) { + Capability capability = metadataFactory.createCapability(dbCapability.getNamespace(), dbCapability.getId()); + + loadCapabilityAttributes(capability, dbCapability.getCapabilityId(), session); + loadCapabilityDirectives(capability, dbCapability.getCapabilityId(), session); + loadProperties(capability, dbCapability.getCapabilityId(), session); + + Requirement requirement = requirements.get(dbCapability.getCapabilityId()); + if (requirement != null) { + capability.addRequirement(requirement); + } + + resource.addCapability(capability); + + capabilities.put(dbCapability.getCapabilityId(), capability); + + if (dbCapability.getCapabilityId() == dbCapability.getParentCapabilityId()) { + assert dbCapability.getLevel() == 0; + + resource.addRootCapability(capability); + } else { + Capability parent = capabilities.get(dbCapability.getParentCapabilityId()); + if (parent != null) { + parent.addChild(capability); + } else { + logger.warn("There is unprocessed capability (missing parent) for resource {}, ID: {}, parent ID: {}.", + resourceId, dbCapability.getCapabilityId(), dbCapability.getParentCapabilityId()); + unprocessedCapabilities.put(dbCapability.getCapabilityId(), dbCapability.getParentCapabilityId()); + } + } + } + + assert unprocessedCapabilities.isEmpty(); + + // Reconstruct capability tree structure - this would be optimized by MPTT or hierarchy leveling or: + // http://www.codeproject.com/Articles/8355/Trees-in-SQL-databases + while (!unprocessedCapabilities.isEmpty()) { + Iterator> iterator = unprocessedCapabilities.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + Capability parent = capabilities.get(entry.getValue()); + if (parent != null) { + Capability capability = capabilities.get(entry.getKey()); + parent.addChild(capability); + iterator.remove(); + } + } + } + } + + void loadProperties(Resource resource, long resourceId, SqlSession session) { + List dbProperties = session.selectList(RESOURCE_MAPPER + "selectResourceProperties", resourceId); + + for (DbProperty dbProperty : dbProperties) { + Property property = metadataFactory.createProperty(dbProperty.getNamespace(), dbProperty.getId()); + + loadResourcePropertyAttributes(property, dbProperty.getPropertyId(), session); + + resource.addProperty(property); + } + } + + void loadProperties(Capability capability, long resourceId, SqlSession session) { + List dbProperties = session.selectList(RESOURCE_MAPPER + "selectCapabilityProperties", resourceId); + + for (DbProperty dbProperty : dbProperties) { + Property property = metadataFactory.createProperty(dbProperty.getNamespace(), dbProperty.getId()); + + loadCapabilityPropertyAttributes(property, dbProperty.getPropertyId(), session); + + capability.addProperty(property); + } + } + + void loadCapabilityAttributes(Capability capability, long capabilityId, SqlSession session) { + List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectCapabilityAttributes", capabilityId); + + MetadataMapping.mapDbAttributes2Capability(dbAttributes, capability); + } + + void loadCapabilityDirectives(Capability capability, long capabilityId, SqlSession session) { + List dbDirectives = session.selectList(RESOURCE_MAPPER + "selectCapabilityDirectives", capabilityId); + + MetadataMapping.mapDbDirectives2Capability(dbDirectives, capability); + } + + void loadRequirementAttributes(Requirement requirement, long requirementId, SqlSession session) { + List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectRequirementAttributes", requirementId); + + MetadataMapping.mapDbAttributes2Requirement(dbAttributes, requirement); + } + + void loadRequirementDirectives(Requirement requirement, long requirementId, SqlSession session) { + List dbDirectives = session.selectList(RESOURCE_MAPPER + "selectRequirementDirectives", requirementId); + + MetadataMapping.mapDbDirectives2Requirement(dbDirectives, requirement); + } + + void loadResourcePropertyAttributes(Property property, long propertyId, SqlSession session) { + List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectResourcePropertyAttributes", propertyId); + + MetadataMapping.mapDbAttributes2Property(dbAttributes, property); + } + + void loadCapabilityPropertyAttributes(Property property, long propertyId, SqlSession session) { + List dbAttributes = session.selectList(RESOURCE_MAPPER + "selectCapabilityPropertyAttributes", propertyId); + + MetadataMapping.mapDbAttributes2Property(dbAttributes, property); + } + + @Override + public synchronized List loadResources(Repository repository) throws IOException { + logger.debug("loadResources(repository={})", repository); + + List result = Collections.emptyList(); + try (SqlSession session = sessionManager.getSession()) { + Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); + + if (repositoryId != null) { + List dbResources = session.selectList(RESOURCE_MAPPER + "selectResourcesByRepositoryId", repositoryId); + if (dbResources != null && !dbResources.isEmpty()) { + result = new ArrayList<>(dbResources.size()); + for (DbResource dbResource : dbResources) { + // TODO optimize - select in loop + Resource resource = loadResource(dbResource, session); + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + result.add(resource); + } + } + } + } catch (PersistenceException e) { + throw new IOException("Could not load resources.", e); + } + + if (logger.isTraceEnabled()) { + logger.trace("loadResources(repository={}) returns {}", repository, result); + } else { + logger.debug("loadResources(repository={) returns {}", repository, result.size()); + } + + return result; + } + + @Override + public List loadResources(@Nonnull Repository repository, @Nonnull ResourceDAOFilter filter) throws IOException { + logger.debug("loadResources(repository={}, filter={})", repository, + logger.isTraceEnabled() ? filter.toString() : "(" + filter.getCapabilityFilters().size() + ")"); + + List result = Collections.emptyList(); + try (SqlSession session = sessionManager.getSession()) { + Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); + + if (repositoryId != null) { + List dbResources = session.getMapper(ResolvingMapper.class).getResources(repositoryId, filter); + + if (dbResources != null && !dbResources.isEmpty()) { + result = new ArrayList<>(dbResources.size()); + for (DbResource dbResource : dbResources) { + // TODO optimize - select in loop + Resource resource = loadResource(dbResource, session); + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + result.add(resource); + } + } + } + + } catch (PersistenceException e) { + throw new IOException("Could not load resources.", e); + } + + if (logger.isTraceEnabled()) { + logger.trace("loadResources(repository={}, filter={}) returns {}", + repository, filter.toString() + "(" + filter.getCapabilityFilters().size() + ")", result); + } else { + logger.debug("loadResources(repository={}, filter={}) returns {}", + repository, "(" + filter.getCapabilityFilters().size() + ")", result.size()); + } + + return result; + } + + @Override + public synchronized void saveResource(Resource resource) throws IOException { + logger.debug("saveResource(resource={})", resource); + + try (SqlSession session = sessionManager.getSession()) { + /* + * Workaround for updating of existing resources: Resource is deleted and then re-inserted + * until some update solution will be implemented. This solution wastes internal unique IDs, + * because a new ID is generated on each insertion. + */ + if (existsResource(resource.getId())) { + session.delete(RESOURCE_MAPPER + "deleteResourceById", resource.getId()); + logger.trace("Update workaround: existing resource {} was deleted before insert.", resource.getId()); + } + + SequenceMapper seqMapper = session.getMapper(SequenceMapper.class); + + DbResource dbResource = MetadataMapping.mapResource2DbResource(resource, metadataService); + + long resourceId = seqMapper.nextVal("resource_seq"); + dbResource.setResourceId(resourceId); + + String repositoryUuid = metadataService.getIdentity(resource) + .getAttributeValue(new SimpleAttributeType<>("repository-id", String.class)); + + if (repositoryUuid == null) { + throw new IllegalArgumentException("Repository is not set on resource: " + resource.getId()); + } + + Long repositoryId = repositoryDAOImpl.getRepositoryId(repositoryUuid, session); + if (repositoryId == null) { + throw new IllegalArgumentException("Repository doesn't exist: " + repositoryUuid); + } + + dbResource.setRepositoryId(repositoryId); + + session.insert(RESOURCE_MAPPER + "insertResource", dbResource); + + // capabilities + for (Capability capability : resource.getRootCapabilities()) { + saveCapabilityRecursive(capability, resourceId, null, 0, session, seqMapper); + } + + // requirements + for (Requirement requirement : resource.getRequirements()) { + saveRequirementRecursive(requirement, resourceId, null, null, 0, session, seqMapper); + } + + // properties + for (Property property : resource.getProperties()) { + saveResourceProperty(property, resourceId, session, seqMapper); + } + + session.commit(); + } catch (PersistenceException e) { + throw new IOException("Could not save resource.", e); + } + + logger.debug("saveResource(resource) returns", resource); + } + + private void saveCapabilityRecursive(Capability capability, long resourceId, Long parentId, int level, + SqlSession session, SequenceMapper seqMapper) { + + DbCapability dbCapability = MetadataMapping.mapCapability2DbCapability(capability, metadataService); + dbCapability.setResourceId(resourceId); + dbCapability.setLevel(level); + + long capabilityId = seqMapper.nextVal("capability_seq"); + dbCapability.setCapabilityId(capabilityId); + dbCapability.setParentCapabilityId(parentId != null ? parentId : capabilityId); + + session.insert(RESOURCE_MAPPER + "insertCapability", dbCapability); + + List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(capability.getAttributes(), capabilityId); + if (!dbAttributes.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertCapabilityAttributes", dbAttributes); + } + + List dbDirectives = MetadataMapping.mapDirectives2DbDirectives(capability.getDirectives(), capabilityId); + if (!dbDirectives.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertCapabilityDirectives", dbDirectives); + } + + for (Requirement requirement : capability.getRequirements()) { + saveRequirementRecursive(requirement, resourceId, null, capabilityId, 0, session, seqMapper); + } + + for (Property property : capability.getProperties()) { + saveCapabilityProperty(property, capabilityId, session, seqMapper); + } + + for (Capability child : capability.getChildren()) { + saveCapabilityRecursive(child, resourceId, capabilityId, level + 1, session, seqMapper); + } + } + + private void saveRequirementRecursive(Requirement requirement, long resourceId, Long parentId, Long capabilityId, int level, + SqlSession session, SequenceMapper seqMapper) { + + DbRequirement dbRequirement = MetadataMapping.mapRequirement2DbRequirement(requirement, metadataService); + dbRequirement.setResourceId(resourceId); + dbRequirement.setCapabilityId(capabilityId); + dbRequirement.setLevel(level); + + long requirementId = seqMapper.nextVal("requirement_seq"); + dbRequirement.setRequirementId(requirementId); + dbRequirement.setParentRequirementId(parentId != null ? parentId : requirementId); + + session.insert(RESOURCE_MAPPER + "insertRequirement", dbRequirement); + + List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(requirement.getAttributes(), requirementId, true); + if (!dbAttributes.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertRequirementAttributes", dbAttributes); + } + + List dbDirectives = MetadataMapping.mapDirectives2DbDirectives(requirement.getDirectives(), requirementId); + if (!dbDirectives.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertRequirementDirectives", dbDirectives); + } + + for (Requirement child : requirement.getChildren()) { + saveRequirementRecursive(child, resourceId, requirementId, capabilityId, level + 1, session, seqMapper); + } + } + + private void saveResourceProperty(Property property, long resourceId, SqlSession session, SequenceMapper seqMapper) { + long propertyId = seqMapper.nextVal("resource_property_seq"); + DbProperty dbProperty = MetadataMapping.mapProperty2DbProperty(property, propertyId, resourceId, metadataService); + + session.insert(RESOURCE_MAPPER + "insertResourceProperty", dbProperty); + + List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(property.getAttributes(), propertyId); + if (!dbAttributes.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertResourcePropertyAttributes", dbAttributes); + } + } + + private void saveCapabilityProperty(Property property, long capabilityId, SqlSession session, SequenceMapper seqMapper) { + long propertyId = seqMapper.nextVal("capability_property_seq"); + DbProperty dbProperty = MetadataMapping.mapProperty2DbProperty(property, propertyId, capabilityId, metadataService); + + session.insert(RESOURCE_MAPPER + "insertCapabilityProperty", dbProperty); + + List dbAttributes = MetadataMapping.mapAttributes2DbAttributes(property.getAttributes(), propertyId); + if (!dbAttributes.isEmpty()) { + session.insert(RESOURCE_MAPPER + "insertCapabilityPropertyAttributes", dbAttributes); + } + } + + @Override + public synchronized void deleteResource(URI uri) throws IOException { + logger.debug("deleteResource(uri={})", uri); + + try (SqlSession session = sessionManager.getSession()) { + DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); + + if (dbResource != null) { + long resourceId = dbResource.getResourceId(); + session.delete(RESOURCE_MAPPER + "deleteResourceByResourceId", resourceId); + session.commit(); + } + } catch (PersistenceException e) { + throw new IOException("Could not delete resource.", e); + } + + logger.debug("deleteResource(uri) returns"); + } + + @Override + public synchronized boolean existsResource(URI uri) throws IOException { // TODO just simple select, check if return null + logger.debug("existsResource(uri={})", uri); + + boolean result = false; + try (SqlSession session = sessionManager.getSession()) { + if (session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()) != null) { + result = true; + } + } catch (PersistenceException e) { + throw new IOException("Could not check presence of resource.", e); + } + + logger.debug("existsResource(uri) returns {}", result); + + return result; + } + + @Override + public boolean existsResource(URI uri, Repository repository) throws IOException { // not needed + logger.debug("existsResource(uri={}, repository={})", uri, repository); + + boolean result = false; + try (SqlSession session = sessionManager.getSession()) { + Long repositoryId = repositoryDAOImpl.getRepositoryId(repository.getId(), session); + + DbResource dbResource = session.selectOne(RESOURCE_MAPPER + "selectResourceByUri", uri.toString()); + if (dbResource != null && dbResource.getRepositoryId() == repositoryId) { + result = true; + } + } catch (PersistenceException e) { + throw new IOException("Could not check presence of resource.", e); + } + + logger.debug("existsResource(uri, repository) returns {}", result); + + return result; + } + + private boolean existsResource(@Nonnull String id) throws IOException { + boolean result = false; + + try (SqlSession session = sessionManager.getSession()) { + if (session.selectOne(RESOURCE_MAPPER + "selectResourceById", id) != null) { + result = true; + } + } catch (PersistenceException e) { + throw new IOException("Could not check presence of resource.", e); + } + + return result; + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/SessionManager.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/SessionManager.java index fde610ca..b6bd577b 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/SessionManager.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/SessionManager.java @@ -1,204 +1,204 @@ -package cz.zcu.kiv.crce.metadata.dao.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Dictionary; -import java.util.Properties; - -import javax.annotation.Nonnull; - -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ConfigurationDependency; -import org.apache.felix.dm.annotation.api.Init; -import org.apache.felix.dm.annotation.api.LifecycleController; -import org.apache.felix.dm.annotation.api.Start; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.session.Configuration; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.googlecode.flyway.core.Flyway; -import com.googlecode.flyway.core.api.FlywayException; - -import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; -import cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResolvingMapper; - - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides={SessionManager.class}) -public class SessionManager implements ManagedService { - - private static final Logger logger = LoggerFactory.getLogger(SessionManager.class); - - protected static final String MYBATIS_DEFAULT_CONFIG = "META-INF/mybatis/config.xml"; - - protected static final String CFG__JDBC_DRIVER = "jdbc.driver"; - protected static final String CFG__JDBC_URL = "jdbc.url"; - protected static final String CFG__JDBC_USERNAME = "jdbc.username"; - protected static final String CFG__JDBC_PASSWORD = "jdbc.password"; - protected static final String CFG__MYBATIS_CONFIG = "mybatis.config"; - - private SqlSessionFactory factory; - private Properties properties; - - @LifecycleController - Runnable lifeCycleController; - - /* - * Won't run until a configuration is passed to ManagedService - */ - @Init - void init() { - logger.info("Initializing DB structure."); - - try { - ClassLoader tmp = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); - // ^ class loader workaround, see http://skysailserver.blogspot.cz/2013/11/using-flyway-with-osgi-part-one.html - - Flyway flyway = new Flyway(); - flyway.setDataSource(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password")); - - flyway.migrate(); - - // v class loader workaround - Thread.currentThread().setContextClassLoader(tmp); - - // starts the component only if initialization is successful - lifeCycleController.run(); - } catch (FlywayException e) { - logger.error("Could not initialize DB.", e); - } - - logger.info("DB structure initialized."); - } - - @Start - void start() { - logger.info("CRCE Metadata DAO SessionManager started."); - } - - /** - * Opens and returns new session. - * @return session. - * @throws IOException - */ - public synchronized SqlSession getSession() throws IOException { - if (factory != null) { - return factory.openSession(); - } else if (properties != null) { - String config = (String) properties.get("config"); - if (config != null && createFactory(config, properties)) { - return factory.openSession(); - } - } - throw new IllegalStateException("Could not create MyBatis SqlSessionFactory."); - } - - /** - * Creates new SqlSessionFactory. - * - * @param config MyBatis configuration file path. - * @param properties Configuration properties. - * @return true if factory was created. - * @throws IOException Thrown when the given configuration file can't be opened. - */ - private boolean createFactory(@Nonnull String config, @Nonnull Properties properties) throws IOException { - Resources.setDefaultClassLoader(getClass().getClassLoader()); - try (InputStream is = Resources.getResourceAsStream(config)) { - factory = new SqlSessionFactoryBuilder().build(is, properties); - factoryPostConfiguration(factory.getConfiguration()); - } catch (RuntimeException e) { // thrown by build() - logger.error("Could not create MyBatis SqlSessionFactory.", e); - return false; - } - return true; - } - - private void factoryPostConfiguration(Configuration configuration) { - configuration.addMapper(ResolvingMapper.class); - configuration.addMapper(SequenceMapper.class); - } - - @Override - @ConfigurationDependency(pid = Activator.PID) - public synchronized void updated(Dictionary dict) throws ConfigurationException { - logger.debug("Configuring CRCE SessionManager."); - - if (dict != null) { - @SuppressWarnings("LocalVariableHidesMemberVariable") - Properties properties = new Properties(); - - String driver = getProperty(dict, CFG__JDBC_DRIVER); - if (driver == null) { - throw new ConfigurationException(CFG__JDBC_DRIVER, "JDBC driver must be specified."); - } - properties.put("driver", driver); - - String url = getProperty(dict, CFG__JDBC_URL); - if (url == null) { - throw new ConfigurationException(CFG__JDBC_URL, "JDBC URL must be specified."); - } - properties.put("url", url); - - properties.put("username", getProperty(dict, CFG__JDBC_USERNAME, "")); - properties.put("password", getProperty(dict, CFG__JDBC_PASSWORD, "")); - - String config = getProperty(dict, CFG__MYBATIS_CONFIG, MYBATIS_DEFAULT_CONFIG); - if (config.isEmpty()) { - config = MYBATIS_DEFAULT_CONFIG; - } - - try { - if (createFactory(config, properties)) { - // Factory is created, so the new setting can be used as a default setting. - properties.put("config", config); - this.properties = new Properties(properties); - } - } catch (IOException e) { // thrown by getResourceAsStream() - throw new ConfigurationException(CFG__MYBATIS_CONFIG, "Could not open MyBatis configuration file.", e); - } - } - logger.debug("CRCE Metadata DAO SessionManager configured."); - } - - /** - * Helper method to safely obtain a property value from the given dictionary. - * - * @param properties the dictionary to retrieve the value from, can be null; - * @param key the name of the property to retrieve, cannot be null; - * @param defaultValue the default value to return in case the property does not exist, or the given dictionary was null. - * @return a property value, can be null. - */ - private String getProperty(Dictionary properties, String key, String defaultValue) { - String value = getProperty(properties, key); - return (value == null) ? defaultValue : value; - } - - /** - * Helper method to safely obtain a property value from the given dictionary. - * - * @param properties the dictionary to retrieve the value from, can be null; - * @param key the name of the property to retrieve, cannot be null. - * @return a property value, can be null. - */ - private String getProperty(Dictionary properties, String key) { - if (properties != null) { - Object value = properties.get(key); - if (value != null && value instanceof String) { - return (String) value; - } - } - return null; - } -} +package cz.zcu.kiv.crce.metadata.dao.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Dictionary; +import java.util.Properties; + +import javax.annotation.Nonnull; + +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ConfigurationDependency; +import org.apache.felix.dm.annotation.api.Init; +import org.apache.felix.dm.annotation.api.LifecycleController; +import org.apache.felix.dm.annotation.api.Start; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.googlecode.flyway.core.Flyway; +import com.googlecode.flyway.core.api.FlywayException; + +import cz.zcu.kiv.crce.metadata.dao.internal.mapper.SequenceMapper; +import cz.zcu.kiv.crce.metadata.dao.internal.mapper.ResolvingMapper; + + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides={SessionManager.class}) +public class SessionManager implements ManagedService { + + private static final Logger logger = LoggerFactory.getLogger(SessionManager.class); + + protected static final String MYBATIS_DEFAULT_CONFIG = "META-INF/mybatis/config.xml"; + + protected static final String CFG__JDBC_DRIVER = "jdbc.driver"; + protected static final String CFG__JDBC_URL = "jdbc.url"; + protected static final String CFG__JDBC_USERNAME = "jdbc.username"; + protected static final String CFG__JDBC_PASSWORD = "jdbc.password"; + protected static final String CFG__MYBATIS_CONFIG = "mybatis.config"; + + private SqlSessionFactory factory; + private Properties properties; + + @LifecycleController + Runnable lifeCycleController; + + /* + * Won't run until a configuration is passed to ManagedService + */ + @Init + void init() { + logger.info("Initializing DB structure."); + + try { + ClassLoader tmp = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + // ^ class loader workaround, see http://skysailserver.blogspot.cz/2013/11/using-flyway-with-osgi-part-one.html + + Flyway flyway = new Flyway(); + flyway.setDataSource(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password")); + + flyway.migrate(); + + // v class loader workaround + Thread.currentThread().setContextClassLoader(tmp); + + // starts the component only if initialization is successful + lifeCycleController.run(); + } catch (FlywayException e) { + logger.error("Could not initialize DB.", e); + } + + logger.info("DB structure initialized."); + } + + @Start + void start() { + logger.info("CRCE Metadata DAO SessionManager started."); + } + + /** + * Opens and returns new session. + * @return session. + * @throws IOException + */ + public synchronized SqlSession getSession() throws IOException { + if (factory != null) { + return factory.openSession(); + } else if (properties != null) { + String config = (String) properties.get("config"); + if (config != null && createFactory(config, properties)) { + return factory.openSession(); + } + } + throw new IllegalStateException("Could not create MyBatis SqlSessionFactory."); + } + + /** + * Creates new SqlSessionFactory. + * + * @param config MyBatis configuration file path. + * @param properties Configuration properties. + * @return true if factory was created. + * @throws IOException Thrown when the given configuration file can't be opened. + */ + private boolean createFactory(@Nonnull String config, @Nonnull Properties properties) throws IOException { + Resources.setDefaultClassLoader(getClass().getClassLoader()); + try (InputStream is = Resources.getResourceAsStream(config)) { + factory = new SqlSessionFactoryBuilder().build(is, properties); + factoryPostConfiguration(factory.getConfiguration()); + } catch (RuntimeException e) { // thrown by build() + logger.error("Could not create MyBatis SqlSessionFactory.", e); + return false; + } + return true; + } + + private void factoryPostConfiguration(Configuration configuration) { + configuration.addMapper(ResolvingMapper.class); + configuration.addMapper(SequenceMapper.class); + } + + @Override + @ConfigurationDependency(pid = Activator.PID) + public synchronized void updated(Dictionary dict) throws ConfigurationException { + logger.debug("Configuring CRCE SessionManager."); + + if (dict != null) { + @SuppressWarnings("LocalVariableHidesMemberVariable") + Properties properties = new Properties(); + + String driver = getProperty(dict, CFG__JDBC_DRIVER); + if (driver == null) { + throw new ConfigurationException(CFG__JDBC_DRIVER, "JDBC driver must be specified."); + } + properties.put("driver", driver); + + String url = getProperty(dict, CFG__JDBC_URL); + if (url == null) { + throw new ConfigurationException(CFG__JDBC_URL, "JDBC URL must be specified."); + } + properties.put("url", url); + + properties.put("username", getProperty(dict, CFG__JDBC_USERNAME, "")); + properties.put("password", getProperty(dict, CFG__JDBC_PASSWORD, "")); + + String config = getProperty(dict, CFG__MYBATIS_CONFIG, MYBATIS_DEFAULT_CONFIG); + if (config.isEmpty()) { + config = MYBATIS_DEFAULT_CONFIG; + } + + try { + if (createFactory(config, properties)) { + // Factory is created, so the new setting can be used as a default setting. + properties.put("config", config); + this.properties = new Properties(properties); + } + } catch (IOException e) { // thrown by getResourceAsStream() + throw new ConfigurationException(CFG__MYBATIS_CONFIG, "Could not open MyBatis configuration file.", e); + } + } + logger.debug("CRCE Metadata DAO SessionManager configured."); + } + + /** + * Helper method to safely obtain a property value from the given dictionary. + * + * @param properties the dictionary to retrieve the value from, can be null; + * @param key the name of the property to retrieve, cannot be null; + * @param defaultValue the default value to return in case the property does not exist, or the given dictionary was null. + * @return a property value, can be null. + */ + private String getProperty(Dictionary properties, String key, String defaultValue) { + String value = getProperty(properties, key); + return (value == null) ? defaultValue : value; + } + + /** + * Helper method to safely obtain a property value from the given dictionary. + * + * @param properties the dictionary to retrieve the value from, can be null; + * @param key the name of the property to retrieve, cannot be null. + * @return a property value, can be null. + */ + private String getProperty(Dictionary properties, String key) { + if (properties != null) { + Object value = properties.get(key); + if (value != null && value instanceof String) { + return (String) value; + } + } + return null; + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbProperty.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbProperty.java index 3436c884..d47efc9b 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbProperty.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbProperty.java @@ -1,45 +1,45 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.db; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class DbProperty { - - private long propertyId; - private long parentId; - private String id; - private String namespace; - - public long getPropertyId() { - return propertyId; - } - - public void setPropertyId(long propertyId) { - this.propertyId = propertyId; - } - - public long getParentId() { - return parentId; - } - - public void setParentId(long parentId) { - this.parentId = parentId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } -} +package cz.zcu.kiv.crce.metadata.dao.internal.db; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class DbProperty { + + private long propertyId; + private long parentId; + private String id; + private String namespace; + + public long getPropertyId() { + return propertyId; + } + + public void setPropertyId(long propertyId) { + this.propertyId = propertyId; + } + + public long getParentId() { + return parentId; + } + + public void setParentId(long parentId) { + this.parentId = parentId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbRepository.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbRepository.java index 4e9be5ec..042c1420 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbRepository.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/db/DbRepository.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.db; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class DbRepository { - - private long repositoryId; - private String id; - private String uri; - - public long getRepositoryId() { - return repositoryId; - } - - public void setRepositoryId(long repositoryId) { - this.repositoryId = repositoryId; - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } -} +package cz.zcu.kiv.crce.metadata.dao.internal.db; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class DbRepository { + + private long repositoryId; + private String id; + private String uri; + + public long getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(long repositoryId) { + this.repositoryId = repositoryId; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/helper/SimpleStringBuilder.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/helper/SimpleStringBuilder.java index 6dd57317..8aae42f0 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/helper/SimpleStringBuilder.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/helper/SimpleStringBuilder.java @@ -1,31 +1,31 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.helper; - -/** - * Wrapper of StringBuilder which makes its usage more comfortable and clear. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class SimpleStringBuilder { - - private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - private final StringBuilder sb = new StringBuilder(); - - public void append(String... strings) { - append(true, strings); - } - - public void append(boolean newLine, String... strings) { - if (newLine && this.sb.length() != 0) { - this.sb.append(LINE_SEPARATOR); - } - for (String string : strings) { - this.sb.append(string); - } - } - - @Override - public String toString() { - return this.sb.toString(); - } - -} +package cz.zcu.kiv.crce.metadata.dao.internal.helper; + +/** + * Wrapper of StringBuilder which makes its usage more comfortable and clear. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class SimpleStringBuilder { + + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); + private final StringBuilder sb = new StringBuilder(); + + public void append(String... strings) { + append(true, strings); + } + + public void append(boolean newLine, String... strings) { + if (newLine && this.sb.length() != 0) { + this.sb.append(LINE_SEPARATOR); + } + for (String string : strings) { + this.sb.append(string); + } + } + + @Override + public String toString() { + return this.sb.toString(); + } + +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResolvingMapper.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResolvingMapper.java index 05aa7b6d..5ab9f561 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResolvingMapper.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResolvingMapper.java @@ -1,19 +1,19 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.mapper; - -import java.util.List; - -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.SelectProvider; - -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; -import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface ResolvingMapper { - - @SelectProvider(type = SqlFilterProvider.class, method = "generateSQL") - List getResources(@Param(SqlFilterProvider.PARAM_REPOSITORY_ID) long repositoryId, @Param(SqlFilterProvider.PARAM_FILTER) ResourceDAOFilter filter); -} +package cz.zcu.kiv.crce.metadata.dao.internal.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.SelectProvider; + +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; +import cz.zcu.kiv.crce.metadata.dao.internal.db.DbResource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface ResolvingMapper { + + @SelectProvider(type = SqlFilterProvider.class, method = "generateSQL") + List getResources(@Param(SqlFilterProvider.PARAM_REPOSITORY_ID) long repositoryId, @Param(SqlFilterProvider.PARAM_FILTER) ResourceDAOFilter filter); +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SequenceMapper.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SequenceMapper.java index df79c8d2..01878f71 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SequenceMapper.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SequenceMapper.java @@ -1,15 +1,15 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.mapper; - -import org.apache.ibatis.annotations.Options; -import org.apache.ibatis.annotations.Select; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface SequenceMapper { - - @Select("select nextval(#{sequence})") - @Options(flushCache = true) - long nextVal(String sequence); -} +package cz.zcu.kiv.crce.metadata.dao.internal.mapper; + +import org.apache.ibatis.annotations.Options; +import org.apache.ibatis.annotations.Select; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface SequenceMapper { + + @Select("select nextval(#{sequence})") + @Options(flushCache = true) + long nextVal(String sequence); +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProvider.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProvider.java index 706c2a6d..4c8c776d 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProvider.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProvider.java @@ -1,459 +1,459 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.mapper; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.ibatis.jdbc.SQL; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; -import cz.zcu.kiv.crce.metadata.dao.internal.helper.SimpleStringBuilder; -import cz.zcu.kiv.crce.metadata.dao.internal.type.DbAttributeType; - -/** - * - * Example for ORed CapabilityFilters - * - SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r - JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID - JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID - WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' - AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true)))) - UNION - SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r - JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID - WHERE (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'org.danekja.java.util.function.serializable') - - - Example for ANDed CapabilityFilters - - SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r - JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID - JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID - JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID - WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' - AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true))) - ) - AND (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow') - - * - * Date: 10.3.16 - * - * @author Jakub Danek - */ -public class SqlFilterProvider { - - public static final String PARAM_REPOSITORY_ID = "repositoryId"; - public static final String PARAM_FILTER = "filter"; - - private static final String PREFIX_CAPABILITY = "c"; - private static final String PREFIX_ATTRIBUTE = "a"; - private static final Logger logger = LoggerFactory.getLogger(SqlFilterProvider.class); - - /** - * - * @param params expected params are: - *

    - *
  • Long repositoryId
  • - *
  • ResourceDAOFilter filter
  • - *
- * @return generated SQL string for the search - */ - public String generateSQL(Map params) { - logger.debug("generateSQL({})", params); - - @SuppressWarnings("unchecked") - ResourceDAOFilter filter = (ResourceDAOFilter) params.get(PARAM_FILTER); - - switch (filter.getOperator()) { - case OR: - return generateOrSQL(filter.getCapabilityFilters()); - case AND: - default: - return generateAndSQL(filter.getCapabilityFilters()); - } - } - - /** - * Generates SQL query in which individual Capability filters are joined using OR - * @param filters list of capability constraints - * @return SQL query - */ - private String generateOrSQL(List filters) { - StringBuilder output = new StringBuilder(); - SQL sql; - - for (int i = 0; i < filters.size(); i++) { - sql = startQuery(); - processRootCapabilityJoin(sql, filters.get(i), i); - sql.WHERE("r.repository_id = #{repositoryId}"); - processRootCapabilityWhere(sql, filters.get(i), i); - - if(output.length() > 0) { - output.append(" UNION "); - } - output.append(sql); - } - - return output.toString(); - } - - /** - * Generates SQL query in which individual Capability filters are joined using AND - * @param filters list of capability constraints - * @return SQL query - */ - private String generateAndSQL(List filters) { - SQL sql = startQuery(); - - for (int i = 0; i < filters.size(); i++) { - processRootCapabilityJoin(sql, filters.get(i), i); - } - - sql.WHERE("r.repository_id = #{repositoryId}"); - - - for (int i = 0; i < filters.size(); i++) { - processRootCapabilityWhere(sql, filters.get(i), i); - } - - return sql.toString(); - } - - private SQL startQuery() { - SQL sql = new SQL(); - return sql.SELECT("DISTINCT r.resource_id, r.repository_id, r.id, r.uri").FROM("resource r"); - } - - /** - * Generate JOIN clause related to a root capability filter - * @param sql existing sql - * @param filter root capability filter - * @param index index of the filter in the filters list - */ - private void processRootCapabilityJoin(SQL sql, CapabilityFilter filter, int index) { - String capabilityAlias = createRootCapabilityAlias(index); - sql.JOIN("capability " + capabilityAlias + " ON " + capabilityAlias + ".resource_id = r.resource_id"); - processAttributesJoin(sql, filter.getAttributes(), capabilityAlias); - - processSubCapabilitiesJoin(sql, filter, capabilityAlias); - } - - /** - * Generate WHERE clause related to a root capability filter - * @param sql existing sql - * @param filter root capability filter - * @param index index of the filter in the filters list - */ - private void processRootCapabilityWhere(SQL sql, CapabilityFilter filter, int index) { - SimpleStringBuilder builder = new SimpleStringBuilder(); - List filterPath = new LinkedList<>(); - filterPath.add(index); - processCapabilityWhere(builder, createRootCapabilityAlias(index), filter, filterPath); - sql.WHERE(builder.toString()); - } - - /** - * Generates portion of the query for subcapability JOIN - * - * @param sql already existing portion of the SQL, presumed to have at least SELECT and FROM clauses. - * @param filter filter for the particular subcapability - * @param parentCapabilityAlias alias of the subcapability's parent in the #sql query - */ - private void processSubCapabilitiesJoin(SQL sql, CapabilityFilter filter, String parentCapabilityAlias) { - String subAlias; - CapabilityFilter subFilter; - for (int k = 0; k < filter.getSubFilters().size(); k++) { - subFilter = filter.getSubFilters().get(k); - - subAlias = parentCapabilityAlias + k; - sql.INNER_JOIN("capability " + subAlias + " ON " + parentCapabilityAlias + ".capability_id = " + subAlias + ".parent_capability_id"); - - processAttributesJoin(sql, subFilter.getAttributes(), subAlias); - - processSubCapabilitiesJoin(sql, subFilter, subAlias); - } - } - - /** - * Generates portion of the query for subcapability WHERE - * - * @param sql already existing portion of the SQL, with SELECT and FROM clauses finished - * @param capabilityAlias alias of the capability for which the condition is to be made - * @param filter filter describing the condition - * @param filterPath indexes into the capability lists up to the root starting from this capability filter. It is used - * to give MyBatis information where to look for parameter values - */ - private void processCapabilityWhere(SimpleStringBuilder sql, String capabilityAlias, CapabilityFilter filter, List filterPath) { - sql.append("(", capabilityAlias, ".namespace = "); - buildParameterValuePath(sql, filterPath, null, "namespace"); - processAttributesWhere(sql, filter.getAttributes(), filterPath, capabilityAlias); - - for (int i = 0; i < filter.getSubFilters().size(); i++) { - List path = new LinkedList<>(filterPath); - path.add(i); - - sql.append(" AND "); - - processCapabilityWhere(sql, capabilityAlias + i, filter.getSubFilters().get(i), path); - } - sql.append(")"); - } - - /** - * Generates portion of the query for attribute JOIN - * - * @param sql already existing portion of the SQL, presumed to have at least SELECT and FROM clauses. - * @param attributes list of attribute constraints for the capability with #capabilityAlias - * @param capabilityAlias alias of the capability to which these attribute constraints belong - */ - private void processAttributesJoin(SQL sql, List> attributes, String capabilityAlias) { - String attributeAlias; - for (int j = 0; j < attributes.size(); j++) { - attributeAlias = createAttributeAlias(capabilityAlias, j); - sql.INNER_JOIN("capability_attribute " + attributeAlias + " ON " + attributeAlias + ".capability_id = " + capabilityAlias + ".capability_id"); - } - } - - /** - * Generates portion of the query for attribute WHEREs - * - * @param sql already existing portion of the SQL, with SELECT and FROM clauses finished - * @param capabilityAlias alias of the capability to which these attribute constraints belong - * @param attributes list of attribute constraints for the capability with #capabilityAlias - * @param capabilityFilterIndexes indexes into the capability lists up to the root starting from this capability filter. It is used - * to give MyBatis information where to look for parameter values - */ - private void processAttributesWhere(SimpleStringBuilder sql, List> attributes, List capabilityFilterIndexes, String capabilityAlias) { - String attributeAlias; - Attribute at; - for (int j = 0; j < attributes.size(); j++) { - sql.append(" AND "); - attributeAlias = createAttributeAlias(capabilityAlias, j); - at = attributes.get(j); - - sql.append(false, attributeAlias, ".name = "); - buildParameterValuePath(sql, capabilityFilterIndexes, j, "name"); - - sql.append(" AND "); - evaluateAttribute(sql, at, capabilityFilterIndexes, j, attributeAlias); - } - } - - /** - * Helper method for generating capability attribute alias - * - * @param capabilityAlias alias of the capability the attribute belongs to - * @param index index of the attribute in the filter - * @return alias for the attribute - */ - private String createAttributeAlias(String capabilityAlias, int index) { - return capabilityAlias + PREFIX_ATTRIBUTE + index; - } - - /** - * Helper method for generating root capability alias - * - * @param index index of the root capability - * @return alias for the capability - */ - private String createRootCapabilityAlias(int index) { - return PREFIX_CAPABILITY + index; - } - - private void evaluateAttribute(SimpleStringBuilder sb, Attribute attribute, List capabilityFilterIndexes, int attributeIndex, String alias) { - switch (DbAttributeType.fromClass(attribute.getType())) { - case DOUBLE: - sb.append(false, alias, ".double_value"); - evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - break; - - case LONG: - sb.append(false, alias, ".long_value"); - evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - break; - - case STRING: - sb.append(false, alias, ".string_value"); - evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - break; - - case URI: - sb.append(false, alias, ".string_value"); - evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - break; - - case VERSION: - sb.append(false, "("); - evaluateVersion(sb, alias, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - sb.append(false, ")"); - break; - - case BOOLEAN: - sb.append(false, alias, ".boolean_value"); - evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); - break; - - case LIST: - throw new UnsupportedOperationException(); - } - - } - - private void evaluateOperator(SimpleStringBuilder sb, cz.zcu.kiv.crce.metadata.Operator operator, List subFilterPath, int attributeIndex) { - switch (operator) { - case EQUAL: - sb.append(false, " = "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - case NOT_EQUAL: - sb.append(false, " <> "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - case PRESENT: - sb.append(false, " is not null"); - break; - - case LESS: - sb.append(false, " < "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - case LESS_EQUAL: - sb.append(false, " <= "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - case GREATER: - sb.append(false, " > "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - case GREATER_EQUAL: - sb.append(false, " >= "); - buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); - break; - - default: - throw new UnsupportedOperationException("Operator " + operator + " is not supported for ... type."); - - } - } - - private void evaluateVersion(SimpleStringBuilder sb, String alias, cz.zcu.kiv.crce.metadata.Operator operator, List subFilterPath, int attributeIndex) { - switch (operator) { - case EQUAL: - sb.append(false, alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " AND ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " AND ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " AND ", alias, ".string_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - break; - - case NOT_EQUAL: - sb.append(false, alias, ".version_major_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " OR ", alias, ".version_minor_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " OR ", alias, ".version_micro_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " OR ", alias, ".string_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - break; - - case PRESENT: - sb.append(false, alias, ".version_major_value is not null"); - sb.append(false, " AND ", alias, ".version_minor_value is not null"); - sb.append(false, " AND ", alias, ".version_micro_value is not null"); - sb.append(false, " AND ", alias, ".string_value is not null"); - break; - - case LESS: - sb.append(false, alias, ".version_major_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_minor_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_micro_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); - sb.append(false, alias, ".string_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - sb.append(false, ")))"); - break; - - case LESS_EQUAL: - sb.append(false, alias, ".version_major_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_minor_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_micro_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); - sb.append(false, alias, ".string_value <= "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - sb.append(false, ")))"); - break; - - case GREATER: - sb.append(false, alias, ".version_major_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_minor_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_micro_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); - sb.append(false, alias, ".string_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - sb.append(false, ")))"); - break; - - case GREATER_EQUAL: - sb.append(false, alias, ".version_major_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_minor_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); - sb.append(false, alias, ".version_micro_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); - sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); - sb.append(false, alias, ".string_value >= "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); - sb.append(false, ")))"); - break; - - case APPROX: - sb.append(false, alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); - sb.append(false, " AND ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); - break; - - default: - throw new UnsupportedOperationException("Operator " + operator + " is not supported for Version type."); - - } - } - - /** - * Builds value portion of the query using MyBatis mechanism for specifying values in queries based on parameter objects. - * - * The value path expects #ResourceDAOFilter with name filter to be present among the parameters. - * - * @param builder string builder used to create the portion of the query - * @param capabilityFilterIndexes indexes into the capability filter tree (one per level) specifying the path from root to the capability owning the attribute - * @param attributeIndex index of the attribute within the capability specified by the #capabilityFilterIndexes - * @param valuePath name of the value column for that particular attribute type - */ - private void buildParameterValuePath(SimpleStringBuilder builder, List capabilityFilterIndexes, Integer attributeIndex, String valuePath) { - Iterator it = capabilityFilterIndexes.iterator(); - - builder.append(false, "#{filter.capabilityFilters[", it.next().toString(), "]"); - while(it.hasNext()) { - builder.append(false, ".subFilters[", it.next().toString(), "]"); - } - if(attributeIndex != null) { - builder.append(false, ".attributes[", attributeIndex.toString(), "]"); - } - builder.append(false, ".", valuePath, "}"); - } - -} +package cz.zcu.kiv.crce.metadata.dao.internal.mapper; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.ibatis.jdbc.SQL; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; +import cz.zcu.kiv.crce.metadata.dao.internal.helper.SimpleStringBuilder; +import cz.zcu.kiv.crce.metadata.dao.internal.type.DbAttributeType; + +/** + * + * Example for ORed CapabilityFilters + * + SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r + JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID + JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID + WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' + AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true)))) + UNION + SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r + JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID + WHERE (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'org.danekja.java.util.function.serializable') + + + Example for ANDed CapabilityFilters + + SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r + JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID + JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID + JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID + WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' + AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true))) + ) + AND (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow') + + * + * Date: 10.3.16 + * + * @author Jakub Danek + */ +public class SqlFilterProvider { + + public static final String PARAM_REPOSITORY_ID = "repositoryId"; + public static final String PARAM_FILTER = "filter"; + + private static final String PREFIX_CAPABILITY = "c"; + private static final String PREFIX_ATTRIBUTE = "a"; + private static final Logger logger = LoggerFactory.getLogger(SqlFilterProvider.class); + + /** + * + * @param params expected params are: + *
    + *
  • Long repositoryId
  • + *
  • ResourceDAOFilter filter
  • + *
+ * @return generated SQL string for the search + */ + public String generateSQL(Map params) { + logger.debug("generateSQL({})", params); + + @SuppressWarnings("unchecked") + ResourceDAOFilter filter = (ResourceDAOFilter) params.get(PARAM_FILTER); + + switch (filter.getOperator()) { + case OR: + return generateOrSQL(filter.getCapabilityFilters()); + case AND: + default: + return generateAndSQL(filter.getCapabilityFilters()); + } + } + + /** + * Generates SQL query in which individual Capability filters are joined using OR + * @param filters list of capability constraints + * @return SQL query + */ + private String generateOrSQL(List filters) { + StringBuilder output = new StringBuilder(); + SQL sql; + + for (int i = 0; i < filters.size(); i++) { + sql = startQuery(); + processRootCapabilityJoin(sql, filters.get(i), i); + sql.WHERE("r.repository_id = #{repositoryId}"); + processRootCapabilityWhere(sql, filters.get(i), i); + + if(output.length() > 0) { + output.append(" UNION "); + } + output.append(sql); + } + + return output.toString(); + } + + /** + * Generates SQL query in which individual Capability filters are joined using AND + * @param filters list of capability constraints + * @return SQL query + */ + private String generateAndSQL(List filters) { + SQL sql = startQuery(); + + for (int i = 0; i < filters.size(); i++) { + processRootCapabilityJoin(sql, filters.get(i), i); + } + + sql.WHERE("r.repository_id = #{repositoryId}"); + + + for (int i = 0; i < filters.size(); i++) { + processRootCapabilityWhere(sql, filters.get(i), i); + } + + return sql.toString(); + } + + private SQL startQuery() { + SQL sql = new SQL(); + return sql.SELECT("DISTINCT r.resource_id, r.repository_id, r.id, r.uri").FROM("resource r"); + } + + /** + * Generate JOIN clause related to a root capability filter + * @param sql existing sql + * @param filter root capability filter + * @param index index of the filter in the filters list + */ + private void processRootCapabilityJoin(SQL sql, CapabilityFilter filter, int index) { + String capabilityAlias = createRootCapabilityAlias(index); + sql.JOIN("capability " + capabilityAlias + " ON " + capabilityAlias + ".resource_id = r.resource_id"); + processAttributesJoin(sql, filter.getAttributes(), capabilityAlias); + + processSubCapabilitiesJoin(sql, filter, capabilityAlias); + } + + /** + * Generate WHERE clause related to a root capability filter + * @param sql existing sql + * @param filter root capability filter + * @param index index of the filter in the filters list + */ + private void processRootCapabilityWhere(SQL sql, CapabilityFilter filter, int index) { + SimpleStringBuilder builder = new SimpleStringBuilder(); + List filterPath = new LinkedList<>(); + filterPath.add(index); + processCapabilityWhere(builder, createRootCapabilityAlias(index), filter, filterPath); + sql.WHERE(builder.toString()); + } + + /** + * Generates portion of the query for subcapability JOIN + * + * @param sql already existing portion of the SQL, presumed to have at least SELECT and FROM clauses. + * @param filter filter for the particular subcapability + * @param parentCapabilityAlias alias of the subcapability's parent in the #sql query + */ + private void processSubCapabilitiesJoin(SQL sql, CapabilityFilter filter, String parentCapabilityAlias) { + String subAlias; + CapabilityFilter subFilter; + for (int k = 0; k < filter.getSubFilters().size(); k++) { + subFilter = filter.getSubFilters().get(k); + + subAlias = parentCapabilityAlias + k; + sql.INNER_JOIN("capability " + subAlias + " ON " + parentCapabilityAlias + ".capability_id = " + subAlias + ".parent_capability_id"); + + processAttributesJoin(sql, subFilter.getAttributes(), subAlias); + + processSubCapabilitiesJoin(sql, subFilter, subAlias); + } + } + + /** + * Generates portion of the query for subcapability WHERE + * + * @param sql already existing portion of the SQL, with SELECT and FROM clauses finished + * @param capabilityAlias alias of the capability for which the condition is to be made + * @param filter filter describing the condition + * @param filterPath indexes into the capability lists up to the root starting from this capability filter. It is used + * to give MyBatis information where to look for parameter values + */ + private void processCapabilityWhere(SimpleStringBuilder sql, String capabilityAlias, CapabilityFilter filter, List filterPath) { + sql.append("(", capabilityAlias, ".namespace = "); + buildParameterValuePath(sql, filterPath, null, "namespace"); + processAttributesWhere(sql, filter.getAttributes(), filterPath, capabilityAlias); + + for (int i = 0; i < filter.getSubFilters().size(); i++) { + List path = new LinkedList<>(filterPath); + path.add(i); + + sql.append(" AND "); + + processCapabilityWhere(sql, capabilityAlias + i, filter.getSubFilters().get(i), path); + } + sql.append(")"); + } + + /** + * Generates portion of the query for attribute JOIN + * + * @param sql already existing portion of the SQL, presumed to have at least SELECT and FROM clauses. + * @param attributes list of attribute constraints for the capability with #capabilityAlias + * @param capabilityAlias alias of the capability to which these attribute constraints belong + */ + private void processAttributesJoin(SQL sql, List> attributes, String capabilityAlias) { + String attributeAlias; + for (int j = 0; j < attributes.size(); j++) { + attributeAlias = createAttributeAlias(capabilityAlias, j); + sql.INNER_JOIN("capability_attribute " + attributeAlias + " ON " + attributeAlias + ".capability_id = " + capabilityAlias + ".capability_id"); + } + } + + /** + * Generates portion of the query for attribute WHEREs + * + * @param sql already existing portion of the SQL, with SELECT and FROM clauses finished + * @param capabilityAlias alias of the capability to which these attribute constraints belong + * @param attributes list of attribute constraints for the capability with #capabilityAlias + * @param capabilityFilterIndexes indexes into the capability lists up to the root starting from this capability filter. It is used + * to give MyBatis information where to look for parameter values + */ + private void processAttributesWhere(SimpleStringBuilder sql, List> attributes, List capabilityFilterIndexes, String capabilityAlias) { + String attributeAlias; + Attribute at; + for (int j = 0; j < attributes.size(); j++) { + sql.append(" AND "); + attributeAlias = createAttributeAlias(capabilityAlias, j); + at = attributes.get(j); + + sql.append(false, attributeAlias, ".name = "); + buildParameterValuePath(sql, capabilityFilterIndexes, j, "name"); + + sql.append(" AND "); + evaluateAttribute(sql, at, capabilityFilterIndexes, j, attributeAlias); + } + } + + /** + * Helper method for generating capability attribute alias + * + * @param capabilityAlias alias of the capability the attribute belongs to + * @param index index of the attribute in the filter + * @return alias for the attribute + */ + private String createAttributeAlias(String capabilityAlias, int index) { + return capabilityAlias + PREFIX_ATTRIBUTE + index; + } + + /** + * Helper method for generating root capability alias + * + * @param index index of the root capability + * @return alias for the capability + */ + private String createRootCapabilityAlias(int index) { + return PREFIX_CAPABILITY + index; + } + + private void evaluateAttribute(SimpleStringBuilder sb, Attribute attribute, List capabilityFilterIndexes, int attributeIndex, String alias) { + switch (DbAttributeType.fromClass(attribute.getType())) { + case DOUBLE: + sb.append(false, alias, ".double_value"); + evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + break; + + case LONG: + sb.append(false, alias, ".long_value"); + evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + break; + + case STRING: + sb.append(false, alias, ".string_value"); + evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + break; + + case URI: + sb.append(false, alias, ".string_value"); + evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + break; + + case VERSION: + sb.append(false, "("); + evaluateVersion(sb, alias, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + sb.append(false, ")"); + break; + + case BOOLEAN: + sb.append(false, alias, ".boolean_value"); + evaluateOperator(sb, attribute.getOperator(), capabilityFilterIndexes, attributeIndex); + break; + + case LIST: + throw new UnsupportedOperationException(); + } + + } + + private void evaluateOperator(SimpleStringBuilder sb, cz.zcu.kiv.crce.metadata.Operator operator, List subFilterPath, int attributeIndex) { + switch (operator) { + case EQUAL: + sb.append(false, " = "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + case NOT_EQUAL: + sb.append(false, " <> "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + case PRESENT: + sb.append(false, " is not null"); + break; + + case LESS: + sb.append(false, " < "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + case LESS_EQUAL: + sb.append(false, " <= "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + case GREATER: + sb.append(false, " > "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + case GREATER_EQUAL: + sb.append(false, " >= "); + buildParameterValuePath(sb, subFilterPath, attributeIndex, "value"); + break; + + default: + throw new UnsupportedOperationException("Operator " + operator + " is not supported for ... type."); + + } + } + + private void evaluateVersion(SimpleStringBuilder sb, String alias, cz.zcu.kiv.crce.metadata.Operator operator, List subFilterPath, int attributeIndex) { + switch (operator) { + case EQUAL: + sb.append(false, alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " AND ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " AND ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " AND ", alias, ".string_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + break; + + case NOT_EQUAL: + sb.append(false, alias, ".version_major_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " OR ", alias, ".version_minor_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " OR ", alias, ".version_micro_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " OR ", alias, ".string_value <> "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + break; + + case PRESENT: + sb.append(false, alias, ".version_major_value is not null"); + sb.append(false, " AND ", alias, ".version_minor_value is not null"); + sb.append(false, " AND ", alias, ".version_micro_value is not null"); + sb.append(false, " AND ", alias, ".string_value is not null"); + break; + + case LESS: + sb.append(false, alias, ".version_major_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_minor_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_micro_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); + sb.append(false, alias, ".string_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + sb.append(false, ")))"); + break; + + case LESS_EQUAL: + sb.append(false, alias, ".version_major_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_minor_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_micro_value < "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); + sb.append(false, alias, ".string_value <= "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + sb.append(false, ")))"); + break; + + case GREATER: + sb.append(false, alias, ".version_major_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_minor_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_micro_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); + sb.append(false, alias, ".string_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + sb.append(false, ")))"); + break; + + case GREATER_EQUAL: + sb.append(false, alias, ".version_major_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " OR ", alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_minor_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + sb.append(false, " OR ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); sb.append(false, " AND ("); + sb.append(false, alias, ".version_micro_value > "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); + sb.append(false, " OR ", alias, ".version_micro_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.micro"); sb.append(false, " AND ("); + sb.append(false, alias, ".string_value >= "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.qualifier"); + sb.append(false, ")))"); + break; + + case APPROX: + sb.append(false, alias, ".version_major_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.major"); + sb.append(false, " AND ", alias, ".version_minor_value = "); buildParameterValuePath(sb, subFilterPath, attributeIndex, "value.minor"); + break; + + default: + throw new UnsupportedOperationException("Operator " + operator + " is not supported for Version type."); + + } + } + + /** + * Builds value portion of the query using MyBatis mechanism for specifying values in queries based on parameter objects. + * + * The value path expects #ResourceDAOFilter with name filter to be present among the parameters. + * + * @param builder string builder used to create the portion of the query + * @param capabilityFilterIndexes indexes into the capability filter tree (one per level) specifying the path from root to the capability owning the attribute + * @param attributeIndex index of the attribute within the capability specified by the #capabilityFilterIndexes + * @param valuePath name of the value column for that particular attribute type + */ + private void buildParameterValuePath(SimpleStringBuilder builder, List capabilityFilterIndexes, Integer attributeIndex, String valuePath) { + Iterator it = capabilityFilterIndexes.iterator(); + + builder.append(false, "#{filter.capabilityFilters[", it.next().toString(), "]"); + while(it.hasNext()) { + builder.append(false, ".subFilters[", it.next().toString(), "]"); + } + if(attributeIndex != null) { + builder.append(false, ".attributes[", attributeIndex.toString(), "]"); + } + builder.append(false, ".", valuePath, "}"); + } + +} diff --git a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/type/DbOperator.java b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/type/DbOperator.java index f4a025af..1d10c810 100644 --- a/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/type/DbOperator.java +++ b/core/crce-metadata-dao-impl/src/main/java/cz/zcu/kiv/crce/metadata/dao/internal/type/DbOperator.java @@ -1,47 +1,47 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.type; - -import cz.zcu.kiv.crce.metadata.Operator; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public enum DbOperator { - - EQUAL(Operator.EQUAL, (short) 0), - NOT_EQUAL(Operator.NOT_EQUAL, (short) 1), - LESS(Operator.LESS, (short) 2), - LESS_EQUAL(Operator.LESS_EQUAL, (short) 3), - GREATER(Operator.GREATER, (short) 4), - GREATER_EQUAL(Operator.GREATER_EQUAL, (short) 5), - SUBSET(Operator.SUBSET, (short) 6), - SUPERSET(Operator.SUPERSET, (short) 7), - PRESENT(Operator.PRESENT, (short) 8), - APPROX(Operator.APPROX, (short) 9); - - private final Operator operator; - private final short dbValue; - - private DbOperator(Operator operator, short dbValue) { - this.operator = operator; - this.dbValue = dbValue; - } - - public static short getDbValue(Operator operator) { - for (DbOperator value : values()) { - if (value.operator.equals(operator)) { - return value.dbValue; - } - } - throw new IllegalArgumentException("Invalid operator: " + operator); - } - - public static Operator getOperatorValue(short dbValue) { - for (DbOperator value : values()) { - if (value.dbValue == dbValue) { - return value.operator; - } - } - throw new IllegalArgumentException("Invalid operator DB value: " + dbValue); - } -} +package cz.zcu.kiv.crce.metadata.dao.internal.type; + +import cz.zcu.kiv.crce.metadata.Operator; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public enum DbOperator { + + EQUAL(Operator.EQUAL, (short) 0), + NOT_EQUAL(Operator.NOT_EQUAL, (short) 1), + LESS(Operator.LESS, (short) 2), + LESS_EQUAL(Operator.LESS_EQUAL, (short) 3), + GREATER(Operator.GREATER, (short) 4), + GREATER_EQUAL(Operator.GREATER_EQUAL, (short) 5), + SUBSET(Operator.SUBSET, (short) 6), + SUPERSET(Operator.SUPERSET, (short) 7), + PRESENT(Operator.PRESENT, (short) 8), + APPROX(Operator.APPROX, (short) 9); + + private final Operator operator; + private final short dbValue; + + private DbOperator(Operator operator, short dbValue) { + this.operator = operator; + this.dbValue = dbValue; + } + + public static short getDbValue(Operator operator) { + for (DbOperator value : values()) { + if (value.operator.equals(operator)) { + return value.dbValue; + } + } + throw new IllegalArgumentException("Invalid operator: " + operator); + } + + public static Operator getOperatorValue(short dbValue) { + for (DbOperator value : values()) { + if (value.dbValue == dbValue) { + return value.operator; + } + } + throw new IllegalArgumentException("Invalid operator DB value: " + dbValue); + } +} diff --git a/core/crce-metadata-dao-impl/src/main/resources/META-INF/mybatis/config.xml b/core/crce-metadata-dao-impl/src/main/resources/META-INF/mybatis/config.xml index 101c443a..8c30d459 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/META-INF/mybatis/config.xml +++ b/core/crce-metadata-dao-impl/src/main/resources/META-INF/mybatis/config.xml @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/RepositoryMapper.xml b/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/RepositoryMapper.xml index 52d58db9..723dfeec 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/RepositoryMapper.xml +++ b/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/RepositoryMapper.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - - insert into repository (repository_id, uri, id) values ( - #{repositoryId}, #{uri}, #{id} - ) - - - - DELETE FROM repository - WHERE uri = #{uri} - - + + + + + + + + + + + + insert into repository (repository_id, uri, id) values ( + #{repositoryId}, #{uri}, #{id} + ) + + + + DELETE FROM repository + WHERE uri = #{uri} + + \ No newline at end of file diff --git a/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResourceMapper.xml b/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResourceMapper.xml index 2a3b1b1a..28ddf8af 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResourceMapper.xml +++ b/core/crce-metadata-dao-impl/src/main/resources/cz/zcu/kiv/crce/metadata/dao/internal/mapper/ResourceMapper.xml @@ -1,275 +1,275 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DELETE FROM resource WHERE resource_id = #{id} - - - - DELETE FROM resource WHERE id = #{id} - - - - - - - INSERT INTO resource (resource_id, repository_id, id, uri) VALUES ( - #{resourceId}, #{repositoryId}, #{id}, #{uri} - ) - - - - INSERT INTO capability (capability_id, parent_capability_id, resource_id, level, id, namespace) VALUES ( - #{capabilityId}, #{parentCapabilityId}, #{resourceId}, #{level}, #{id}, #{namespace} - ) - - - - INSERT INTO requirement (requirement_id, parent_requirement_id, resource_id, level, id, namespace, capability_id) VALUES ( - #{requirementId}, #{parentRequirementId}, #{resourceId}, #{level}, #{id}, #{namespace}, #{capabilityId} - ) - - - - INSERT INTO resource_property (property_id, resource_id, id, namespace) VALUES ( - #{propertyId}, #{parentId}, #{id}, #{namespace} - ) - - - - INSERT INTO capability_property (property_id, capability_id, id, namespace) VALUES ( - #{propertyId}, #{parentId}, #{id}, #{namespace} - ) - - - - INSERT INTO capability_attribute ( - capability_id, name, list_index, type, operator, string_value, long_value, double_value, - boolean_value, version_major_value, version_minor_value, version_micro_value - ) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.listIndex, jdbcType=SMALLINT}, - #{item.type, jdbcType=SMALLINT}, - #{item.operator, jdbcType=SMALLINT}, - #{item.stringValue, jdbcType=VARCHAR}, - #{item.longValue, jdbcType=BIGINT}, - #{item.doubleValue, jdbcType=DOUBLE}, - #{item.booleanValue, jdbcType=VARCHAR}, - #{item.versionMajorValue, jdbcType=INTEGER}, - #{item.versionMinorValue, jdbcType=INTEGER}, - #{item.versionMicroValue, jdbcType=INTEGER} - - - - - INSERT INTO requirement_attribute ( - requirement_id, name, attribute_index, list_index, type, operator, string_value, long_value, double_value, - boolean_value, version_major_value, version_minor_value, version_micro_value - ) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.attributeIndex, jdbcType=SMALLINT}, - #{item.listIndex, jdbcType=SMALLINT}, - #{item.type, jdbcType=SMALLINT}, - #{item.operator, jdbcType=SMALLINT}, - #{item.stringValue, jdbcType=VARCHAR}, - #{item.longValue, jdbcType=BIGINT}, - #{item.doubleValue, jdbcType=DOUBLE}, - #{item.booleanValue, jdbcType=VARCHAR}, - #{item.versionMajorValue, jdbcType=INTEGER}, - #{item.versionMinorValue, jdbcType=INTEGER}, - #{item.versionMicroValue, jdbcType=INTEGER} - - - - - INSERT INTO resource_property_attribute ( - property_id, name, list_index, type, operator, string_value, long_value, double_value, - boolean_value, version_major_value, version_minor_value, version_micro_value - ) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.listIndex, jdbcType=SMALLINT}, - #{item.type, jdbcType=SMALLINT}, - #{item.operator, jdbcType=SMALLINT}, - #{item.stringValue, jdbcType=VARCHAR}, - #{item.longValue, jdbcType=BIGINT}, - #{item.doubleValue, jdbcType=DOUBLE}, - #{item.booleanValue, jdbcType=VARCHAR}, - #{item.versionMajorValue, jdbcType=INTEGER}, - #{item.versionMinorValue, jdbcType=INTEGER}, - #{item.versionMicroValue, jdbcType=INTEGER} - - - - - INSERT INTO capability_property_attribute ( - property_id, name, list_index, type, operator, string_value, long_value, double_value, - boolean_value, version_major_value, version_minor_value, version_micro_value - ) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.listIndex, jdbcType=SMALLINT}, - #{item.type, jdbcType=SMALLINT}, - #{item.operator, jdbcType=SMALLINT}, - #{item.stringValue, jdbcType=VARCHAR}, - #{item.longValue, jdbcType=BIGINT}, - #{item.doubleValue, jdbcType=DOUBLE}, - #{item.booleanValue, jdbcType=VARCHAR}, - #{item.versionMajorValue, jdbcType=INTEGER}, - #{item.versionMinorValue, jdbcType=INTEGER}, - #{item.versionMicroValue, jdbcType=INTEGER} - - - - - INSERT INTO capability_directive (capability_id, name, value) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.value, jdbcType=VARCHAR}, - - - - - INSERT INTO requirement_directive (requirement_id, name, value) VALUES - - #{item.entityId, jdbcType=BIGINT}, - #{item.name, jdbcType=VARCHAR}, - #{item.value, jdbcType=VARCHAR}, - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM resource WHERE resource_id = #{id} + + + + DELETE FROM resource WHERE id = #{id} + + + + + + + INSERT INTO resource (resource_id, repository_id, id, uri) VALUES ( + #{resourceId}, #{repositoryId}, #{id}, #{uri} + ) + + + + INSERT INTO capability (capability_id, parent_capability_id, resource_id, level, id, namespace) VALUES ( + #{capabilityId}, #{parentCapabilityId}, #{resourceId}, #{level}, #{id}, #{namespace} + ) + + + + INSERT INTO requirement (requirement_id, parent_requirement_id, resource_id, level, id, namespace, capability_id) VALUES ( + #{requirementId}, #{parentRequirementId}, #{resourceId}, #{level}, #{id}, #{namespace}, #{capabilityId} + ) + + + + INSERT INTO resource_property (property_id, resource_id, id, namespace) VALUES ( + #{propertyId}, #{parentId}, #{id}, #{namespace} + ) + + + + INSERT INTO capability_property (property_id, capability_id, id, namespace) VALUES ( + #{propertyId}, #{parentId}, #{id}, #{namespace} + ) + + + + INSERT INTO capability_attribute ( + capability_id, name, list_index, type, operator, string_value, long_value, double_value, + boolean_value, version_major_value, version_minor_value, version_micro_value + ) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.listIndex, jdbcType=SMALLINT}, + #{item.type, jdbcType=SMALLINT}, + #{item.operator, jdbcType=SMALLINT}, + #{item.stringValue, jdbcType=VARCHAR}, + #{item.longValue, jdbcType=BIGINT}, + #{item.doubleValue, jdbcType=DOUBLE}, + #{item.booleanValue, jdbcType=VARCHAR}, + #{item.versionMajorValue, jdbcType=INTEGER}, + #{item.versionMinorValue, jdbcType=INTEGER}, + #{item.versionMicroValue, jdbcType=INTEGER} + + + + + INSERT INTO requirement_attribute ( + requirement_id, name, attribute_index, list_index, type, operator, string_value, long_value, double_value, + boolean_value, version_major_value, version_minor_value, version_micro_value + ) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.attributeIndex, jdbcType=SMALLINT}, + #{item.listIndex, jdbcType=SMALLINT}, + #{item.type, jdbcType=SMALLINT}, + #{item.operator, jdbcType=SMALLINT}, + #{item.stringValue, jdbcType=VARCHAR}, + #{item.longValue, jdbcType=BIGINT}, + #{item.doubleValue, jdbcType=DOUBLE}, + #{item.booleanValue, jdbcType=VARCHAR}, + #{item.versionMajorValue, jdbcType=INTEGER}, + #{item.versionMinorValue, jdbcType=INTEGER}, + #{item.versionMicroValue, jdbcType=INTEGER} + + + + + INSERT INTO resource_property_attribute ( + property_id, name, list_index, type, operator, string_value, long_value, double_value, + boolean_value, version_major_value, version_minor_value, version_micro_value + ) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.listIndex, jdbcType=SMALLINT}, + #{item.type, jdbcType=SMALLINT}, + #{item.operator, jdbcType=SMALLINT}, + #{item.stringValue, jdbcType=VARCHAR}, + #{item.longValue, jdbcType=BIGINT}, + #{item.doubleValue, jdbcType=DOUBLE}, + #{item.booleanValue, jdbcType=VARCHAR}, + #{item.versionMajorValue, jdbcType=INTEGER}, + #{item.versionMinorValue, jdbcType=INTEGER}, + #{item.versionMicroValue, jdbcType=INTEGER} + + + + + INSERT INTO capability_property_attribute ( + property_id, name, list_index, type, operator, string_value, long_value, double_value, + boolean_value, version_major_value, version_minor_value, version_micro_value + ) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.listIndex, jdbcType=SMALLINT}, + #{item.type, jdbcType=SMALLINT}, + #{item.operator, jdbcType=SMALLINT}, + #{item.stringValue, jdbcType=VARCHAR}, + #{item.longValue, jdbcType=BIGINT}, + #{item.doubleValue, jdbcType=DOUBLE}, + #{item.booleanValue, jdbcType=VARCHAR}, + #{item.versionMajorValue, jdbcType=INTEGER}, + #{item.versionMinorValue, jdbcType=INTEGER}, + #{item.versionMicroValue, jdbcType=INTEGER} + + + + + INSERT INTO capability_directive (capability_id, name, value) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.value, jdbcType=VARCHAR}, + + + + + INSERT INTO requirement_directive (requirement_id, name, value) VALUES + + #{item.entityId, jdbcType=BIGINT}, + #{item.name, jdbcType=VARCHAR}, + #{item.value, jdbcType=VARCHAR}, + + + \ No newline at end of file diff --git a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V1__Create_db_structure.sql b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V1__Create_db_structure.sql index 99d01ef8..911909c0 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V1__Create_db_structure.sql +++ b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V1__Create_db_structure.sql @@ -1,192 +1,192 @@ -CREATE TABLE IF NOT EXISTS repository ( - repository_id BIGINT NOT NULL, - uri VARCHAR(512) NOT NULL, - PRIMARY KEY (repository_id) -); - -CREATE TABLE IF NOT EXISTS resource ( - resource_id BIGINT NOT NULL, - repository_id BIGINT NOT NULL, - id VARCHAR(48) NOT NULL, - uri VARCHAR(512) NOT NULL, - PRIMARY KEY (resource_id), - FOREIGN KEY (repository_id) REFERENCES repository (repository_id) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS capability ( - capability_id BIGINT NOT NULL, - parent_capability_id BIGINT NOT NULL, - resource_id BIGINT NOT NULL, - level SMALLINT DEFAULT 0 NOT NULL, - id VARCHAR(48) NOT NULL, - namespace VARCHAR(64) NOT NULL, - PRIMARY KEY (capability_id), - FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, - FOREIGN KEY (parent_capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS requirement ( - requirement_id BIGINT NOT NULL, - parent_requirement_id BIGINT NOT NULL, - resource_id BIGINT NOT NULL, - level SMALLINT DEFAULT 0 NOT NULL, - id VARCHAR(48) NOT NULL, - namespace VARCHAR(64) NOT NULL, - PRIMARY KEY (requirement_id), - FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, - FOREIGN KEY (parent_requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS resource_property ( - property_id BIGINT NOT NULL, - resource_id BIGINT NOT NULL, - id VARCHAR(48) NOT NULL, - namespace VARCHAR(64) NOT NULL, - PRIMARY KEY (property_id), - FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, -); - -CREATE TABLE IF NOT EXISTS capability_property ( - property_id BIGINT NOT NULL, - capability_id BIGINT NOT NULL, - id VARCHAR(48) NOT NULL, - namespace VARCHAR(64) NOT NULL, - PRIMARY KEY (property_id), - FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, -); - -CREATE TABLE IF NOT EXISTS capability_attribute ( - capability_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - list_index SMALLINT DEFAULT 0 NOT NULL, - type SMALLINT DEFAULT 0 NOT NULL, - operator SMALLINT DEFAULT 0 NOT NULL, - string_value VARCHAR(1024), - long_value BIGINT, - double_value DOUBLE, - version_major_value INTEGER, - version_minor_value INTEGER, - version_micro_value INTEGER, - PRIMARY KEY (capability_id, name, list_index), - FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, - CONSTRAINT capability_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL, - CONSTRAINT capability_attribute_ck2 CHECK - (string_value IS NOT NULL - AND version_major_value IS NOT NULL - AND version_minor_value IS NOT NULL - AND version_micro_value IS NOT NULL) - OR (version_major_value IS NULL - AND version_minor_value IS NULL - AND version_micro_value IS NULL) -); - -CREATE TABLE IF NOT EXISTS requirement_attribute ( - requirement_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - attribute_index SMALLINT DEFAULT 0 NOT NULL, - list_index SMALLINT DEFAULT 0 NOT NULL, - type SMALLINT DEFAULT 0 NOT NULL, - operator SMALLINT DEFAULT 0 NOT NULL, - string_value VARCHAR(1024), - long_value BIGINT, - double_value DOUBLE, - version_major_value INTEGER, - version_minor_value INTEGER, - version_micro_value INTEGER, - PRIMARY KEY (requirement_id, name, attribute_index, list_index), - FOREIGN KEY (requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE, - CONSTRAINT requirement_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL, - CONSTRAINT requirement_attribute_ck2 CHECK - (string_value IS NOT NULL - AND version_major_value IS NOT NULL - AND version_minor_value IS NOT NULL - AND version_micro_value IS NOT NULL) - OR (version_major_value IS NULL - AND version_minor_value IS NULL - AND version_micro_value IS NULL) -); - -CREATE TABLE IF NOT EXISTS resource_property_attribute ( - property_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - list_index SMALLINT DEFAULT 0 NOT NULL, - type SMALLINT DEFAULT 0 NOT NULL, - operator SMALLINT DEFAULT 0 NOT NULL, - string_value VARCHAR(1024), - long_value BIGINT, - double_value DOUBLE, - version_major_value INTEGER, - version_minor_value INTEGER, - version_micro_value INTEGER, - PRIMARY KEY (property_id, name, list_index), - FOREIGN KEY (property_id) REFERENCES resource_property (property_id) ON DELETE CASCADE, - CONSTRAINT res_property_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL, - CONSTRAINT res_property_attribute_ck2 CHECK - (string_value IS NOT NULL - AND version_major_value IS NOT NULL - AND version_minor_value IS NOT NULL - AND version_micro_value IS NOT NULL) - OR (version_major_value IS NULL - AND version_minor_value IS NULL - AND version_micro_value IS NULL) -); - -CREATE TABLE IF NOT EXISTS capability_property_attribute ( - property_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - list_index SMALLINT DEFAULT 0 NOT NULL, - type SMALLINT DEFAULT 0 NOT NULL, - operator SMALLINT DEFAULT 0 NOT NULL, - string_value VARCHAR(1024), - long_value BIGINT, - double_value DOUBLE, - version_major_value INTEGER, - version_minor_value INTEGER, - version_micro_value INTEGER, - PRIMARY KEY (property_id, name, list_index), - FOREIGN KEY (property_id) REFERENCES capability_property (property_id) ON DELETE CASCADE, - CONSTRAINT cap_property_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL, - CONSTRAINT cap_property_attribute_ck2 CHECK - (string_value IS NOT NULL - AND version_major_value IS NOT NULL - AND version_minor_value IS NOT NULL - AND version_micro_value IS NOT NULL) - OR (version_major_value IS NULL - AND version_minor_value IS NULL - AND version_micro_value IS NULL) -); - -CREATE TABLE IF NOT EXISTS capability_directive ( - capability_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - value VARCHAR(1024) NOT NULL, - PRIMARY KEY (capability_id, name), - FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, -); - -CREATE TABLE IF NOT EXISTS requirement_directive ( - requirement_id BIGINT NOT NULL, - name VARCHAR(16) NOT NULL, - value VARCHAR(1024) NOT NULL, - PRIMARY KEY (requirement_id, name), - FOREIGN KEY (requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE, -); - -CREATE SEQUENCE IF NOT EXISTS repository_seq; -CREATE SEQUENCE IF NOT EXISTS resource_seq; -CREATE SEQUENCE IF NOT EXISTS capability_seq; -CREATE SEQUENCE IF NOT EXISTS requirement_seq; -CREATE SEQUENCE IF NOT EXISTS resource_property_seq; -CREATE SEQUENCE IF NOT EXISTS capability_property_seq; +CREATE TABLE IF NOT EXISTS repository ( + repository_id BIGINT NOT NULL, + uri VARCHAR(512) NOT NULL, + PRIMARY KEY (repository_id) +); + +CREATE TABLE IF NOT EXISTS resource ( + resource_id BIGINT NOT NULL, + repository_id BIGINT NOT NULL, + id VARCHAR(48) NOT NULL, + uri VARCHAR(512) NOT NULL, + PRIMARY KEY (resource_id), + FOREIGN KEY (repository_id) REFERENCES repository (repository_id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS capability ( + capability_id BIGINT NOT NULL, + parent_capability_id BIGINT NOT NULL, + resource_id BIGINT NOT NULL, + level SMALLINT DEFAULT 0 NOT NULL, + id VARCHAR(48) NOT NULL, + namespace VARCHAR(64) NOT NULL, + PRIMARY KEY (capability_id), + FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, + FOREIGN KEY (parent_capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS requirement ( + requirement_id BIGINT NOT NULL, + parent_requirement_id BIGINT NOT NULL, + resource_id BIGINT NOT NULL, + level SMALLINT DEFAULT 0 NOT NULL, + id VARCHAR(48) NOT NULL, + namespace VARCHAR(64) NOT NULL, + PRIMARY KEY (requirement_id), + FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, + FOREIGN KEY (parent_requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS resource_property ( + property_id BIGINT NOT NULL, + resource_id BIGINT NOT NULL, + id VARCHAR(48) NOT NULL, + namespace VARCHAR(64) NOT NULL, + PRIMARY KEY (property_id), + FOREIGN KEY (resource_id) REFERENCES resource (resource_id) ON DELETE CASCADE, +); + +CREATE TABLE IF NOT EXISTS capability_property ( + property_id BIGINT NOT NULL, + capability_id BIGINT NOT NULL, + id VARCHAR(48) NOT NULL, + namespace VARCHAR(64) NOT NULL, + PRIMARY KEY (property_id), + FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, +); + +CREATE TABLE IF NOT EXISTS capability_attribute ( + capability_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + list_index SMALLINT DEFAULT 0 NOT NULL, + type SMALLINT DEFAULT 0 NOT NULL, + operator SMALLINT DEFAULT 0 NOT NULL, + string_value VARCHAR(1024), + long_value BIGINT, + double_value DOUBLE, + version_major_value INTEGER, + version_minor_value INTEGER, + version_micro_value INTEGER, + PRIMARY KEY (capability_id, name, list_index), + FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, + CONSTRAINT capability_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL, + CONSTRAINT capability_attribute_ck2 CHECK + (string_value IS NOT NULL + AND version_major_value IS NOT NULL + AND version_minor_value IS NOT NULL + AND version_micro_value IS NOT NULL) + OR (version_major_value IS NULL + AND version_minor_value IS NULL + AND version_micro_value IS NULL) +); + +CREATE TABLE IF NOT EXISTS requirement_attribute ( + requirement_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + attribute_index SMALLINT DEFAULT 0 NOT NULL, + list_index SMALLINT DEFAULT 0 NOT NULL, + type SMALLINT DEFAULT 0 NOT NULL, + operator SMALLINT DEFAULT 0 NOT NULL, + string_value VARCHAR(1024), + long_value BIGINT, + double_value DOUBLE, + version_major_value INTEGER, + version_minor_value INTEGER, + version_micro_value INTEGER, + PRIMARY KEY (requirement_id, name, attribute_index, list_index), + FOREIGN KEY (requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE, + CONSTRAINT requirement_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL, + CONSTRAINT requirement_attribute_ck2 CHECK + (string_value IS NOT NULL + AND version_major_value IS NOT NULL + AND version_minor_value IS NOT NULL + AND version_micro_value IS NOT NULL) + OR (version_major_value IS NULL + AND version_minor_value IS NULL + AND version_micro_value IS NULL) +); + +CREATE TABLE IF NOT EXISTS resource_property_attribute ( + property_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + list_index SMALLINT DEFAULT 0 NOT NULL, + type SMALLINT DEFAULT 0 NOT NULL, + operator SMALLINT DEFAULT 0 NOT NULL, + string_value VARCHAR(1024), + long_value BIGINT, + double_value DOUBLE, + version_major_value INTEGER, + version_minor_value INTEGER, + version_micro_value INTEGER, + PRIMARY KEY (property_id, name, list_index), + FOREIGN KEY (property_id) REFERENCES resource_property (property_id) ON DELETE CASCADE, + CONSTRAINT res_property_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL, + CONSTRAINT res_property_attribute_ck2 CHECK + (string_value IS NOT NULL + AND version_major_value IS NOT NULL + AND version_minor_value IS NOT NULL + AND version_micro_value IS NOT NULL) + OR (version_major_value IS NULL + AND version_minor_value IS NULL + AND version_micro_value IS NULL) +); + +CREATE TABLE IF NOT EXISTS capability_property_attribute ( + property_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + list_index SMALLINT DEFAULT 0 NOT NULL, + type SMALLINT DEFAULT 0 NOT NULL, + operator SMALLINT DEFAULT 0 NOT NULL, + string_value VARCHAR(1024), + long_value BIGINT, + double_value DOUBLE, + version_major_value INTEGER, + version_minor_value INTEGER, + version_micro_value INTEGER, + PRIMARY KEY (property_id, name, list_index), + FOREIGN KEY (property_id) REFERENCES capability_property (property_id) ON DELETE CASCADE, + CONSTRAINT cap_property_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL, + CONSTRAINT cap_property_attribute_ck2 CHECK + (string_value IS NOT NULL + AND version_major_value IS NOT NULL + AND version_minor_value IS NOT NULL + AND version_micro_value IS NOT NULL) + OR (version_major_value IS NULL + AND version_minor_value IS NULL + AND version_micro_value IS NULL) +); + +CREATE TABLE IF NOT EXISTS capability_directive ( + capability_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + value VARCHAR(1024) NOT NULL, + PRIMARY KEY (capability_id, name), + FOREIGN KEY (capability_id) REFERENCES capability (capability_id) ON DELETE CASCADE, +); + +CREATE TABLE IF NOT EXISTS requirement_directive ( + requirement_id BIGINT NOT NULL, + name VARCHAR(16) NOT NULL, + value VARCHAR(1024) NOT NULL, + PRIMARY KEY (requirement_id, name), + FOREIGN KEY (requirement_id) REFERENCES requirement (requirement_id) ON DELETE CASCADE, +); + +CREATE SEQUENCE IF NOT EXISTS repository_seq; +CREATE SEQUENCE IF NOT EXISTS resource_seq; +CREATE SEQUENCE IF NOT EXISTS capability_seq; +CREATE SEQUENCE IF NOT EXISTS requirement_seq; +CREATE SEQUENCE IF NOT EXISTS resource_property_seq; +CREATE SEQUENCE IF NOT EXISTS capability_property_seq; diff --git a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V5__Add_capability_id_to_requirement.sql b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V5__Add_capability_id_to_requirement.sql index 052bf832..3239a493 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V5__Add_capability_id_to_requirement.sql +++ b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V5__Add_capability_id_to_requirement.sql @@ -1,3 +1,3 @@ -ALTER TABLE requirement ADD capability_id BIGINT; - -ALTER TABLE requirement ADD FOREIGN KEY(capability_id) REFERENCES capability(capability_id) ON DELETE CASCADE; +ALTER TABLE requirement ADD capability_id BIGINT; + +ALTER TABLE requirement ADD FOREIGN KEY(capability_id) REFERENCES capability(capability_id) ON DELETE CASCADE; diff --git a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V6__Add_boolean_value_.sql b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V6__Add_boolean_value_.sql index 0775e199..6a2ab73a 100644 --- a/core/crce-metadata-dao-impl/src/main/resources/db/migration/V6__Add_boolean_value_.sql +++ b/core/crce-metadata-dao-impl/src/main/resources/db/migration/V6__Add_boolean_value_.sql @@ -1,32 +1,32 @@ -ALTER TABLE capability_attribute ADD boolean_value BOOLEAN; -ALTER TABLE capability_attribute DROP CONSTRAINT IF EXISTS capability_attribute_ck1; -ALTER TABLE capability_attribute ADD CONSTRAINT capability_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL - OR boolean_value IS NOT NULL; - -ALTER TABLE requirement_attribute ADD boolean_value BOOLEAN; -ALTER TABLE requirement_attribute DROP CONSTRAINT IF EXISTS requirement_attribute_ck1; -ALTER TABLE requirement_attribute ADD CONSTRAINT requirement_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL - OR boolean_value IS NOT NULL; - -ALTER TABLE resource_property_attribute ADD boolean_value BOOLEAN; -ALTER TABLE resource_property_attribute DROP CONSTRAINT IF EXISTS res_property_attribute_ck1; -ALTER TABLE resource_property_attribute ADD CONSTRAINT res_property_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL - OR boolean_value IS NOT NULL; - -ALTER TABLE capability_property_attribute ADD boolean_value BOOLEAN; -ALTER TABLE capability_property_attribute DROP CONSTRAINT IF EXISTS cap_property_attribute_ck1; -ALTER TABLE capability_property_attribute ADD CONSTRAINT cap_property_attribute_ck1 CHECK - string_value IS NOT NULL - OR long_value IS NOT NULL - OR double_value IS NOT NULL - OR boolean_value IS NOT NULL; - +ALTER TABLE capability_attribute ADD boolean_value BOOLEAN; +ALTER TABLE capability_attribute DROP CONSTRAINT IF EXISTS capability_attribute_ck1; +ALTER TABLE capability_attribute ADD CONSTRAINT capability_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL + OR boolean_value IS NOT NULL; + +ALTER TABLE requirement_attribute ADD boolean_value BOOLEAN; +ALTER TABLE requirement_attribute DROP CONSTRAINT IF EXISTS requirement_attribute_ck1; +ALTER TABLE requirement_attribute ADD CONSTRAINT requirement_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL + OR boolean_value IS NOT NULL; + +ALTER TABLE resource_property_attribute ADD boolean_value BOOLEAN; +ALTER TABLE resource_property_attribute DROP CONSTRAINT IF EXISTS res_property_attribute_ck1; +ALTER TABLE resource_property_attribute ADD CONSTRAINT res_property_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL + OR boolean_value IS NOT NULL; + +ALTER TABLE capability_property_attribute ADD boolean_value BOOLEAN; +ALTER TABLE capability_property_attribute DROP CONSTRAINT IF EXISTS cap_property_attribute_ck1; +ALTER TABLE capability_property_attribute ADD CONSTRAINT cap_property_attribute_ck1 CHECK + string_value IS NOT NULL + OR long_value IS NOT NULL + OR double_value IS NOT NULL + OR boolean_value IS NOT NULL; + diff --git a/core/crce-metadata-dao-impl/src/test/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProviderTest.java b/core/crce-metadata-dao-impl/src/test/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProviderTest.java index 6e2bd1cb..810cd26c 100644 --- a/core/crce-metadata-dao-impl/src/test/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProviderTest.java +++ b/core/crce-metadata-dao-impl/src/test/java/cz/zcu/kiv/crce/metadata/dao/internal/mapper/SqlFilterProviderTest.java @@ -1,109 +1,109 @@ -package cz.zcu.kiv.crce.metadata.dao.internal.mapper; - -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; -import cz.zcu.kiv.crce.metadata.dao.filter.Operator; -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; - -/** - * Date: 14.3.16 - * - * @author Jakub Danek - */ -public class SqlFilterProviderTest { - - private static final Logger logger = LoggerFactory.getLogger(SqlFilterProvider.class); - - private SqlFilterProvider provider; - - @Before - public void setUp() throws Exception { - provider = new SqlFilterProvider(); - } - - /** - * Desired SQL output for the test data and AND operator between capability filters: - *

- * SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r - JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID - JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID - JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID - LEFT JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID - JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID - WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' - AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true))) - ) - AND (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.gateway') -

- * @throws Exception - */ - @Test - public void testAndFilter() throws Exception { - Map params = new HashMap<>(); - params.put(SqlFilterProvider.PARAM_FILTER, buildFilter(Operator.AND)); - - String sql = provider.generateSQL(params); - logger.info(sql); - } - - private ResourceDAOFilter buildFilter(Operator operator) { - ResourceDAOFilter filter = new ResourceDAOFilter(); - filter.setOperator(operator); - - List> attributes = new ArrayList<>(); - attributes.add(createAttribute("name", "IVehicleFlow")); - attributes.add(createAttribute("interface", true)); - CapabilityFilter clazz = buildCapabilityFilter("crce.api.java.class", attributes, null); - - attributes = new ArrayList<>(); - attributes.add(createAttribute("name", "cz.zcu.kiv.osgi.demo.parking.carpark.flow")); - CapabilityFilter pckg = buildCapabilityFilter("crce.api.java.package", attributes, Collections.singletonList(clazz)); - filter.addCapabilityFilter(pckg); - - attributes = new ArrayList<>(); - attributes.add(createAttribute("name", "cz.zcu.kiv.osgi.demo.parking.carpark.gateway")); - pckg = buildCapabilityFilter("crce.api.java.package", attributes, null); - filter.addCapabilityFilter(pckg); - - return filter; - } - - private CapabilityFilter buildCapabilityFilter(String namespace, List> attributes, List subFilters) { - CapabilityFilter f = new CapabilityFilter(namespace); - if(attributes != null) { - f.addAttributes(attributes); - } - if(subFilters != null) { - f.addSubFilters(subFilters); - } - - return f; - } - - private Attribute createAttribute(String name, Object value) { - Attribute at = Mockito.mock(Attribute.class); - when(at.getName()).thenReturn(name); - when(at.getValue()).thenReturn(value); - when(at.getStringValue()).thenReturn(value.toString()); - when(at.getType()).thenReturn(value.getClass()); - when(at.getOperator()).thenReturn(cz.zcu.kiv.crce.metadata.Operator.EQUAL); - return at; - } - -} +package cz.zcu.kiv.crce.metadata.dao.internal.mapper; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; +import cz.zcu.kiv.crce.metadata.dao.filter.Operator; +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; + +/** + * Date: 14.3.16 + * + * @author Jakub Danek + */ +public class SqlFilterProviderTest { + + private static final Logger logger = LoggerFactory.getLogger(SqlFilterProvider.class); + + private SqlFilterProvider provider; + + @Before + public void setUp() throws Exception { + provider = new SqlFilterProvider(); + } + + /** + * Desired SQL output for the test data and AND operator between capability filters: + *

+ * SELECT DISTINCT r.resource_id, r.repository_id, r.id, r.uri FROM resource r + JOIN capability c1 ON c1.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca11 ON ca11.CAPABILITY_ID = c1.CAPABILITY_ID + JOIN CAPABILITY sc11 ON c1.CAPABILITY_ID = sc11.PARENT_CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca111 ON ca111.CAPABILITY_ID = sc11.CAPABILITY_ID + JOIN CAPABILITY_ATTRIBUTE ca112 ON ca112.CAPABILITY_ID = sc11.CAPABILITY_ID + LEFT JOIN capability c2 ON c2.RESOURCE_ID = r.RESOURCE_ID + JOIN CAPABILITY_ATTRIBUTE ca21 ON ca21.CAPABILITY_ID = c2.CAPABILITY_ID + WHERE (c1.NAMESPACE = 'crce.api.java.package' AND ca11.name = 'name' AND ca11.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.flow' + AND (sc11.NAMESPACE = 'crce.api.java.class' AND ((ca111.name = 'name' AND ca111.STRING_VALUE = 'IVehicleFlow') AND (ca112.name = 'interface' AND ca112.BOOLEAN_VALUE = true))) + ) + AND (c2.NAMESPACE = 'crce.api.java.package' AND ca21.name = 'name' AND ca21.STRING_VALUE = 'cz.zcu.kiv.osgi.demo.parking.carpark.gateway') +

+ * @throws Exception + */ + @Test + public void testAndFilter() throws Exception { + Map params = new HashMap<>(); + params.put(SqlFilterProvider.PARAM_FILTER, buildFilter(Operator.AND)); + + String sql = provider.generateSQL(params); + logger.info(sql); + } + + private ResourceDAOFilter buildFilter(Operator operator) { + ResourceDAOFilter filter = new ResourceDAOFilter(); + filter.setOperator(operator); + + List> attributes = new ArrayList<>(); + attributes.add(createAttribute("name", "IVehicleFlow")); + attributes.add(createAttribute("interface", true)); + CapabilityFilter clazz = buildCapabilityFilter("crce.api.java.class", attributes, null); + + attributes = new ArrayList<>(); + attributes.add(createAttribute("name", "cz.zcu.kiv.osgi.demo.parking.carpark.flow")); + CapabilityFilter pckg = buildCapabilityFilter("crce.api.java.package", attributes, Collections.singletonList(clazz)); + filter.addCapabilityFilter(pckg); + + attributes = new ArrayList<>(); + attributes.add(createAttribute("name", "cz.zcu.kiv.osgi.demo.parking.carpark.gateway")); + pckg = buildCapabilityFilter("crce.api.java.package", attributes, null); + filter.addCapabilityFilter(pckg); + + return filter; + } + + private CapabilityFilter buildCapabilityFilter(String namespace, List> attributes, List subFilters) { + CapabilityFilter f = new CapabilityFilter(namespace); + if(attributes != null) { + f.addAttributes(attributes); + } + if(subFilters != null) { + f.addSubFilters(subFilters); + } + + return f; + } + + private Attribute createAttribute(String name, Object value) { + Attribute at = Mockito.mock(Attribute.class); + when(at.getName()).thenReturn(name); + when(at.getValue()).thenReturn(value); + when(at.getStringValue()).thenReturn(value.toString()); + when(at.getType()).thenReturn(value.getClass()); + when(at.getOperator()).thenReturn(cz.zcu.kiv.crce.metadata.Operator.EQUAL); + return at; + } + +} diff --git a/core/crce-metadata-impl/osgi.bnd b/core/crce-metadata-impl/osgi.bnd index 845b61c1..9ccc9f75 100644 --- a/core/crce-metadata-impl/osgi.bnd +++ b/core/crce-metadata-impl/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Embed-Dependency: org.apache.felix.utils +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Embed-Dependency: org.apache.felix.utils diff --git a/core/crce-metadata-impl/pom.xml b/core/crce-metadata-impl/pom.xml index 5276f057..4ff38864 100644 --- a/core/crce-metadata-impl/pom.xml +++ b/core/crce-metadata-impl/pom.xml @@ -1,82 +1,82 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-impl - 3.0.1-SNAPSHOT - bundle - - CRCE - Core - Metadata Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.impl - ${namespace}.metadata - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-json-api - 2.1.0 - true - - - - org.apache.felix - org.apache.felix.bundlerepository - - - org.apache.felix - org.apache.felix.utils - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-impl + 3.0.1-SNAPSHOT + bundle + + CRCE - Core - Metadata Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.impl + ${namespace}.metadata + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-json-api + 2.1.0 + true + + + + org.apache.felix + org.apache.felix.bundlerepository + + + org.apache.felix + org.apache.felix.utils + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeImpl.java index 6045a725..c1fde974 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeImpl.java @@ -1,113 +1,113 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Operator; - -/** - * - * @param - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class AttributeImpl implements Attribute { - - private static final long serialVersionUID = 3231029096691170916L; - - private T value; - private AttributeType type; - private Operator operator; - - public AttributeImpl(@Nonnull AttributeType type, @Nonnull T value, Operator operator) { - this.value = value; - this.type = type; - this.operator = operator != null ? operator : Operator.EQUAL; - } - - public AttributeImpl(@Nonnull AttributeType type, @Nonnull T value) { - this(type, value, Operator.EQUAL); - } - - @Override - public String getName() { - return type.getName(); - } - - @Override - public Class getType() { - return type.getType(); - } - - @Override - public T getValue() { - if (value == null) { - throw new IllegalStateException("Value is null for " + type.getName()); - } - return value; - } - - @Override - public String getStringValue() { - if (value == null) { - throw new IllegalStateException("Value is null for " + type.getName()); - } - if (List.class.equals(type.getType())) { - StringBuilder sb = new StringBuilder(); - Iterator iterator = ((List) value).iterator(); - if (iterator.hasNext()) { - sb.append(iterator.next()); - } - while (iterator.hasNext()) { - sb.append(",").append(iterator.next()); - } - return sb.toString(); - } - return String.valueOf(value); - } - - @Override - public AttributeType getAttributeType() { - return type; - } - - @Override - public int hashCode() { - int hash = 3; - hash = 97 * hash + Objects.hashCode(this.value); - hash = 97 * hash + Objects.hashCode(this.type); - hash = 97 * hash + (this.operator != null ? this.operator.hashCode() : 0); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AttributeImpl other = (AttributeImpl) obj; - if (!Objects.equals(this.value, other.value)) { - return false; - } - if (!Objects.equals(this.type, other.type)) { - return false; - } - return this.operator == other.operator; - } - - @Override - public Operator getOperator() { - return operator; - } - - @Override - public String toString() { - return MetadataFactoryImpl.toString(this); - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Operator; + +/** + * + * @param + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class AttributeImpl implements Attribute { + + private static final long serialVersionUID = 3231029096691170916L; + + private T value; + private AttributeType type; + private Operator operator; + + public AttributeImpl(@Nonnull AttributeType type, @Nonnull T value, Operator operator) { + this.value = value; + this.type = type; + this.operator = operator != null ? operator : Operator.EQUAL; + } + + public AttributeImpl(@Nonnull AttributeType type, @Nonnull T value) { + this(type, value, Operator.EQUAL); + } + + @Override + public String getName() { + return type.getName(); + } + + @Override + public Class getType() { + return type.getType(); + } + + @Override + public T getValue() { + if (value == null) { + throw new IllegalStateException("Value is null for " + type.getName()); + } + return value; + } + + @Override + public String getStringValue() { + if (value == null) { + throw new IllegalStateException("Value is null for " + type.getName()); + } + if (List.class.equals(type.getType())) { + StringBuilder sb = new StringBuilder(); + Iterator iterator = ((List) value).iterator(); + if (iterator.hasNext()) { + sb.append(iterator.next()); + } + while (iterator.hasNext()) { + sb.append(",").append(iterator.next()); + } + return sb.toString(); + } + return String.valueOf(value); + } + + @Override + public AttributeType getAttributeType() { + return type; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 97 * hash + Objects.hashCode(this.value); + hash = 97 * hash + Objects.hashCode(this.type); + hash = 97 * hash + (this.operator != null ? this.operator.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AttributeImpl other = (AttributeImpl) obj; + if (!Objects.equals(this.value, other.value)) { + return false; + } + if (!Objects.equals(this.type, other.type)) { + return false; + } + return this.operator == other.operator; + } + + @Override + public Operator getOperator() { + return operator; + } + + @Override + public String toString() { + return MetadataFactoryImpl.toString(this); + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeProviderImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeProviderImpl.java index 4d7a8480..7b6c9ef4 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeProviderImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/AttributeProviderImpl.java @@ -1,110 +1,110 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeProvider; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class AttributeProviderImpl implements AttributeProvider { - - private static final long serialVersionUID = 1L; - - protected final Map> attributesMap = new HashMap<>(); - - - @Override - public String getAttributeStringValue(AttributeType type) { - Attribute attribute = attributesMap.get(type.getName()); - if (attribute != null) { - return attribute.getStringValue(); - } - return null; - } - - @Override - public boolean setAttribute(AttributeType type, T value) { - attributesMap.put(type.getName(), new AttributeImpl<>(type, value)); - return true; - } - - @Override - public boolean setAttribute(Attribute attribute) { - attributesMap.put(attribute.getAttributeType().getName(), attribute); - return true; - } - - @Override - public boolean removeAttribute(Attribute attribute) { - return attributesMap.remove(attribute.getAttributeType().getName()) != null; - } - - @Override - public boolean setAttribute(AttributeType type, T value, Operator operator) { - attributesMap.put(type.getName(), new AttributeImpl<>(type, value, operator)); - return true; - } - - @Override - public boolean setAttribute(String name, Class type, T value) { - return setAttribute(name, type, value, Operator.EQUAL); - } - - @Override - public boolean setAttribute(String name, Class type, T value, Operator operator) { - AttributeType attributeType = new SimpleAttributeType<>(name, type); - Attribute attribute = new AttributeImpl<>(attributeType, value, operator); - attributesMap.put(attributeType.getName(), attribute); - return true; - } - - @Override - public boolean removeAttribute(AttributeType type) { - return attributesMap.remove(type.getName()) != null; - } - - @Override - public boolean removeAttribute(String name) { - return attributesMap.remove(name) != null; - } - - @Override - @SuppressWarnings("unchecked") - public Attribute getAttribute(AttributeType type) { - Attribute attribute = attributesMap.get(type.getName()); - if (attribute != null) { - return (Attribute) attribute; - } - return null; - } - - @Override - public List> getAttributes() { - return Collections.unmodifiableList(new ArrayList<>(attributesMap.values())); - } - - @Override - public Map> getAttributesMap() { - return Collections.unmodifiableMap(attributesMap); - } - - @Override - @SuppressWarnings("unchecked") - public T getAttributeValue(AttributeType type) { - Attribute attribute = attributesMap.get(type.getName()); - if (attribute != null) { - return (T) attribute.getValue(); - } - return null; - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeProvider; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class AttributeProviderImpl implements AttributeProvider { + + private static final long serialVersionUID = 1L; + + protected final Map> attributesMap = new HashMap<>(); + + + @Override + public String getAttributeStringValue(AttributeType type) { + Attribute attribute = attributesMap.get(type.getName()); + if (attribute != null) { + return attribute.getStringValue(); + } + return null; + } + + @Override + public boolean setAttribute(AttributeType type, T value) { + attributesMap.put(type.getName(), new AttributeImpl<>(type, value)); + return true; + } + + @Override + public boolean setAttribute(Attribute attribute) { + attributesMap.put(attribute.getAttributeType().getName(), attribute); + return true; + } + + @Override + public boolean removeAttribute(Attribute attribute) { + return attributesMap.remove(attribute.getAttributeType().getName()) != null; + } + + @Override + public boolean setAttribute(AttributeType type, T value, Operator operator) { + attributesMap.put(type.getName(), new AttributeImpl<>(type, value, operator)); + return true; + } + + @Override + public boolean setAttribute(String name, Class type, T value) { + return setAttribute(name, type, value, Operator.EQUAL); + } + + @Override + public boolean setAttribute(String name, Class type, T value, Operator operator) { + AttributeType attributeType = new SimpleAttributeType<>(name, type); + Attribute attribute = new AttributeImpl<>(attributeType, value, operator); + attributesMap.put(attributeType.getName(), attribute); + return true; + } + + @Override + public boolean removeAttribute(AttributeType type) { + return attributesMap.remove(type.getName()) != null; + } + + @Override + public boolean removeAttribute(String name) { + return attributesMap.remove(name) != null; + } + + @Override + @SuppressWarnings("unchecked") + public Attribute getAttribute(AttributeType type) { + Attribute attribute = attributesMap.get(type.getName()); + if (attribute != null) { + return (Attribute) attribute; + } + return null; + } + + @Override + public List> getAttributes() { + return Collections.unmodifiableList(new ArrayList<>(attributesMap.values())); + } + + @Override + public Map> getAttributesMap() { + return Collections.unmodifiableMap(attributesMap); + } + + @Override + @SuppressWarnings("unchecked") + public T getAttributeValue(AttributeType type) { + Attribute attribute = attributesMap.get(type.getName()); + if (attribute != null) { + return (T) attribute.getValue(); + } + return null; + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/CapabilityImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/CapabilityImpl.java index e54ea8c2..ea297af5 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/CapabilityImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/CapabilityImpl.java @@ -1,247 +1,247 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.DirectiveProvider; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.PropertyProvider; -import cz.zcu.kiv.crce.metadata.Requirement; - -/** - * Implementation of metadata Capability interface. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class CapabilityImpl extends AttributeProviderImpl implements Capability, Comparable { - - private static final long serialVersionUID = -813453152194473221L; - - private final String id; - private final List children = new ArrayList<>(); - - private final Map> allRequirements = new HashMap<>(); - private final PropertyProvider propertyProvider = new PropertyProviderImpl(); - private final DirectiveProvider directiveProvider = new DirectiveProviderImpl(); - - private String namespace = null; - - public CapabilityImpl(@Nonnull String namespace, @Nonnull String id) { - this.namespace = namespace.intern(); - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getNamespace() { - return namespace; - } - - @Override - public boolean addChild(Capability capability) { - return children.add(capability); - } - - @Override - public boolean removeChild(Capability capability) { - return children.remove(capability); - } - - @Override - public List getChildren() { - return Collections.unmodifiableList(children); - } - - // delegated methods - - @Override - public List getProperties() { - return propertyProvider.getProperties(); - } - - @Override - public List getProperties(String namespace) { - return propertyProvider.getProperties(namespace); - } - - @Override - public boolean hasProperty(Property property) { - return propertyProvider.hasProperty(property); - } - - @Override - public void addProperty(Property property) { - propertyProvider.addProperty(property); - } - - @Override - public void removeProperty(Property property) { - propertyProvider.removeProperty(property); - } - - @Override - public String getDirective(String name) { - return directiveProvider.getDirective(name); - } - - @Override - public Map getDirectives() { - return directiveProvider.getDirectives(); - } - - @Override - public boolean setDirective(String name, String directive) { - return directiveProvider.setDirective(name, directive); - } - - @Override - public boolean unsetDirective(String name) { - return directiveProvider.unsetDirective(name); - } - - @Override - public List getRequirements() { - List result = new ArrayList<>(); - for (List requirements : allRequirements.values()) { - result.addAll(requirements); - } - return result; - } - - @Override - public List getRequirements(String namespace) { - List result = allRequirements.get(namespace); - if (result == null) { - result = Collections.emptyList(); - } - return result; - } - - @Override - public boolean hasRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements != null) { - return requirements.contains(requirement); - } - return false; - } - - @Override - public void addRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements == null) { - requirements = new ArrayList<>(); - allRequirements.put(requirement.getNamespace(), requirements); - } - requirements.add(requirement); - } - - @Override - public void removeRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements != null) { - requirements.remove(requirement); - } - } - - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() == obj.getClass() || obj instanceof Capability) { - final Capability other = (Capability) obj; - return Objects.equals(this.id, other.getId()); - } - return false; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 89 * hash + Objects.hashCode(this.id); - return hash; - } - - @Override - public boolean equalsTo(Capability other, EqualityLevel level) { - if (other == null) { - return false; - } - switch (level) { - case KEY: - return id.equals(other.getId()); - - case SHALLOW_NO_KEY: - if (!Objects.equals(this.namespace, other.getNamespace())) { - return false; - } - if (!Objects.equals(this.attributesMap, other.getAttributesMap())) { - return false; - } - if (!Objects.equals(this.getDirectives(), other.getDirectives())) { - return false; - } - if (!Objects.equals(propertyProvider.getProperties(), other.getProperties())) { - return false; - } - return true; - - case SHALLOW_WITH_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.KEY)) { - return false; - } - return this.equalsTo(other, EqualityLevel.SHALLOW_NO_KEY); - - case DEEP_NO_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { - return false; - } - if (!Util.equalsTo(children, other.getChildren(), EqualityLevel.DEEP_NO_KEY)) { - return false; - } - if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_NO_KEY)) { - return false; - } - return true; - - case DEEP_WITH_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { - return false; - } - if (!Util.equalsTo(children, other.getChildren(), EqualityLevel.DEEP_WITH_KEY)) { - return false; - } - if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_WITH_KEY)) { - return false; - } - return true; - - default: - return equalsTo(other, EqualityLevel.KEY); - } - } - - @Override - public int compareTo(Capability o) { - return id.compareTo(o.getId()); - } - - @Override - public String toString() { - return MetadataFactoryImpl.toString(this); - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.DirectiveProvider; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.PropertyProvider; +import cz.zcu.kiv.crce.metadata.Requirement; + +/** + * Implementation of metadata Capability interface. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class CapabilityImpl extends AttributeProviderImpl implements Capability, Comparable { + + private static final long serialVersionUID = -813453152194473221L; + + private final String id; + private final List children = new ArrayList<>(); + + private final Map> allRequirements = new HashMap<>(); + private final PropertyProvider propertyProvider = new PropertyProviderImpl(); + private final DirectiveProvider directiveProvider = new DirectiveProviderImpl(); + + private String namespace = null; + + public CapabilityImpl(@Nonnull String namespace, @Nonnull String id) { + this.namespace = namespace.intern(); + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getNamespace() { + return namespace; + } + + @Override + public boolean addChild(Capability capability) { + return children.add(capability); + } + + @Override + public boolean removeChild(Capability capability) { + return children.remove(capability); + } + + @Override + public List getChildren() { + return Collections.unmodifiableList(children); + } + + // delegated methods + + @Override + public List getProperties() { + return propertyProvider.getProperties(); + } + + @Override + public List getProperties(String namespace) { + return propertyProvider.getProperties(namespace); + } + + @Override + public boolean hasProperty(Property property) { + return propertyProvider.hasProperty(property); + } + + @Override + public void addProperty(Property property) { + propertyProvider.addProperty(property); + } + + @Override + public void removeProperty(Property property) { + propertyProvider.removeProperty(property); + } + + @Override + public String getDirective(String name) { + return directiveProvider.getDirective(name); + } + + @Override + public Map getDirectives() { + return directiveProvider.getDirectives(); + } + + @Override + public boolean setDirective(String name, String directive) { + return directiveProvider.setDirective(name, directive); + } + + @Override + public boolean unsetDirective(String name) { + return directiveProvider.unsetDirective(name); + } + + @Override + public List getRequirements() { + List result = new ArrayList<>(); + for (List requirements : allRequirements.values()) { + result.addAll(requirements); + } + return result; + } + + @Override + public List getRequirements(String namespace) { + List result = allRequirements.get(namespace); + if (result == null) { + result = Collections.emptyList(); + } + return result; + } + + @Override + public boolean hasRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements != null) { + return requirements.contains(requirement); + } + return false; + } + + @Override + public void addRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements == null) { + requirements = new ArrayList<>(); + allRequirements.put(requirement.getNamespace(), requirements); + } + requirements.add(requirement); + } + + @Override + public void removeRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements != null) { + requirements.remove(requirement); + } + } + + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() == obj.getClass() || obj instanceof Capability) { + final Capability other = (Capability) obj; + return Objects.equals(this.id, other.getId()); + } + return false; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + Objects.hashCode(this.id); + return hash; + } + + @Override + public boolean equalsTo(Capability other, EqualityLevel level) { + if (other == null) { + return false; + } + switch (level) { + case KEY: + return id.equals(other.getId()); + + case SHALLOW_NO_KEY: + if (!Objects.equals(this.namespace, other.getNamespace())) { + return false; + } + if (!Objects.equals(this.attributesMap, other.getAttributesMap())) { + return false; + } + if (!Objects.equals(this.getDirectives(), other.getDirectives())) { + return false; + } + if (!Objects.equals(propertyProvider.getProperties(), other.getProperties())) { + return false; + } + return true; + + case SHALLOW_WITH_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.KEY)) { + return false; + } + return this.equalsTo(other, EqualityLevel.SHALLOW_NO_KEY); + + case DEEP_NO_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { + return false; + } + if (!Util.equalsTo(children, other.getChildren(), EqualityLevel.DEEP_NO_KEY)) { + return false; + } + if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_NO_KEY)) { + return false; + } + return true; + + case DEEP_WITH_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { + return false; + } + if (!Util.equalsTo(children, other.getChildren(), EqualityLevel.DEEP_WITH_KEY)) { + return false; + } + if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_WITH_KEY)) { + return false; + } + return true; + + default: + return equalsTo(other, EqualityLevel.KEY); + } + } + + @Override + public int compareTo(Capability o) { + return id.compareTo(o.getId()); + } + + @Override + public String toString() { + return MetadataFactoryImpl.toString(this); + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/DirectiveProviderImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/DirectiveProviderImpl.java index 4497bbd5..60e3d3da 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/DirectiveProviderImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/DirectiveProviderImpl.java @@ -1,62 +1,62 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import cz.zcu.kiv.crce.metadata.DirectiveProvider; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class DirectiveProviderImpl implements DirectiveProvider { - - private static final long serialVersionUID = 1L; - - protected final Map directivesMap = new HashMap<>(); - - @Override - public String getDirective(String name) { - return directivesMap.get(name); - } - - @Override - public Map getDirectives() { - return Collections.unmodifiableMap(directivesMap); - } - - @Override - public boolean setDirective(String name, String directive) { - directivesMap.put(name, directive); - return true; - } - - @Override - public boolean unsetDirective(String name) { - return directivesMap.remove(name) != null; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 41 * hash + Objects.hashCode(this.directivesMap); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DirectiveProviderImpl other = (DirectiveProviderImpl) obj; - if (!Objects.equals(this.directivesMap, other.directivesMap)) { - return false; - } - return true; - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import cz.zcu.kiv.crce.metadata.DirectiveProvider; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class DirectiveProviderImpl implements DirectiveProvider { + + private static final long serialVersionUID = 1L; + + protected final Map directivesMap = new HashMap<>(); + + @Override + public String getDirective(String name) { + return directivesMap.get(name); + } + + @Override + public Map getDirectives() { + return Collections.unmodifiableMap(directivesMap); + } + + @Override + public boolean setDirective(String name, String directive) { + directivesMap.put(name, directive); + return true; + } + + @Override + public boolean unsetDirective(String name) { + return directivesMap.remove(name) != null; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 41 * hash + Objects.hashCode(this.directivesMap); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DirectiveProviderImpl other = (DirectiveProviderImpl) obj; + if (!Objects.equals(this.directivesMap, other.directivesMap)) { + return false; + } + return true; + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelper.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelper.java index acd35559..9a67ad17 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelper.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelper.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import cz.zcu.kiv.crce.metadata.Entity; - -/** - * Wrapper for JSON serializer which allows to have an optional OSGi/DM dependency. - *

If optional package 'cz.zcu.kiv.crce.metadata.json' is not present on classpath, - * then this class is not loaded. So metadata entities implementations - * should not call this class directly. - * - * TODO this could be put to public API - it would allow to have other than JSON implementation. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface LogHelper { - - String toString(Entity entity); - - /** - * Regular implementation returns true, "null object" created by DM - * when optional dependency is not available returns false. This allows - * to decide whether or not to use the LogHelper to produce toString message. - * - * @return true if the interface implementation is available. - */ - boolean available(); -} +package cz.zcu.kiv.crce.metadata.internal; + +import cz.zcu.kiv.crce.metadata.Entity; + +/** + * Wrapper for JSON serializer which allows to have an optional OSGi/DM dependency. + *

If optional package 'cz.zcu.kiv.crce.metadata.json' is not present on classpath, + * then this class is not loaded. So metadata entities implementations + * should not call this class directly. + * + * TODO this could be put to public API - it would allow to have other than JSON implementation. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface LogHelper { + + String toString(Entity entity); + + /** + * Regular implementation returns true, "null object" created by DM + * when optional dependency is not available returns false. This allows + * to decide whether or not to use the LogHelper to produce toString message. + * + * @return true if the interface implementation is available. + */ + boolean available(); +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelperImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelperImpl.java index 210a2824..6e28e8de 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelperImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/LogHelperImpl.java @@ -1,54 +1,54 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.Dictionary; - -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Entity; -import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; - -@Component(provides = {LogHelper.class, ManagedService.class}, properties = { - @org.apache.felix.dm.annotation.api.Property(name = "service.pid", value = "cz.zcu.kiv.crce.metadata") -}) -public class LogHelperImpl implements LogHelper, ManagedService { - - private static final Logger logger = LoggerFactory.getLogger(LogHelperImpl.class); - - public static final String CFG__JSON_TO_STRING_ENABLED = "json-to-string.enabled"; - public static final String CFG__JSON_TO_STRING_PRETTY_PRINT = "json-to-string.pretty-print"; - - private boolean available = true; - private boolean prettyPrint = false; - - @ServiceDependency - private MetadataJsonMapper metadataJsonMapper; - - @Override - public String toString(Entity resource) { - return metadataJsonMapper.serialize(resource, prettyPrint); - } - - @Override - public boolean available() { - return available; - } - - @Override - public void updated(Dictionary properties) throws ConfigurationException { - if (properties != null) { - Object value = properties.get(CFG__JSON_TO_STRING_ENABLED); - available = value == null || !(value instanceof String) || !"false".equalsIgnoreCase(((String) value).trim()); // default true - - value = properties.get(CFG__JSON_TO_STRING_PRETTY_PRINT); - prettyPrint = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false - - logger.info("LogHelper configured: enabled={}, pretty-print={}", available, prettyPrint); - } - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.Dictionary; + +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Entity; +import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; + +@Component(provides = {LogHelper.class, ManagedService.class}, properties = { + @org.apache.felix.dm.annotation.api.Property(name = "service.pid", value = "cz.zcu.kiv.crce.metadata") +}) +public class LogHelperImpl implements LogHelper, ManagedService { + + private static final Logger logger = LoggerFactory.getLogger(LogHelperImpl.class); + + public static final String CFG__JSON_TO_STRING_ENABLED = "json-to-string.enabled"; + public static final String CFG__JSON_TO_STRING_PRETTY_PRINT = "json-to-string.pretty-print"; + + private boolean available = true; + private boolean prettyPrint = false; + + @ServiceDependency + private MetadataJsonMapper metadataJsonMapper; + + @Override + public String toString(Entity resource) { + return metadataJsonMapper.serialize(resource, prettyPrint); + } + + @Override + public boolean available() { + return available; + } + + @Override + public void updated(Dictionary properties) throws ConfigurationException { + if (properties != null) { + Object value = properties.get(CFG__JSON_TO_STRING_ENABLED); + available = value == null || !(value instanceof String) || !"false".equalsIgnoreCase(((String) value).trim()); // default true + + value = properties.get(CFG__JSON_TO_STRING_PRETTY_PRINT); + prettyPrint = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false + + logger.info("LogHelper configured: enabled={}, pretty-print={}", available, prettyPrint); + } + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/MetadataFactoryImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/MetadataFactoryImpl.java index 54a517e8..14391d86 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/MetadataFactoryImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/MetadataFactoryImpl.java @@ -1,195 +1,195 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.net.URI; -import java.util.UUID; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * Implementation of - * MetadataFactory interface. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = MetadataFactory.class) -public class MetadataFactoryImpl implements MetadataFactory { - - @ServiceDependency(required = false) - private static LogHelper logHelper; - - @Override - public Resource createResource() { - return createResource(generateId()); - } - - @Override - public Requirement createRequirement(String namespace) { - return createRequirement(namespace, generateId()); - } - - @Override - public Capability createCapability(String namespace) { - return createCapability(namespace, generateId()); - } - - @Override - public Resource createResource(String id) { - return new ResourceImpl(id); - } - - @Override - public Requirement createRequirement(String namespace, String id) { - return new RequirementImpl(namespace, id); - } - - @Override - public Capability createCapability(String namespace, String id) { - return new CapabilityImpl(namespace, id); - } - - @Override - public Property createProperty(String namespace) { - return createProperty(namespace, generateId()); - } - - @Override - public Property createProperty(String namespace, String id) { - return new PropertyImpl(namespace, id); - } - - @Override - public Attribute createAttribute(AttributeType type, T value) { - return createAttribute(type, value, Operator.EQUAL); - } - - @Override - public Attribute createAttribute(AttributeType type, T value, Operator operator) { - return new AttributeImpl<>(type, value, operator); - } - - @Override - public Attribute createAttribute(String name, Class type, T value) { - return createAttribute(name, type, value, Operator.EQUAL); - } - - @Override - public Attribute createAttribute(String name, Class type, T value, Operator operator) { - AttributeType attributeType = new SimpleAttributeType<>(name, type); - return createAttribute(attributeType, value, operator); - } - - @Override - public Repository createRepository(URI uri) { - return createRepository(uri, generateId()); - } - - @Override - public Repository createRepository(URI uri, String id) { - return new RepositoryImpl(uri, id); - } - - @Override - public Resource cloneResource(Resource resource) { - return clone(resource); - } - - @Override - public Capability cloneCapability(Capability capability) { - return clone(capability); - } - - @Override - public Requirement cloneRequirement(Requirement requirement) { - return clone(requirement); - } - - @Override - public Property cloneProperty(Property property) { - return clone(property); - } - - @Override - public Attribute cloneAttribute(Attribute attribute) { - return clone(attribute); - } - - private String generateId() { - return UUID.randomUUID().toString(); - } - - /** - * Experimental cloning method. - * - * @param - * @param object - * @return - */ - @SuppressWarnings("unchecked") - private static T clone(T object) { - try { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - try (ObjectOutputStream objOut = new ObjectOutputStream(byteArrayOutputStream)) { - objOut.writeObject(object); - } - - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); - return (T) new ObjectInputStream(byteArrayInputStream).readObject(); - } catch (ClassNotFoundException | IOException e) { - throw new RuntimeException(e); - } - } - - static String toString(Resource resource) { - if (logHelper != null && logHelper.available()) { - return logHelper.toString(resource); - } - return "ResourceImpl{" + "id=" + resource.getId() + "}"; - } - - static String toString(Capability capability) { - if (logHelper != null && logHelper.available()) { - return logHelper.toString(capability); - } - return "CapabilityImpl{" + "id=" + capability.getId() + "}"; - } - - static String toString(Requirement requirement) { - if (logHelper != null && logHelper.available()) { - return logHelper.toString(requirement); - } - return "RequirementImpl{" + "id=" + requirement.getId() + "}"; - } - - static String toString(Property property) { - if (logHelper != null && logHelper.available()) { - return logHelper.toString(property); - } - return "PropertyImpl{" + "id=" + property.getId() + "}"; - } - - static String toString(Attribute attribute) { - if (logHelper != null && logHelper.available()) { - return logHelper.toString(attribute); - } - return "AttributeImpl{" + "name=" + attribute.getName() + ", type=" + attribute.getType().getName() + ", value=" + attribute.getStringValue() + "}"; - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.net.URI; +import java.util.UUID; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * Implementation of + * MetadataFactory interface. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = MetadataFactory.class) +public class MetadataFactoryImpl implements MetadataFactory { + + @ServiceDependency(required = false) + private static LogHelper logHelper; + + @Override + public Resource createResource() { + return createResource(generateId()); + } + + @Override + public Requirement createRequirement(String namespace) { + return createRequirement(namespace, generateId()); + } + + @Override + public Capability createCapability(String namespace) { + return createCapability(namespace, generateId()); + } + + @Override + public Resource createResource(String id) { + return new ResourceImpl(id); + } + + @Override + public Requirement createRequirement(String namespace, String id) { + return new RequirementImpl(namespace, id); + } + + @Override + public Capability createCapability(String namespace, String id) { + return new CapabilityImpl(namespace, id); + } + + @Override + public Property createProperty(String namespace) { + return createProperty(namespace, generateId()); + } + + @Override + public Property createProperty(String namespace, String id) { + return new PropertyImpl(namespace, id); + } + + @Override + public Attribute createAttribute(AttributeType type, T value) { + return createAttribute(type, value, Operator.EQUAL); + } + + @Override + public Attribute createAttribute(AttributeType type, T value, Operator operator) { + return new AttributeImpl<>(type, value, operator); + } + + @Override + public Attribute createAttribute(String name, Class type, T value) { + return createAttribute(name, type, value, Operator.EQUAL); + } + + @Override + public Attribute createAttribute(String name, Class type, T value, Operator operator) { + AttributeType attributeType = new SimpleAttributeType<>(name, type); + return createAttribute(attributeType, value, operator); + } + + @Override + public Repository createRepository(URI uri) { + return createRepository(uri, generateId()); + } + + @Override + public Repository createRepository(URI uri, String id) { + return new RepositoryImpl(uri, id); + } + + @Override + public Resource cloneResource(Resource resource) { + return clone(resource); + } + + @Override + public Capability cloneCapability(Capability capability) { + return clone(capability); + } + + @Override + public Requirement cloneRequirement(Requirement requirement) { + return clone(requirement); + } + + @Override + public Property cloneProperty(Property property) { + return clone(property); + } + + @Override + public Attribute cloneAttribute(Attribute attribute) { + return clone(attribute); + } + + private String generateId() { + return UUID.randomUUID().toString(); + } + + /** + * Experimental cloning method. + * + * @param + * @param object + * @return + */ + @SuppressWarnings("unchecked") + private static T clone(T object) { + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + try (ObjectOutputStream objOut = new ObjectOutputStream(byteArrayOutputStream)) { + objOut.writeObject(object); + } + + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + return (T) new ObjectInputStream(byteArrayInputStream).readObject(); + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException(e); + } + } + + static String toString(Resource resource) { + if (logHelper != null && logHelper.available()) { + return logHelper.toString(resource); + } + return "ResourceImpl{" + "id=" + resource.getId() + "}"; + } + + static String toString(Capability capability) { + if (logHelper != null && logHelper.available()) { + return logHelper.toString(capability); + } + return "CapabilityImpl{" + "id=" + capability.getId() + "}"; + } + + static String toString(Requirement requirement) { + if (logHelper != null && logHelper.available()) { + return logHelper.toString(requirement); + } + return "RequirementImpl{" + "id=" + requirement.getId() + "}"; + } + + static String toString(Property property) { + if (logHelper != null && logHelper.available()) { + return logHelper.toString(property); + } + return "PropertyImpl{" + "id=" + property.getId() + "}"; + } + + static String toString(Attribute attribute) { + if (logHelper != null && logHelper.available()) { + return logHelper.toString(attribute); + } + return "AttributeImpl{" + "name=" + attribute.getName() + ", type=" + attribute.getType().getName() + ", value=" + attribute.getStringValue() + "}"; + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyImpl.java index 93a4213c..0ef48397 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyImpl.java @@ -1,107 +1,107 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.Objects; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.Property; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - * @param - */ -public class PropertyImpl extends AttributeProviderImpl implements Property, Comparable { - - private static final long serialVersionUID = -7003533524061344584L; - - private final String id; - private String namespace = null; - - public PropertyImpl(@Nonnull String namespace, @Nonnull String id) { - this.namespace = namespace; - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getNamespace() { - return namespace; - } - - @Override - public boolean equalsTo(Property other, EqualityLevel level) { - if (other == null) { - return false; - } - switch (level) { - case KEY: - return id.equals(other.getId()); - - case SHALLOW_NO_KEY: - if (!Objects.equals(this.namespace, other.getNamespace())) { - return false; - } - if (!Objects.equals(this.attributesMap, other.getAttributesMap())) { - return false; - } - return true; - - case SHALLOW_WITH_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.KEY)) { - return false; - } - return this.equalsTo(other, EqualityLevel.SHALLOW_NO_KEY); - - case DEEP_NO_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { - return false; - } - return true; - - case DEEP_WITH_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { - return false; - } - return true; - - default: - return equalsTo(other, EqualityLevel.KEY); - - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PropertyImpl other = (PropertyImpl) obj; - return Objects.equals(this.id, other.id); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 37 * hash + Objects.hashCode(this.id); - return hash; - } - - @Override - public String toString() { - return MetadataFactoryImpl.toString(this); - } - - @Override - public int compareTo(Property o) { - return id.compareTo(o.getId()); - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.Objects; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.Property; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + * @param + */ +public class PropertyImpl extends AttributeProviderImpl implements Property, Comparable { + + private static final long serialVersionUID = -7003533524061344584L; + + private final String id; + private String namespace = null; + + public PropertyImpl(@Nonnull String namespace, @Nonnull String id) { + this.namespace = namespace; + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getNamespace() { + return namespace; + } + + @Override + public boolean equalsTo(Property other, EqualityLevel level) { + if (other == null) { + return false; + } + switch (level) { + case KEY: + return id.equals(other.getId()); + + case SHALLOW_NO_KEY: + if (!Objects.equals(this.namespace, other.getNamespace())) { + return false; + } + if (!Objects.equals(this.attributesMap, other.getAttributesMap())) { + return false; + } + return true; + + case SHALLOW_WITH_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.KEY)) { + return false; + } + return this.equalsTo(other, EqualityLevel.SHALLOW_NO_KEY); + + case DEEP_NO_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { + return false; + } + return true; + + case DEEP_WITH_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { + return false; + } + return true; + + default: + return equalsTo(other, EqualityLevel.KEY); + + } + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PropertyImpl other = (PropertyImpl) obj; + return Objects.equals(this.id, other.id); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 37 * hash + Objects.hashCode(this.id); + return hash; + } + + @Override + public String toString() { + return MetadataFactoryImpl.toString(this); + } + + @Override + public int compareTo(Property o) { + return id.compareTo(o.getId()); + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyProviderImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyProviderImpl.java index a34812cc..6821546e 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyProviderImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/PropertyProviderImpl.java @@ -1,67 +1,67 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.PropertyProvider; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class PropertyProviderImpl implements PropertyProvider { - - private static final long serialVersionUID = 1L; - - private final Map> allProperties = new HashMap<>(); - - @Override - public List getProperties() { - List result = new ArrayList<>(); - for (List properties : allProperties.values()) { - result.addAll(properties); - } - return result; - } - - @Override - public List getProperties(String namespace) { - List result = allProperties.get(namespace); - if (result == null) { - result = Collections.emptyList(); - } - return result; - } - - @Override - public boolean hasProperty(Property property) { - List properties = allProperties.get(property.getNamespace()); - if (properties != null) { - return properties.contains(property); - } - return false; - } - - @Override - public void addProperty(Property property) { - List properties = allProperties.get(property.getNamespace()); - if (properties == null) { - properties = new ArrayList<>(); - allProperties.put(property.getNamespace(), properties); - } - properties.add(property); - } - - @Override - public void removeProperty(Property property) { - List properties = allProperties.get(property.getNamespace()); - if (properties != null) { - properties.remove(property); - } - } - -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.PropertyProvider; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class PropertyProviderImpl implements PropertyProvider { + + private static final long serialVersionUID = 1L; + + private final Map> allProperties = new HashMap<>(); + + @Override + public List getProperties() { + List result = new ArrayList<>(); + for (List properties : allProperties.values()) { + result.addAll(properties); + } + return result; + } + + @Override + public List getProperties(String namespace) { + List result = allProperties.get(namespace); + if (result == null) { + result = Collections.emptyList(); + } + return result; + } + + @Override + public boolean hasProperty(Property property) { + List properties = allProperties.get(property.getNamespace()); + if (properties != null) { + return properties.contains(property); + } + return false; + } + + @Override + public void addProperty(Property property) { + List properties = allProperties.get(property.getNamespace()); + if (properties == null) { + properties = new ArrayList<>(); + allProperties.put(property.getNamespace(), properties); + } + properties.add(property); + } + + @Override + public void removeProperty(Property property) { + List properties = allProperties.get(property.getNamespace()); + if (properties != null) { + properties.remove(property); + } + } + +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/RepositoryImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/RepositoryImpl.java index fc8ee27c..b7447346 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/RepositoryImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/RepositoryImpl.java @@ -1,60 +1,60 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.net.URI; -import java.util.Objects; - -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Repository; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public class RepositoryImpl implements Repository { - - private static final long serialVersionUID = -5217714862846966653L; - - private final String id; - private final URI uri; - - public RepositoryImpl(URI uri, String id) { - this.uri = uri; - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public URI getUri() { - return uri; - } - - @Override - public int hashCode() { - int hash = 3; - hash = 97 * hash + Objects.hashCode(this.uri); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final RepositoryImpl other = (RepositoryImpl) obj; - return Objects.equals(this.uri, other.uri); - } - - @Override - public String toString() { - return "RepositoryImpl{" + "uri=" + uri + '}'; - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.net.URI; +import java.util.Objects; + +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Repository; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public class RepositoryImpl implements Repository { + + private static final long serialVersionUID = -5217714862846966653L; + + private final String id; + private final URI uri; + + public RepositoryImpl(URI uri, String id) { + this.uri = uri; + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public URI getUri() { + return uri; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 97 * hash + Objects.hashCode(this.uri); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final RepositoryImpl other = (RepositoryImpl) obj; + return Objects.equals(this.uri, other.uri); + } + + @Override + public String toString() { + return "RepositoryImpl{" + "uri=" + uri + '}'; + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/ResourceImpl.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/ResourceImpl.java index c59ba773..873b9986 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/ResourceImpl.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/ResourceImpl.java @@ -1,247 +1,247 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Objects; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * Implementation of Resource interface. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ResourceImpl extends PropertyProviderImpl implements Resource, Comparable { - - private static final long serialVersionUID = 2594634894045505360L; - - private final String id; - /* - * All maps: - * Key: namespace, value: list of entities. - */ - private final Map> allCapabilities = new HashMap<>(); - private final Map> rootCapabilities = new HashMap<>(); - private final Map> allRequirements = new HashMap<>(); - - public ResourceImpl(@Nonnull String id) { - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public List getCapabilities() { - List result = new ArrayList<>(); - for (List capabilities : allCapabilities.values()) { - result.addAll(capabilities); - } - return result; - } - - @Override - public List getRootCapabilities() { - List result = new ArrayList<>(); - for (List capabilities : rootCapabilities.values()) { - result.addAll(capabilities); - } - return result; - } - - @Override - public List getRootCapabilities(String namespace) { - List capabilities = rootCapabilities.get(namespace); - if (capabilities == null) { - capabilities = Collections.emptyList(); - } - return capabilities; - } - - @Override - public List getCapabilities(String namespace) { - List capabilities = allCapabilities.get(namespace); - if (capabilities == null) { - capabilities = Collections.emptyList(); - } - return capabilities; - } - - @Override - public boolean hasCapability(Capability capability) { - List capabilities = allCapabilities.get(capability.getNamespace()); - if (capabilities != null) { - return capabilities.contains(capability); - } - return false; - } - - @Override - public void addCapability(Capability capability) { - List capabilities = allCapabilities.get(capability.getNamespace()); - if (capabilities == null) { - capabilities = new ArrayList<>(); - allCapabilities.put(capability.getNamespace(), capabilities); - } - capabilities.add(capability); - } - - @Override - public void addRootCapability(Capability capability) { - List capabilities = rootCapabilities.get(capability.getNamespace()); - if (capabilities == null) { - capabilities = new ArrayList<>(); - rootCapabilities.put(capability.getNamespace(), capabilities); - } - capabilities.add(capability); - } - - @Override - public void removeCapability(Capability capability) { - List roots = allCapabilities.get(capability.getNamespace()); - if (roots != null) { - roots.remove(capability); - } - } - - @Override - public void removeRootCapability(Capability capability) { - List all = rootCapabilities.get(capability.getNamespace()); - if (all != null) { - all.remove(capability); - } - } - - @Override - public List getRequirements() { - List result = new ArrayList<>(); - for (List requirements : allRequirements.values()) { - result.addAll(requirements); - } - return result; - } - - @Override - public List getRequirements(String namespace) { - List result = allRequirements.get(namespace); - if (result == null) { - result = Collections.emptyList(); - } - return result; - } - - @Override - public boolean hasRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements != null) { - return requirements.contains(requirement); - } - return false; - } - - @Override - public void addRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements == null) { - requirements = new ArrayList<>(); - allRequirements.put(requirement.getNamespace(), requirements); - } - requirements.add(requirement); - } - - @Override - public void removeRequirement(Requirement requirement) { - List requirements = allRequirements.get(requirement.getNamespace()); - if (requirements != null) { - requirements.remove(requirement); - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() == obj.getClass() || obj instanceof Resource) { - final Resource other = (Resource) obj; - return Objects.equals(this.id, other.getId()); - } - return false; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 79 * hash + Objects.hashCode(this.id); - return hash; - } - - @Override - public boolean equalsTo(Resource other, EqualityLevel level) { - if (other == null) { - return false; - } - switch (level) { - case KEY: - return id.equals(other.getId()); - - case SHALLOW_NO_KEY: - return true; - - case SHALLOW_WITH_KEY: - return Util.equalsTo(this, other, EqualityLevel.KEY); - - case DEEP_NO_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { - return false; - } - if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_NO_KEY)) { - return false; - } - if (!Util.equalsTo(getCapabilities(), other.getCapabilities(), EqualityLevel.DEEP_NO_KEY)) { - return false; - } - if (!Util.equalsTo(getProperties(), other.getProperties(), EqualityLevel.DEEP_NO_KEY)) { - return false; - } - return true; - - case DEEP_WITH_KEY: - if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { - return false; - } - if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_WITH_KEY)) { - return false; - } - if (!Util.equalsTo(getCapabilities(), other.getCapabilities(), EqualityLevel.DEEP_WITH_KEY)) { - return false; - } - if (!Util.equalsTo(getProperties(), other.getProperties(), EqualityLevel.DEEP_WITH_KEY)) { - return false; - } - return true; - - default: - return equalsTo(other, EqualityLevel.KEY); - } - } - - @Override - public int compareTo(Resource o) { - return id.compareTo(o.getId()); - } - - @Override - public String toString() { - return MetadataFactoryImpl.toString(this); - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.List; +import java.util.Map; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Objects; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * Implementation of Resource interface. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ResourceImpl extends PropertyProviderImpl implements Resource, Comparable { + + private static final long serialVersionUID = 2594634894045505360L; + + private final String id; + /* + * All maps: + * Key: namespace, value: list of entities. + */ + private final Map> allCapabilities = new HashMap<>(); + private final Map> rootCapabilities = new HashMap<>(); + private final Map> allRequirements = new HashMap<>(); + + public ResourceImpl(@Nonnull String id) { + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public List getCapabilities() { + List result = new ArrayList<>(); + for (List capabilities : allCapabilities.values()) { + result.addAll(capabilities); + } + return result; + } + + @Override + public List getRootCapabilities() { + List result = new ArrayList<>(); + for (List capabilities : rootCapabilities.values()) { + result.addAll(capabilities); + } + return result; + } + + @Override + public List getRootCapabilities(String namespace) { + List capabilities = rootCapabilities.get(namespace); + if (capabilities == null) { + capabilities = Collections.emptyList(); + } + return capabilities; + } + + @Override + public List getCapabilities(String namespace) { + List capabilities = allCapabilities.get(namespace); + if (capabilities == null) { + capabilities = Collections.emptyList(); + } + return capabilities; + } + + @Override + public boolean hasCapability(Capability capability) { + List capabilities = allCapabilities.get(capability.getNamespace()); + if (capabilities != null) { + return capabilities.contains(capability); + } + return false; + } + + @Override + public void addCapability(Capability capability) { + List capabilities = allCapabilities.get(capability.getNamespace()); + if (capabilities == null) { + capabilities = new ArrayList<>(); + allCapabilities.put(capability.getNamespace(), capabilities); + } + capabilities.add(capability); + } + + @Override + public void addRootCapability(Capability capability) { + List capabilities = rootCapabilities.get(capability.getNamespace()); + if (capabilities == null) { + capabilities = new ArrayList<>(); + rootCapabilities.put(capability.getNamespace(), capabilities); + } + capabilities.add(capability); + } + + @Override + public void removeCapability(Capability capability) { + List roots = allCapabilities.get(capability.getNamespace()); + if (roots != null) { + roots.remove(capability); + } + } + + @Override + public void removeRootCapability(Capability capability) { + List all = rootCapabilities.get(capability.getNamespace()); + if (all != null) { + all.remove(capability); + } + } + + @Override + public List getRequirements() { + List result = new ArrayList<>(); + for (List requirements : allRequirements.values()) { + result.addAll(requirements); + } + return result; + } + + @Override + public List getRequirements(String namespace) { + List result = allRequirements.get(namespace); + if (result == null) { + result = Collections.emptyList(); + } + return result; + } + + @Override + public boolean hasRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements != null) { + return requirements.contains(requirement); + } + return false; + } + + @Override + public void addRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements == null) { + requirements = new ArrayList<>(); + allRequirements.put(requirement.getNamespace(), requirements); + } + requirements.add(requirement); + } + + @Override + public void removeRequirement(Requirement requirement) { + List requirements = allRequirements.get(requirement.getNamespace()); + if (requirements != null) { + requirements.remove(requirement); + } + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() == obj.getClass() || obj instanceof Resource) { + final Resource other = (Resource) obj; + return Objects.equals(this.id, other.getId()); + } + return false; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 79 * hash + Objects.hashCode(this.id); + return hash; + } + + @Override + public boolean equalsTo(Resource other, EqualityLevel level) { + if (other == null) { + return false; + } + switch (level) { + case KEY: + return id.equals(other.getId()); + + case SHALLOW_NO_KEY: + return true; + + case SHALLOW_WITH_KEY: + return Util.equalsTo(this, other, EqualityLevel.KEY); + + case DEEP_NO_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_NO_KEY)) { + return false; + } + if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_NO_KEY)) { + return false; + } + if (!Util.equalsTo(getCapabilities(), other.getCapabilities(), EqualityLevel.DEEP_NO_KEY)) { + return false; + } + if (!Util.equalsTo(getProperties(), other.getProperties(), EqualityLevel.DEEP_NO_KEY)) { + return false; + } + return true; + + case DEEP_WITH_KEY: + if (!Util.equalsTo(this, other, EqualityLevel.SHALLOW_WITH_KEY)) { + return false; + } + if (!Util.equalsTo(getRequirements(), other.getRequirements(), EqualityLevel.DEEP_WITH_KEY)) { + return false; + } + if (!Util.equalsTo(getCapabilities(), other.getCapabilities(), EqualityLevel.DEEP_WITH_KEY)) { + return false; + } + if (!Util.equalsTo(getProperties(), other.getProperties(), EqualityLevel.DEEP_WITH_KEY)) { + return false; + } + return true; + + default: + return equalsTo(other, EqualityLevel.KEY); + } + } + + @Override + public int compareTo(Resource o) { + return id.compareTo(o.getId()); + } + + @Override + public String toString() { + return MetadataFactoryImpl.toString(this); + } +} diff --git a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/Util.java b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/Util.java index cf0aae14..553ab80b 100644 --- a/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/Util.java +++ b/core/crce-metadata-impl/src/main/java/cz/zcu/kiv/crce/metadata/internal/Util.java @@ -1,48 +1,48 @@ -package cz.zcu.kiv.crce.metadata.internal; - -import java.util.Iterator; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -import cz.zcu.kiv.crce.metadata.EqualityComparable; -import cz.zcu.kiv.crce.metadata.EqualityLevel; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Util { - - public static > boolean equalsTo(T a, T b, EqualityLevel level) { - return (a == b) || (a != null && a.equalsTo(b, level)); // NOPMD better clarity - } - - public static > boolean equalsTo(List a, List b, EqualityLevel level) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - if (a.size() != b.size()) { - return false; - } - SortedSet set1 = new TreeSet<>(a); - SortedSet set2 = new TreeSet<>(b); - if (set1.size() != set2.size()) { - return false; - } - Iterator it1 = set1.iterator(); - Iterator it2 = set2.iterator(); - - while (it1.hasNext() && it2.hasNext()) { - T o1 = it1.next(); - T o2 = it2.next(); - if (!equalsTo(o1, o2, level)) { - return false; - } - } - return true; - } -} +package cz.zcu.kiv.crce.metadata.internal; + +import java.util.Iterator; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import cz.zcu.kiv.crce.metadata.EqualityComparable; +import cz.zcu.kiv.crce.metadata.EqualityLevel; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Util { + + public static > boolean equalsTo(T a, T b, EqualityLevel level) { + return (a == b) || (a != null && a.equalsTo(b, level)); // NOPMD better clarity + } + + public static > boolean equalsTo(List a, List b, EqualityLevel level) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a.size() != b.size()) { + return false; + } + SortedSet set1 = new TreeSet<>(a); + SortedSet set2 = new TreeSet<>(b); + if (set1.size() != set2.size()) { + return false; + } + Iterator it1 = set1.iterator(); + Iterator it2 = set2.iterator(); + + while (it1.hasNext() && it2.hasNext()) { + T o1 = it1.next(); + T o2 = it2.next(); + if (!equalsTo(o1, o2, level)) { + return false; + } + } + return true; + } +} diff --git a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/AttributeTest.java b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/AttributeTest.java index 43e63802..6fca4f55 100644 --- a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/AttributeTest.java +++ b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/AttributeTest.java @@ -1,96 +1,96 @@ -package cz.zcu.kiv.crce.metadata.test; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.junit.*; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.internal.AttributeImpl; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class AttributeTest { - - private final AttributeType ATTR_P1 = new SimpleAttributeType<>("p1", String.class); - private final AttributeType ATTR_P1_LONG = new SimpleAttributeType<>("p1", Long.class); - private final AttributeType ATTR_P1_DOUBLE = new SimpleAttributeType<>("p1", Double.class); - private final AttributeType ATTR_P2 = new SimpleAttributeType<>("p2", String.class); - - @Test - public void equalsNames() throws Exception { - assert (new AttributeImpl<>(ATTR_P1, "1")).equals( - new AttributeImpl<>(ATTR_P1, "1")); - - assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( - new AttributeImpl<>(ATTR_P2, "1")); - } - - @Test - public void equalsTypes() throws Exception { - - assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( - new AttributeImpl<>(ATTR_P1_LONG, 1L)); - - assert !(new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( - new AttributeImpl<>(ATTR_P1_DOUBLE, 1.)); - - assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( - new AttributeImpl<>(ATTR_P1_DOUBLE, 1.)); - } - - @Test - public void equalsValues() throws Exception { - assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( - new AttributeImpl<>(ATTR_P1, "2")); - - assert (new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( - new AttributeImpl<>(ATTR_P1_LONG, 1L)); - - assert !(new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( - new AttributeImpl<>(ATTR_P1_LONG, 2L)); - } - - @Test - public void hashSet() throws Exception { - Set set1 = new HashSet<>(); - Set set2 = new HashSet<>(); - - assert set1.equals(set2); - - set1.add(new AttributeImpl<>(ATTR_P1, "1")); - assert !set1.equals(set2); - - set2.add(new AttributeImpl<>(ATTR_P1, "1")); - assert set1.equals(set2); - - set2.remove(new AttributeImpl<>(ATTR_P1, "1")); - assert !set1.equals(set2); - - set2.add(new AttributeImpl<>(ATTR_P1_LONG, 1L)); - assert !set1.equals(set2); - } - - @Test - public void hashMap() throws Exception { - Map map1 = new HashMap<>(); - Map map2 = new HashMap<>(); - - assert map1.equals(map2); - - map1.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v1")); - assert !map1.equals(map2); - - map2.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v1")); - assert map1.equals(map2); - - map1.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v2")); - assert !map1.equals(map2); - } -} +package cz.zcu.kiv.crce.metadata.test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.*; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.internal.AttributeImpl; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class AttributeTest { + + private final AttributeType ATTR_P1 = new SimpleAttributeType<>("p1", String.class); + private final AttributeType ATTR_P1_LONG = new SimpleAttributeType<>("p1", Long.class); + private final AttributeType ATTR_P1_DOUBLE = new SimpleAttributeType<>("p1", Double.class); + private final AttributeType ATTR_P2 = new SimpleAttributeType<>("p2", String.class); + + @Test + public void equalsNames() throws Exception { + assert (new AttributeImpl<>(ATTR_P1, "1")).equals( + new AttributeImpl<>(ATTR_P1, "1")); + + assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( + new AttributeImpl<>(ATTR_P2, "1")); + } + + @Test + public void equalsTypes() throws Exception { + + assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( + new AttributeImpl<>(ATTR_P1_LONG, 1L)); + + assert !(new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( + new AttributeImpl<>(ATTR_P1_DOUBLE, 1.)); + + assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( + new AttributeImpl<>(ATTR_P1_DOUBLE, 1.)); + } + + @Test + public void equalsValues() throws Exception { + assert !(new AttributeImpl<>(ATTR_P1, "1")).equals( + new AttributeImpl<>(ATTR_P1, "2")); + + assert (new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( + new AttributeImpl<>(ATTR_P1_LONG, 1L)); + + assert !(new AttributeImpl<>(ATTR_P1_LONG, 1L)).equals( + new AttributeImpl<>(ATTR_P1_LONG, 2L)); + } + + @Test + public void hashSet() throws Exception { + Set set1 = new HashSet<>(); + Set set2 = new HashSet<>(); + + assert set1.equals(set2); + + set1.add(new AttributeImpl<>(ATTR_P1, "1")); + assert !set1.equals(set2); + + set2.add(new AttributeImpl<>(ATTR_P1, "1")); + assert set1.equals(set2); + + set2.remove(new AttributeImpl<>(ATTR_P1, "1")); + assert !set1.equals(set2); + + set2.add(new AttributeImpl<>(ATTR_P1_LONG, 1L)); + assert !set1.equals(set2); + } + + @Test + public void hashMap() throws Exception { + Map map1 = new HashMap<>(); + Map map2 = new HashMap<>(); + + assert map1.equals(map2); + + map1.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v1")); + assert !map1.equals(map2); + + map2.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v1")); + assert map1.equals(map2); + + map1.put(ATTR_P1, new AttributeImpl<>(ATTR_P1, "v2")); + assert !map1.equals(map2); + } +} diff --git a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/CapabilityTest.java b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/CapabilityTest.java index fecf603f..a68079f0 100644 --- a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/CapabilityTest.java +++ b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/CapabilityTest.java @@ -1,163 +1,163 @@ -package cz.zcu.kiv.crce.metadata.test; - -import java.util.List; -import static org.junit.Assert.*; - - -import org.junit.Before; -import org.junit.Test; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class CapabilityTest { - - private MetadataFactory factory; - - private final AttributeType ATTR_P1 = new SimpleAttributeType<>("p1", String.class); - private final AttributeType ATTR_P2 = new SimpleAttributeType<>("p2", Long.class); - private final AttributeType ATTR_P3 = new SimpleAttributeType<>("p3", String.class); - - @Before - public void before(){ - factory = new MetadataFactoryImpl(); - } - - @Test - public void testSetAttribute() throws Exception { - Capability c = factory.createCapability("a"); - c.setAttribute(ATTR_P1, "1"); - c.setAttribute(ATTR_P2, 2L); - - assertEquals("a", c.getNamespace()); - assertEquals("1", c.getAttributeValue(ATTR_P1)); - assertEquals(2L, (long) c.getAttributeValue(ATTR_P2)); - } - - @Test - public void testUnsetAttribute() throws Exception { - Capability c = factory.createCapability("a"); - c.setAttribute(ATTR_P1, "1"); - c.setAttribute(ATTR_P2, 2L); - - assertNotNull(c.getAttribute(ATTR_P1)); - assertNotNull(c.getAttribute(ATTR_P2)); - - c.removeAttribute(ATTR_P1); - - assertNull(c.getAttribute(ATTR_P1)); - assertNotNull(c.getAttribute(ATTR_P2)); - - Attribute attribute = c.getAttribute(ATTR_P2); - - assertNotNull(attribute); - - c.removeAttribute(attribute); - - assertNull(c.getAttribute(ATTR_P1)); - assertNull(c.getAttribute(ATTR_P2)); - } - - @Test - public void testUniqueAttributes() throws Exception { - Capability c1 = factory.createCapability("a"); - - c1.setAttribute(ATTR_P1, "a"); - assertEquals(1, c1.getAttributes().size()); - - c1.setAttribute(ATTR_P1, "a"); - assertEquals(1, c1.getAttributes().size()); - - c1.setAttribute(ATTR_P1, "b"); - assertEquals(1, c1.getAttributes().size()); - - c1.setAttribute(ATTR_P3, "a"); - assertEquals(2, c1.getAttributes().size()); - } - - @Test - public void equals() throws Exception { - Capability c1 = factory.createCapability("a"); - Capability c2 = factory.createCapability("a"); - - assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); - - c1.setAttribute(ATTR_P1, "v1"); - assertFalse(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); - - - c2.setAttribute(ATTR_P1, "v1"); - assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); - } - - - @Test - public void testEqualNamespaces() { - Capability c1 = factory.createCapability("cap"); - Capability c2 = factory.createCapability("cap"); - Capability c3 = factory.createCapability("cap3"); - - assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); - assertFalse(c1.equalsTo(c3, EqualityLevel.SHALLOW_NO_KEY)); - assertFalse(c2.equalsTo(c3, EqualityLevel.SHALLOW_NO_KEY)); - } - - @Test - public void testHashSetContains() throws Exception { - Capability c1 = factory.createCapability("a"); - Capability c2 = factory.createCapability("a"); - - assertNotNull(c1); - assertNotNull(c2); - - assertNotEquals(c1.hashCode(), c2.hashCode()); - - c1.setAttribute(ATTR_P1, "p1"); - - assertNotEquals(c1.hashCode(), c2.hashCode()); - - c2.setAttribute(ATTR_P1, "p1"); - - assertNotEquals(c1.hashCode(), c2.hashCode()); - } - - @Test - public void testHierarchy() { - Capability root = factory.createCapability("a"); - - Capability child1 = factory.createCapability("a.b"); - child1.setAttribute("key", String.class, "child1"); - - Capability child2 = factory.createCapability("a.b"); - child2.setAttribute("key", String.class, "child2"); - - Capability child3 = factory.createCapability("a.c"); - - root.addChild(child1); - root.addChild(child1); - root.addChild(child2); - root.addChild(child2); - root.addChild(child3); - root.addChild(child3); - - // checking of presence of added child is commented because of possible performance decrease - - List children = root.getChildren(); - // with the check enabled, expected value would be 3 - assertEquals(6, children.size()); - - assertTrue(children.contains(child1)); - assertTrue(children.contains(child2)); - assertTrue(children.contains(child3)); - } -} +package cz.zcu.kiv.crce.metadata.test; + +import java.util.List; +import static org.junit.Assert.*; + + +import org.junit.Before; +import org.junit.Test; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class CapabilityTest { + + private MetadataFactory factory; + + private final AttributeType ATTR_P1 = new SimpleAttributeType<>("p1", String.class); + private final AttributeType ATTR_P2 = new SimpleAttributeType<>("p2", Long.class); + private final AttributeType ATTR_P3 = new SimpleAttributeType<>("p3", String.class); + + @Before + public void before(){ + factory = new MetadataFactoryImpl(); + } + + @Test + public void testSetAttribute() throws Exception { + Capability c = factory.createCapability("a"); + c.setAttribute(ATTR_P1, "1"); + c.setAttribute(ATTR_P2, 2L); + + assertEquals("a", c.getNamespace()); + assertEquals("1", c.getAttributeValue(ATTR_P1)); + assertEquals(2L, (long) c.getAttributeValue(ATTR_P2)); + } + + @Test + public void testUnsetAttribute() throws Exception { + Capability c = factory.createCapability("a"); + c.setAttribute(ATTR_P1, "1"); + c.setAttribute(ATTR_P2, 2L); + + assertNotNull(c.getAttribute(ATTR_P1)); + assertNotNull(c.getAttribute(ATTR_P2)); + + c.removeAttribute(ATTR_P1); + + assertNull(c.getAttribute(ATTR_P1)); + assertNotNull(c.getAttribute(ATTR_P2)); + + Attribute attribute = c.getAttribute(ATTR_P2); + + assertNotNull(attribute); + + c.removeAttribute(attribute); + + assertNull(c.getAttribute(ATTR_P1)); + assertNull(c.getAttribute(ATTR_P2)); + } + + @Test + public void testUniqueAttributes() throws Exception { + Capability c1 = factory.createCapability("a"); + + c1.setAttribute(ATTR_P1, "a"); + assertEquals(1, c1.getAttributes().size()); + + c1.setAttribute(ATTR_P1, "a"); + assertEquals(1, c1.getAttributes().size()); + + c1.setAttribute(ATTR_P1, "b"); + assertEquals(1, c1.getAttributes().size()); + + c1.setAttribute(ATTR_P3, "a"); + assertEquals(2, c1.getAttributes().size()); + } + + @Test + public void equals() throws Exception { + Capability c1 = factory.createCapability("a"); + Capability c2 = factory.createCapability("a"); + + assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); + + c1.setAttribute(ATTR_P1, "v1"); + assertFalse(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); + + + c2.setAttribute(ATTR_P1, "v1"); + assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); + } + + + @Test + public void testEqualNamespaces() { + Capability c1 = factory.createCapability("cap"); + Capability c2 = factory.createCapability("cap"); + Capability c3 = factory.createCapability("cap3"); + + assertTrue(c1.equalsTo(c2, EqualityLevel.SHALLOW_NO_KEY)); + assertFalse(c1.equalsTo(c3, EqualityLevel.SHALLOW_NO_KEY)); + assertFalse(c2.equalsTo(c3, EqualityLevel.SHALLOW_NO_KEY)); + } + + @Test + public void testHashSetContains() throws Exception { + Capability c1 = factory.createCapability("a"); + Capability c2 = factory.createCapability("a"); + + assertNotNull(c1); + assertNotNull(c2); + + assertNotEquals(c1.hashCode(), c2.hashCode()); + + c1.setAttribute(ATTR_P1, "p1"); + + assertNotEquals(c1.hashCode(), c2.hashCode()); + + c2.setAttribute(ATTR_P1, "p1"); + + assertNotEquals(c1.hashCode(), c2.hashCode()); + } + + @Test + public void testHierarchy() { + Capability root = factory.createCapability("a"); + + Capability child1 = factory.createCapability("a.b"); + child1.setAttribute("key", String.class, "child1"); + + Capability child2 = factory.createCapability("a.b"); + child2.setAttribute("key", String.class, "child2"); + + Capability child3 = factory.createCapability("a.c"); + + root.addChild(child1); + root.addChild(child1); + root.addChild(child2); + root.addChild(child2); + root.addChild(child3); + root.addChild(child3); + + // checking of presence of added child is commented because of possible performance decrease + + List children = root.getChildren(); + // with the check enabled, expected value would be 3 + assertEquals(6, children.size()); + + assertTrue(children.contains(child1)); + assertTrue(children.contains(child2)); + assertTrue(children.contains(child3)); + } +} diff --git a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RepositoryTest.java b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RepositoryTest.java index e3cd546c..5258ebd2 100644 --- a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RepositoryTest.java +++ b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RepositoryTest.java @@ -1,55 +1,55 @@ -package cz.zcu.kiv.crce.metadata.test; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.Repository; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class RepositoryTest { - - private Repository repository; - private Resource resource; - -// @Before -// public void before() throws Exception { -// repository = new RepositoryImpl(new URI("some:uri")); -// resource = new ResourceImpl(); -// -// resource.setSymbolicName("r1"); -// resource.setVersion("1.0.0"); -// } -// -// @Test -// public void add() throws Exception { -// repository.addResource(resource); -// repository.addResource(resource); -// assert repository.contains(resource); -// assert repository.getResources().length == 1; -// } -// -// @Test -// public void remove() throws Exception { -// repository.addResource(resource); -// repository.removeResource(resource); -// -// assert !repository.contains(resource); -// assert repository.getResources().length == 0; -// } -// -// @Test -// public void changeSymbolicName() throws Exception { -// repository.addResource(resource); -// resource.setSymbolicName("r2"); -// assert repository.contains(resource); -// } -// -// @Test -// public void changeVersion() throws Exception { -// repository.addResource(resource); -// resource.setVersion("1.0.1"); -// assert repository.contains(resource); -// } - -} +package cz.zcu.kiv.crce.metadata.test; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.Repository; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class RepositoryTest { + + private Repository repository; + private Resource resource; + +// @Before +// public void before() throws Exception { +// repository = new RepositoryImpl(new URI("some:uri")); +// resource = new ResourceImpl(); +// +// resource.setSymbolicName("r1"); +// resource.setVersion("1.0.0"); +// } +// +// @Test +// public void add() throws Exception { +// repository.addResource(resource); +// repository.addResource(resource); +// assert repository.contains(resource); +// assert repository.getResources().length == 1; +// } +// +// @Test +// public void remove() throws Exception { +// repository.addResource(resource); +// repository.removeResource(resource); +// +// assert !repository.contains(resource); +// assert repository.getResources().length == 0; +// } +// +// @Test +// public void changeSymbolicName() throws Exception { +// repository.addResource(resource); +// resource.setSymbolicName("r2"); +// assert repository.contains(resource); +// } +// +// @Test +// public void changeVersion() throws Exception { +// repository.addResource(resource); +// resource.setVersion("1.0.1"); +// assert repository.contains(resource); +// } + +} diff --git a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RequirementTest.java b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RequirementTest.java index 96090ff2..8253d7b7 100644 --- a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RequirementTest.java +++ b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/RequirementTest.java @@ -1,123 +1,123 @@ -package cz.zcu.kiv.crce.metadata.test; - -import static org.junit.Assert.*; - -import org.junit.*; - -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.internal.RequirementImpl; -import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class RequirementTest { - - private Requirement r1; - private Requirement r2; - private Requirement r3; - private MetadataFactory rc; - - @Before - public void before() { - rc = new MetadataFactoryImpl(); - r1 = new RequirementImpl("req", "a"); - r2 = new RequirementImpl("req", "b"); - r3 = new RequirementImpl("req3", "c"); - } - - @Test - public void equalsName() { - assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - assertFalse(r1.equalsTo(r3, EqualityLevel.SHALLOW_NO_KEY)); - assertFalse(r2.equalsTo(r3, EqualityLevel.SHALLOW_NO_KEY)); - } - - @Test - public void testEqualAttributes() { - r1.addAttribute("atr1", String.class, "value", Operator.EQUAL); - assert !r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY); - - r2.addAttribute("atr1", String.class, "value", Operator.EQUAL); - assert r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY); - } - - @Test - public void testAttributesWithOperator() { - r1.addAttribute("atr1", String.class, "value", Operator.GREATER); - assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - - r2.addAttribute("atr1", String.class, "value", Operator.GREATER); - assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - - r1.addAttribute("atr1", String.class, "value", Operator.LESS); - r1.equals(r2); - System.out.println("eq: " + r1.equals(r2)); - assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - } - - @Test - public void testDirectives() { - r1.setDirective("optional", "true"); - - assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - - r2.setDirective("optional", "true"); - assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - - r1.setDirective("multiple", "false"); - assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); - - assertEquals("true", r1.getDirective("optional")); - assertEquals("false", r1.getDirective("multiple")); - - assertNull(r1.getDirective("unknown")); - } - -// @Test -// public void equals() { -// r1.setOptional(true); -// r1.setMultiple(true); -// r1.setExtend(true); -// r1.setFilter("(&(a=1)(b=2))"); -// assert !r1.equals(r2); -// -// r2.setOptional(true); -// assert !r1.equals(r2); -// -// r2.setMultiple(true); -// assert !r1.equals(r2); -// -// r2.setExtend(true); -// assert !r1.equals(r2); -// -// r2.setFilter("(&(a=1)(b=2))"); -// assert r1.equals(r2); -// } -// -// @Test -// public void hashSet() throws Exception { -// Requirement r1 = rc.createRequirement("a"); -// Requirement r2 = rc.createRequirement("a"); -// -// Set set = new HashSet(); -// -// set.add(r1); -// -// assert set.contains(r1); -// assert set.contains(r2); -// -// r1.setFilter("(a=b)"); -// assert set.contains(r1); -// assert !set.contains(r2); -// -// r2.setFilter("(a=b)"); -// assert set.contains(r1); -// assert set.contains(r2); -// -// } -} +package cz.zcu.kiv.crce.metadata.test; + +import static org.junit.Assert.*; + +import org.junit.*; + +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.internal.RequirementImpl; +import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class RequirementTest { + + private Requirement r1; + private Requirement r2; + private Requirement r3; + private MetadataFactory rc; + + @Before + public void before() { + rc = new MetadataFactoryImpl(); + r1 = new RequirementImpl("req", "a"); + r2 = new RequirementImpl("req", "b"); + r3 = new RequirementImpl("req3", "c"); + } + + @Test + public void equalsName() { + assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + assertFalse(r1.equalsTo(r3, EqualityLevel.SHALLOW_NO_KEY)); + assertFalse(r2.equalsTo(r3, EqualityLevel.SHALLOW_NO_KEY)); + } + + @Test + public void testEqualAttributes() { + r1.addAttribute("atr1", String.class, "value", Operator.EQUAL); + assert !r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY); + + r2.addAttribute("atr1", String.class, "value", Operator.EQUAL); + assert r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY); + } + + @Test + public void testAttributesWithOperator() { + r1.addAttribute("atr1", String.class, "value", Operator.GREATER); + assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + + r2.addAttribute("atr1", String.class, "value", Operator.GREATER); + assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + + r1.addAttribute("atr1", String.class, "value", Operator.LESS); + r1.equals(r2); + System.out.println("eq: " + r1.equals(r2)); + assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + } + + @Test + public void testDirectives() { + r1.setDirective("optional", "true"); + + assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + + r2.setDirective("optional", "true"); + assertTrue(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + + r1.setDirective("multiple", "false"); + assertFalse(r1.equalsTo(r2, EqualityLevel.SHALLOW_NO_KEY)); + + assertEquals("true", r1.getDirective("optional")); + assertEquals("false", r1.getDirective("multiple")); + + assertNull(r1.getDirective("unknown")); + } + +// @Test +// public void equals() { +// r1.setOptional(true); +// r1.setMultiple(true); +// r1.setExtend(true); +// r1.setFilter("(&(a=1)(b=2))"); +// assert !r1.equals(r2); +// +// r2.setOptional(true); +// assert !r1.equals(r2); +// +// r2.setMultiple(true); +// assert !r1.equals(r2); +// +// r2.setExtend(true); +// assert !r1.equals(r2); +// +// r2.setFilter("(&(a=1)(b=2))"); +// assert r1.equals(r2); +// } +// +// @Test +// public void hashSet() throws Exception { +// Requirement r1 = rc.createRequirement("a"); +// Requirement r2 = rc.createRequirement("a"); +// +// Set set = new HashSet(); +// +// set.add(r1); +// +// assert set.contains(r1); +// assert set.contains(r2); +// +// r1.setFilter("(a=b)"); +// assert set.contains(r1); +// assert !set.contains(r2); +// +// r2.setFilter("(a=b)"); +// assert set.contains(r1); +// assert set.contains(r2); +// +// } +} diff --git a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/ResourceTest.java b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/ResourceTest.java index 4a763dfc..ea918da5 100644 --- a/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/ResourceTest.java +++ b/core/crce-metadata-impl/src/test/java/cz/zcu/kiv/crce/metadata/test/ResourceTest.java @@ -1,193 +1,193 @@ -package cz.zcu.kiv.crce.metadata.test; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.*; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; - -// TODO test of properties -// TODO test of removing entities - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ResourceTest { - - private MetadataFactory factory; - - @Before - public void before() throws Exception { - factory = new MetadataFactoryImpl(); - } - - @Test - public void testSimpleCapability() { - Resource resource = factory.createResource(); - - Capability capability = factory.createCapability("a"); - resource.addCapability(capability); - assertTrue(resource.hasCapability(capability)); - - List capabilities = resource.getCapabilities(); - assertTrue(capabilities.contains(capability)); - - capabilities = resource.getCapabilities("a"); - assertTrue(capabilities.contains(capability)); - - capabilities = resource.getCapabilities("b"); - assertFalse(capabilities.contains(capability)); - -// capabilities = resource.getRootCapabilities(); -// assertTrue(capabilities.contains(capability)); - } - - @Test - public void testChangeSimpleCapability() { - Resource resource = factory.createResource(); - - Capability capability = factory.createCapability("a"); - resource.addCapability(capability); - - capability.setAttribute("atr", String.class, "val"); - assertTrue(resource.hasCapability(capability)); - - List capabilities = resource.getCapabilities(); - assertTrue(capabilities.contains(capability)); - - capabilities = resource.getCapabilities("a"); - assertTrue(capabilities.contains(capability)); - - capabilities = resource.getCapabilities("b"); - assertFalse(capabilities.contains(capability)); - -// capabilities = resource.getRootCapabilities(); -// assertTrue(capabilities.contains(capability)); - } - - @Test - public void testCapabilitiesHierarchyByRoot() { - Resource resource = factory.createResource(); - - Capability root = factory.createCapability("a"); - - Capability child1 = factory.createCapability("a.b"); - child1.setAttribute("key", String.class, "child1"); - - Capability child2 = factory.createCapability("a.b"); - child2.setAttribute("key", String.class, "child2"); - - assertNotEquals(child1, child2); - - root.addChild(child1); - root.addChild(child2); - resource.addCapability(root); - - assertTrue(resource.hasCapability(root)); -// assertTrue(resource.hasCapability(child1)); -// assertTrue(resource.hasCapability(child2)); - - List rootCapabilities = resource.getRootCapabilities(); -// assertTrue(rootCapabilities.contains(root)); - assertFalse(rootCapabilities.contains(child1)); - assertFalse(rootCapabilities.contains(child2)); - - List capabilities = resource.getCapabilities(); - assertTrue(capabilities.contains(root)); -// assertTrue(capabilities.contains(child1)); -// assertTrue(capabilities.contains(child2)); - } - - @Test - public void testCapabilitiesHierarchyByChild() { - Resource resource = factory.createResource(); - - Capability root = factory.createCapability("a"); - - Capability child1 = factory.createCapability("a.b"); - child1.setAttribute("key", String.class, "child1"); - - Capability child2 = factory.createCapability("a.b"); - child2.setAttribute("key", String.class, "child2"); - - // checking of presence of added child is commented because of possible performance decrease - root.addChild(child1); - root.addChild(child2); - - resource.addCapability(child1); - -// assertTrue(resource.hasCapability(root)); - assertTrue(resource.hasCapability(child1)); -// assertTrue(resource.hasCapability(child2)); - - List rootCapabilities = resource.getRootCapabilities(); -// assertTrue(rootCapabilities.contains(root)); - assertFalse(rootCapabilities.contains(child1)); - assertFalse(rootCapabilities.contains(child2)); - - List capabilities = resource.getCapabilities(); -// assertTrue(capabilities.contains(root)); - assertTrue(capabilities.contains(child1)); -// assertTrue(capabilities.contains(child2)); - } - - @Test - public void testRequirement() { - Resource resource = factory.createResource(); - - Requirement req = factory.createRequirement("a"); - - resource.addRequirement(req); - assertTrue(resource.hasRequirement(req)); - - req.addAttribute("atr", String.class, "val", Operator.GREATER); - assertTrue(resource.hasRequirement(req)); - - List requirements = resource.getRequirements("a"); - assertTrue(requirements.contains(req)); - - Requirement req2 = factory.createRequirement("a"); - assertFalse(requirements.contains(req2)); - - requirements = resource.getRequirements("b"); - assertFalse(requirements.contains(req)); - } - - @Test - public void testNestedRequirementByNest() { - Resource resource = factory.createResource(); - - Requirement nest = factory.createRequirement("a"); - Requirement nested = factory.createRequirement("a"); - nest.addChild(nested); - - resource.addRequirement(nest); - - assertTrue(resource.hasRequirement(nest)); - assertFalse(resource.hasRequirement(nested)); - } - - @Test - public void testNestedRequirementByNested() { - Resource resource = factory.createResource(); - - Requirement nest = factory.createRequirement("a"); - Requirement nested = factory.createRequirement("a"); - nest.addChild(nested); - - // checking of presence of added child is commented because of possible performance decrease - - resource.addRequirement(nested); - -// assertTrue(resource.hasRequirement(nest)); -// assertFalse(resource.hasRequirement(nested)); - } -} +package cz.zcu.kiv.crce.metadata.test; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.*; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; + +// TODO test of properties +// TODO test of removing entities + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ResourceTest { + + private MetadataFactory factory; + + @Before + public void before() throws Exception { + factory = new MetadataFactoryImpl(); + } + + @Test + public void testSimpleCapability() { + Resource resource = factory.createResource(); + + Capability capability = factory.createCapability("a"); + resource.addCapability(capability); + assertTrue(resource.hasCapability(capability)); + + List capabilities = resource.getCapabilities(); + assertTrue(capabilities.contains(capability)); + + capabilities = resource.getCapabilities("a"); + assertTrue(capabilities.contains(capability)); + + capabilities = resource.getCapabilities("b"); + assertFalse(capabilities.contains(capability)); + +// capabilities = resource.getRootCapabilities(); +// assertTrue(capabilities.contains(capability)); + } + + @Test + public void testChangeSimpleCapability() { + Resource resource = factory.createResource(); + + Capability capability = factory.createCapability("a"); + resource.addCapability(capability); + + capability.setAttribute("atr", String.class, "val"); + assertTrue(resource.hasCapability(capability)); + + List capabilities = resource.getCapabilities(); + assertTrue(capabilities.contains(capability)); + + capabilities = resource.getCapabilities("a"); + assertTrue(capabilities.contains(capability)); + + capabilities = resource.getCapabilities("b"); + assertFalse(capabilities.contains(capability)); + +// capabilities = resource.getRootCapabilities(); +// assertTrue(capabilities.contains(capability)); + } + + @Test + public void testCapabilitiesHierarchyByRoot() { + Resource resource = factory.createResource(); + + Capability root = factory.createCapability("a"); + + Capability child1 = factory.createCapability("a.b"); + child1.setAttribute("key", String.class, "child1"); + + Capability child2 = factory.createCapability("a.b"); + child2.setAttribute("key", String.class, "child2"); + + assertNotEquals(child1, child2); + + root.addChild(child1); + root.addChild(child2); + resource.addCapability(root); + + assertTrue(resource.hasCapability(root)); +// assertTrue(resource.hasCapability(child1)); +// assertTrue(resource.hasCapability(child2)); + + List rootCapabilities = resource.getRootCapabilities(); +// assertTrue(rootCapabilities.contains(root)); + assertFalse(rootCapabilities.contains(child1)); + assertFalse(rootCapabilities.contains(child2)); + + List capabilities = resource.getCapabilities(); + assertTrue(capabilities.contains(root)); +// assertTrue(capabilities.contains(child1)); +// assertTrue(capabilities.contains(child2)); + } + + @Test + public void testCapabilitiesHierarchyByChild() { + Resource resource = factory.createResource(); + + Capability root = factory.createCapability("a"); + + Capability child1 = factory.createCapability("a.b"); + child1.setAttribute("key", String.class, "child1"); + + Capability child2 = factory.createCapability("a.b"); + child2.setAttribute("key", String.class, "child2"); + + // checking of presence of added child is commented because of possible performance decrease + root.addChild(child1); + root.addChild(child2); + + resource.addCapability(child1); + +// assertTrue(resource.hasCapability(root)); + assertTrue(resource.hasCapability(child1)); +// assertTrue(resource.hasCapability(child2)); + + List rootCapabilities = resource.getRootCapabilities(); +// assertTrue(rootCapabilities.contains(root)); + assertFalse(rootCapabilities.contains(child1)); + assertFalse(rootCapabilities.contains(child2)); + + List capabilities = resource.getCapabilities(); +// assertTrue(capabilities.contains(root)); + assertTrue(capabilities.contains(child1)); +// assertTrue(capabilities.contains(child2)); + } + + @Test + public void testRequirement() { + Resource resource = factory.createResource(); + + Requirement req = factory.createRequirement("a"); + + resource.addRequirement(req); + assertTrue(resource.hasRequirement(req)); + + req.addAttribute("atr", String.class, "val", Operator.GREATER); + assertTrue(resource.hasRequirement(req)); + + List requirements = resource.getRequirements("a"); + assertTrue(requirements.contains(req)); + + Requirement req2 = factory.createRequirement("a"); + assertFalse(requirements.contains(req2)); + + requirements = resource.getRequirements("b"); + assertFalse(requirements.contains(req)); + } + + @Test + public void testNestedRequirementByNest() { + Resource resource = factory.createResource(); + + Requirement nest = factory.createRequirement("a"); + Requirement nested = factory.createRequirement("a"); + nest.addChild(nested); + + resource.addRequirement(nest); + + assertTrue(resource.hasRequirement(nest)); + assertFalse(resource.hasRequirement(nested)); + } + + @Test + public void testNestedRequirementByNested() { + Resource resource = factory.createResource(); + + Requirement nest = factory.createRequirement("a"); + Requirement nested = factory.createRequirement("a"); + nest.addChild(nested); + + // checking of presence of added child is commented because of possible performance decrease + + resource.addRequirement(nested); + +// assertTrue(resource.hasRequirement(nest)); +// assertFalse(resource.hasRequirement(nested)); + } +} diff --git a/core/crce-metadata-indexer-api/osgi.bnd b/core/crce-metadata-indexer-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-metadata-indexer-api/osgi.bnd +++ b/core/crce-metadata-indexer-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-metadata-indexer-api/pom.xml b/core/crce-metadata-indexer-api/pom.xml index 3524afeb..2d0dcff1 100644 --- a/core/crce-metadata-indexer-api/pom.xml +++ b/core/crce-metadata-indexer-api/pom.xml @@ -1,58 +1,58 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-indexer-api - 2.1.1-SNAPSHOT - bundle - - CRCE - Core - Metadata Indexer API - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-indexer-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.indexer - ${namespace}.metadata.indexer - - - - - ${project.groupId} - crce-plugin-api - 2.1.0 - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-indexer-api + 2.1.1-SNAPSHOT + bundle + + CRCE - Core - Metadata Indexer API + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-indexer-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.indexer + ${namespace}.metadata.indexer + + + + + ${project.groupId} + crce-plugin-api + 2.1.0 + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/AbstractResourceIndexer.java b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/AbstractResourceIndexer.java index 843e74d3..976c3f26 100644 --- a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/AbstractResourceIndexer.java +++ b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/AbstractResourceIndexer.java @@ -1,34 +1,34 @@ -package cz.zcu.kiv.crce.metadata.indexer; - -import java.util.Collections; -import java.util.List; - -import cz.zcu.kiv.crce.plugin.AbstractPlugin; - -/** - * Abstract implementation of ResourceIndexer which can be extended - * by other implementations. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public abstract class AbstractResourceIndexer extends AbstractPlugin implements ResourceIndexer { - - @Override - public List getProvidedCategories() { - return Collections.emptyList(); - } - - @Override - public List getRequiredCategories() { - return Collections.emptyList(); - } - - @Override - public List getPluginKeywords() { - return getRequiredCategories(); - } - - @Override - public String getPluginDescription() { - return "ResourceIndexer plugin implementation"; - } -} +package cz.zcu.kiv.crce.metadata.indexer; + +import java.util.Collections; +import java.util.List; + +import cz.zcu.kiv.crce.plugin.AbstractPlugin; + +/** + * Abstract implementation of ResourceIndexer which can be extended + * by other implementations. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public abstract class AbstractResourceIndexer extends AbstractPlugin implements ResourceIndexer { + + @Override + public List getProvidedCategories() { + return Collections.emptyList(); + } + + @Override + public List getRequiredCategories() { + return Collections.emptyList(); + } + + @Override + public List getPluginKeywords() { + return getRequiredCategories(); + } + + @Override + public String getPluginDescription() { + return "ResourceIndexer plugin2 implementation"; + } +} diff --git a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexer.java b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexer.java index 5e1b251f..305cd64b 100644 --- a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexer.java +++ b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexer.java @@ -1,59 +1,59 @@ -package cz.zcu.kiv.crce.metadata.indexer; - -import java.io.InputStream; -import java.util.List; - -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.plugin.Plugin; - -/** - * Resource indexer indexes content of an artifact and stores obtained metadata - * into Resource object. - * - *

Typical usage of resource indexers is fast scan of an artifacts to - * provide information about resources like file type, provided and required - * packages and services of bundles etc. - * - *

Indexer can set up one or more categories of resource (e.g. 'jar' for JAR - * files, 'jpeg' for JPEG files etc.) which can ease the resources discovery. - * - *

Indexing process may be optimized by hierarchizing indexers in dependence - * on categories that they provides or categories that they require to index - * a resource. E.g. root indexer could set up file type (like 'jar', 'jpeg', - * 'txt'...) as category, some other indexer which requires 'jar' category could - * set up 'osgi' or 'cosi' as categories. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ResourceIndexer extends Plugin { - - /** - * Indexes data from given InputStream and stores results into - * given Resource object. Returns an array of categories set to - * resource by this indexer. - * - *

If indexer can't index artifact content, resource stays unchanged. - * - * @param input - * @param resource - * @return - */ - List index(InputStream input, Resource resource); - - /** - * Returns set of categories that this indexer can discover from an indexed - * artifact. - * @return - */ - List getProvidedCategories(); - - /** - * Returns set of categories that this indexer requires to be present in an - * indexed artifact. - * @return - */ - List getRequiredCategories(); -} +package cz.zcu.kiv.crce.metadata.indexer; + +import java.io.InputStream; +import java.util.List; + +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.plugin.Plugin; + +/** + * Resource indexer indexes content of an artifact and stores obtained metadata + * into Resource object. + * + *

Typical usage of resource indexers is fast scan of an artifacts to + * provide information about resources like file type, provided and required + * packages and services of bundles etc. + * + *

Indexer can set up one or more categories of resource (e.g. 'jar' for JAR + * files, 'jpeg' for JPEG files etc.) which can ease the resources discovery. + * + *

Indexing process may be optimized by hierarchizing indexers in dependence + * on categories that they provides or categories that they require to index + * a resource. E.g. root indexer could set up file type (like 'jar', 'jpeg', + * 'txt'...) as category, some other indexer which requires 'jar' category could + * set up 'osgi' or 'cosi' as categories. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ResourceIndexer extends Plugin { + + /** + * Indexes data from given InputStream and stores results into + * given Resource object. Returns an array of categories set to + * resource by this indexer. + * + *

If indexer can't index artifact content, resource stays unchanged. + * + * @param input + * @param resource + * @return + */ + List index(InputStream input, Resource resource); + + /** + * Returns set of categories that this indexer can discover from an indexed + * artifact. + * @return + */ + List getProvidedCategories(); + + /** + * Returns set of categories that this indexer requires to be present in an + * indexed artifact. + * @return + */ + List getRequiredCategories(); +} diff --git a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexerService.java b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexerService.java index 34c32698..88e212af 100644 --- a/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexerService.java +++ b/core/crce-metadata-indexer-api/src/main/java/cz/zcu/kiv/crce/metadata/indexer/ResourceIndexerService.java @@ -1,29 +1,29 @@ -package cz.zcu.kiv.crce.metadata.indexer; - -import java.io.File; -import java.io.IOException; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * Service for indexing of resources metadata. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ResourceIndexerService { - - /** - * Indexes the given resource file and returns {@code Resource} - * containing found metadata. - * - * @param resource Resource file to be indexed. - * @return Metadata resource. - * @throws IOException If indexing fails on I/O error. - */ - @Nonnull - Resource indexResource(File resource) throws IOException; -} +package cz.zcu.kiv.crce.metadata.indexer; + +import java.io.File; +import java.io.IOException; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * Service for indexing of resources metadata. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ResourceIndexerService { + + /** + * Indexes the given resource file and returns {@code Resource} + * containing found metadata. + * + * @param resource Resource file to be indexed. + * @return Metadata resource. + * @throws IOException If indexing fails on I/O error. + */ + @Nonnull + Resource indexResource(File resource) throws IOException; +} diff --git a/core/crce-metadata-indexer-impl/osgi.bnd b/core/crce-metadata-indexer-impl/osgi.bnd index ed49a253..874da744 100644 --- a/core/crce-metadata-indexer-impl/osgi.bnd +++ b/core/crce-metadata-indexer-impl/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator diff --git a/core/crce-metadata-indexer-impl/pom.xml b/core/crce-metadata-indexer-impl/pom.xml index 4e115979..3a3032f5 100644 --- a/core/crce-metadata-indexer-impl/pom.xml +++ b/core/crce-metadata-indexer-impl/pom.xml @@ -1,68 +1,68 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-indexer-impl - 2.1.1-SNAPSHOT - bundle - - CRCE - Core - Metadata Indexer Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-indexer - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.indexer.service - ${namespace}.metadata.indexer - - - - - ${project.groupId} - crce-plugin-api - 2.1.0 - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-service-api - 3.0.0 - - - ${project.groupId} - crce-metadata-indexer-api - 2.1.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-indexer-impl + 2.1.1-SNAPSHOT + bundle + + CRCE - Core - Metadata Indexer Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-indexer + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.indexer.service + ${namespace}.metadata.indexer + + + + + ${project.groupId} + crce-plugin-api + 2.1.0 + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-service-api + 3.0.0 + + + ${project.groupId} + crce-metadata-indexer-api + 2.1.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/Activator.java b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/Activator.java index c998103d..34943c37 100644 --- a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/Activator.java +++ b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/Activator.java @@ -1,42 +1,42 @@ -package cz.zcu.kiv.crce.metadata.indexer.internal; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexer; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.plugin.PluginManager; - -/** - * Activator of this bundle. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase { - - @Override - public void init(BundleContext context, final DependencyManager manager) throws Exception { - manager.add(createComponent() - .setInterface(ResourceIndexerService.class.getName(), null) - .setImplementation(ResourceIndexerServiceImpl.class) - .add(createServiceDependency().setRequired(true).setService(PluginManager.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) - .add(createServiceDependency().setRequired(false).setCallbacks("add", "remove").setService(ResourceIndexer.class)) - ); - - manager.add(createComponent() - .setInterface(Plugin.class.getName(), null) - .setImplementation(FileTypeResourceIndexer.class) - .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) - ); - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - - } - -} +package cz.zcu.kiv.crce.metadata.indexer.internal; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexer; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.plugin.PluginManager; + +/** + * Activator of this bundle. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase { + + @Override + public void init(BundleContext context, final DependencyManager manager) throws Exception { + manager.add(createComponent() + .setInterface(ResourceIndexerService.class.getName(), null) + .setImplementation(ResourceIndexerServiceImpl.class) + .add(createServiceDependency().setRequired(true).setService(PluginManager.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) + .add(createServiceDependency().setRequired(false).setCallbacks("add", "remove").setService(ResourceIndexer.class)) + ); + + manager.add(createComponent() + .setInterface(Plugin.class.getName(), null) + .setImplementation(FileTypeResourceIndexer.class) + .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) + ); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + + } + +} diff --git a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/FileTypeResourceIndexer.java b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/FileTypeResourceIndexer.java index f422c238..bd21959c 100644 --- a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/FileTypeResourceIndexer.java +++ b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/FileTypeResourceIndexer.java @@ -1,94 +1,94 @@ -package cz.zcu.kiv.crce.metadata.indexer.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * A samle implementation of ResourceIndexer which can determine - * a file type. It supports ZIP, PNG and JPG files. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class FileTypeResourceIndexer extends AbstractResourceIndexer { - - private static final int BUFFER_LENGTH = 8; - - private static final byte[] PNG = new byte[] {(byte) 0x89, (byte) 0x50, (byte) 0x4E, (byte) 0x47, - (byte) 0x0D, (byte) 0x0A, (byte) 0x1A, (byte) 0x0A}; - private static final byte[] JPEG = new byte[] {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}; - private static final byte[] ZIP = new byte[] {(byte) 0x50, (byte) 0x4B, (byte) 0x03, (byte) 0x04}; - - private static final Logger logger = LoggerFactory.getLogger(FileTypeResourceIndexer.class); - - private volatile MetadataService metadataService; - - @Override - public List index(InputStream input, Resource resource) { - byte[] buffer = new byte[BUFFER_LENGTH]; - - int read; - try { - read = input.read(buffer); - input.close(); // TODO close input stream by its creator. - } catch (IOException e) { - logger.error("Could not index resource.", e); - return Collections.emptyList(); - } - - if (read != BUFFER_LENGTH) { - return Collections.emptyList(); - } - - if (startsWith(buffer, ZIP)) { - metadataService.addCategory(resource, "zip"); - return Collections.singletonList("zip"); - } else if (startsWith(buffer, JPEG)) { - metadataService.addCategory(resource, "jpeg"); - return Collections.singletonList("jpeg"); - } else if (startsWith(buffer, PNG)) { - metadataService.addCategory(resource, "png"); - return Collections.singletonList("png"); - } - - return Collections.emptyList(); - } - - public static byte[] hexStringToByteArray(String s) { - int len = s.length(); - byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) (Character.digit(s.charAt(i), 16) << 4 - + Character.digit(s.charAt(i + 1), 16)); - } - return data; - } - - @Override - public List getProvidedCategories() { - List result = new ArrayList<>(); - Collections.addAll(result, "zip", "jpeg", "png"); - return result; - } - - private boolean startsWith(byte[] source, byte[] match) { - if (match.length > source.length) { - return false; - } - - for (int i = 0; i < match.length; i++) { - if (source[i] != match[i]) { - return false; - } - } - return true; - } -} +package cz.zcu.kiv.crce.metadata.indexer.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * A samle implementation of ResourceIndexer which can determine + * a file type. It supports ZIP, PNG and JPG files. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class FileTypeResourceIndexer extends AbstractResourceIndexer { + + private static final int BUFFER_LENGTH = 8; + + private static final byte[] PNG = new byte[] {(byte) 0x89, (byte) 0x50, (byte) 0x4E, (byte) 0x47, + (byte) 0x0D, (byte) 0x0A, (byte) 0x1A, (byte) 0x0A}; + private static final byte[] JPEG = new byte[] {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}; + private static final byte[] ZIP = new byte[] {(byte) 0x50, (byte) 0x4B, (byte) 0x03, (byte) 0x04}; + + private static final Logger logger = LoggerFactory.getLogger(FileTypeResourceIndexer.class); + + private volatile MetadataService metadataService; + + @Override + public List index(InputStream input, Resource resource) { + byte[] buffer = new byte[BUFFER_LENGTH]; + + int read; + try { + read = input.read(buffer); + input.close(); // TODO close input stream by its creator. + } catch (IOException e) { + logger.error("Could not index resource.", e); + return Collections.emptyList(); + } + + if (read != BUFFER_LENGTH) { + return Collections.emptyList(); + } + + if (startsWith(buffer, ZIP)) { + metadataService.addCategory(resource, "zip"); + return Collections.singletonList("zip"); + } else if (startsWith(buffer, JPEG)) { + metadataService.addCategory(resource, "jpeg"); + return Collections.singletonList("jpeg"); + } else if (startsWith(buffer, PNG)) { + metadataService.addCategory(resource, "png"); + return Collections.singletonList("png"); + } + + return Collections.emptyList(); + } + + public static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) (Character.digit(s.charAt(i), 16) << 4 + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } + + @Override + public List getProvidedCategories() { + List result = new ArrayList<>(); + Collections.addAll(result, "zip", "jpeg", "png"); + return result; + } + + private boolean startsWith(byte[] source, byte[] match) { + if (match.length > source.length) { + return false; + } + + for (int i = 0; i < match.length; i++) { + if (source[i] != match[i]) { + return false; + } + } + return true; + } +} diff --git a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/ResourceIndexerServiceImpl.java b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/ResourceIndexerServiceImpl.java index 8566f435..129fdbf3 100644 --- a/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/ResourceIndexerServiceImpl.java +++ b/core/crce-metadata-indexer-impl/src/main/java/cz/zcu/kiv/crce/metadata/indexer/internal/ResourceIndexerServiceImpl.java @@ -1,76 +1,76 @@ -package cz.zcu.kiv.crce.metadata.indexer.internal; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexer; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.plugin.PluginManager; - -/** - * Implementation of ResourceDAO which provides indexing of artifacts - * with indexers to a static (read-only) metadata representation. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ResourceIndexerServiceImpl implements ResourceIndexerService { - - private static final Logger logger = LoggerFactory.getLogger(ResourceIndexerServiceImpl.class); - - private volatile PluginManager pluginManager; - private volatile MetadataFactory metadataFactory; /* injected by dependency manager */ - - @Override - public Resource indexResource(File file) throws IOException { - logger.debug("Indexing file {}", file); - - Resource resource = metadataFactory.createResource(); - - // TODO - may be optimized for remote protocols by copying resource to local file and opening local url - - Set usedKeywords = new HashSet<>(); - Set keywords = new HashSet<>(); - Set newKeywords = new HashSet<>(); - Set usedIndexers = new HashSet<>(); - - keywords.add(PluginManager.NO_KEYWORDS); - - while (!keywords.isEmpty()) { - Iterator it = keywords.iterator(); - while (it.hasNext()) { - String keyword = it.next(); - it.remove(); - if (usedKeywords.contains(keyword)) { - continue; - } - List indexers = pluginManager.getPlugins(ResourceIndexer.class, keyword); - for (ResourceIndexer indexer : indexers) { - if (usedIndexers.contains(indexer)) { - continue; - } - try (FileInputStream fis = new FileInputStream(file)) { - if (logger.isTraceEnabled()) { - logger.trace("Using indexer: {}", indexer.getPluginId()); - } - newKeywords.addAll(indexer.index(fis, resource)); - } - usedIndexers.add(indexer); - } - usedKeywords.add(keyword); - } - keywords.addAll(newKeywords); - newKeywords = new HashSet<>(); - } - - return resource; - } -} +package cz.zcu.kiv.crce.metadata.indexer.internal; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexer; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.plugin.PluginManager; + +/** + * Implementation of ResourceDAO which provides indexing of artifacts + * with indexers to a static (read-only) metadata representation. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ResourceIndexerServiceImpl implements ResourceIndexerService { + + private static final Logger logger = LoggerFactory.getLogger(ResourceIndexerServiceImpl.class); + + private volatile PluginManager pluginManager; + private volatile MetadataFactory metadataFactory; /* injected by dependency manager */ + + @Override + public Resource indexResource(File file) throws IOException { + logger.debug("Indexing file {}", file); + + Resource resource = metadataFactory.createResource(); + + // TODO - may be optimized for remote protocols by copying resource to local file and opening local url + + Set usedKeywords = new HashSet<>(); + Set keywords = new HashSet<>(); + Set newKeywords = new HashSet<>(); + Set usedIndexers = new HashSet<>(); + + keywords.add(PluginManager.NO_KEYWORDS); + + while (!keywords.isEmpty()) { + Iterator it = keywords.iterator(); + while (it.hasNext()) { + String keyword = it.next(); + it.remove(); + if (usedKeywords.contains(keyword)) { + continue; + } + List indexers = pluginManager.getPlugins(ResourceIndexer.class, keyword); + for (ResourceIndexer indexer : indexers) { + if (usedIndexers.contains(indexer)) { + continue; + } + try (FileInputStream fis = new FileInputStream(file)) { + if (logger.isTraceEnabled()) { + logger.trace("Using indexer: {}", indexer.getPluginId()); + } + newKeywords.addAll(indexer.index(fis, resource)); + } + usedIndexers.add(indexer); + } + usedKeywords.add(keyword); + } + keywords.addAll(newKeywords); + newKeywords = new HashSet<>(); + } + + return resource; + } +} diff --git a/core/crce-metadata-json-api/osgi.bnd b/core/crce-metadata-json-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-metadata-json-api/osgi.bnd +++ b/core/crce-metadata-json-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-metadata-json-api/pom.xml b/core/crce-metadata-json-api/pom.xml index 60b02a3c..a546ddef 100644 --- a/core/crce-metadata-json-api/pom.xml +++ b/core/crce-metadata-json-api/pom.xml @@ -1,53 +1,53 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1-SNAPSHOT - - - - crce-metadata-json-api - 2.1.1-SNAPSHOT - bundle - - CRCE - Core - Metadata JSON API - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-json-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.json.api - ${namespace}.metadata.json - - - - - ${project.groupId} - crce-metadata-api - 2.1.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1-SNAPSHOT + + + + crce-metadata-json-api + 2.1.1-SNAPSHOT + bundle + + CRCE - Core - Metadata JSON API + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-json-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.json.api + ${namespace}.metadata.json + + + + + ${project.groupId} + crce-metadata-api + 2.1.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-json-api/src/main/java/cz/zcu/kiv/crce/metadata/json/MetadataJsonMapper.java b/core/crce-metadata-json-api/src/main/java/cz/zcu/kiv/crce/metadata/json/MetadataJsonMapper.java index 90617f98..14452134 100644 --- a/core/crce-metadata-json-api/src/main/java/cz/zcu/kiv/crce/metadata/json/MetadataJsonMapper.java +++ b/core/crce-metadata-json-api/src/main/java/cz/zcu/kiv/crce/metadata/json/MetadataJsonMapper.java @@ -1,22 +1,22 @@ -package cz.zcu.kiv.crce.metadata.json; - -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Entity; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface MetadataJsonMapper { - - String serialize(Entity entity); - - String serialize(Entity entity, boolean prettyPrint); - - Resource deserialize(String json); - - T deserialize(String json, Class entity); -} +package cz.zcu.kiv.crce.metadata.json; + +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Entity; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface MetadataJsonMapper { + + String serialize(Entity entity); + + String serialize(Entity entity, boolean prettyPrint); + + Resource deserialize(String json); + + T deserialize(String json, Class entity); +} diff --git a/core/crce-metadata-json-impl/osgi.bnd b/core/crce-metadata-json-impl/osgi.bnd index 8247c5ee..df4ea477 100644 --- a/core/crce-metadata-json-impl/osgi.bnd +++ b/core/crce-metadata-json-impl/osgi.bnd @@ -1,4 +1,4 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + diff --git a/core/crce-metadata-json-impl/pom.xml b/core/crce-metadata-json-impl/pom.xml index ed874835..85baddf8 100644 --- a/core/crce-metadata-json-impl/pom.xml +++ b/core/crce-metadata-json-impl/pom.xml @@ -1,81 +1,81 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-json-impl - 3.0.1-SNAPSHOT - bundle - - CRCE - Core - Metadata JSON Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-json-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.json.impl - ${namespace}.metadata.json - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-json-api - 2.1.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-json-impl + 3.0.1-SNAPSHOT + bundle + + CRCE - Core - Metadata JSON Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-json-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.json.impl + ${namespace}.metadata.json + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-databind + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-json-api + 2.1.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/AttributeSerializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/AttributeSerializer.java index 2135aed0..ec912a52 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/AttributeSerializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/AttributeSerializer.java @@ -1,83 +1,83 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@SuppressWarnings("unchecked") -public class AttributeSerializer extends JsonSerializer> { - - private final MetadataJsonMapperImpl metadataJsonMapperImpl; - - public AttributeSerializer(MetadataJsonMapperImpl metadataJsonMapperImpl) { - this.metadataJsonMapperImpl = metadataJsonMapperImpl; - } - - @Override - @SuppressWarnings("unchecked") - public void serialize(Attribute attribute, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - - jgen.writeStringField(Constants.ATTRIBUTE__NAME, attribute.getAttributeType().getName()); - jgen.writeStringField(Constants.ATTRIBUTE__TYPE, attribute.getAttributeType().getType().getSimpleName()); - if (!Operator.EQUAL.equals(attribute.getOperator())) { - jgen.writeStringField(Constants.ATTRIBUTE__OPERATOR, attribute.getOperator().getValue()); - } - - if (metadataJsonMapperImpl.expandAttributes()) { - serializeAsExpanded(attribute, jgen); - } else { - serializeAsString(attribute, jgen); - } - - jgen.writeEndObject(); - } - - private void serializeAsExpanded(Attribute attribute, JsonGenerator jgen) throws IOException, JsonProcessingException { - Class type = attribute.getAttributeType().getType(); - if (String.class.equals(type)) { - jgen.writeStringField(Constants.ATTRIBUTE__VALUE, (String) attribute.getValue()); - } else if (Long.class.equals(type)) { - jgen.writeNumberField(Constants.ATTRIBUTE__VALUE, (Long) attribute.getValue()); - } else if (Double.class.equals(type)) { - jgen.writeNumberField(Constants.ATTRIBUTE__VALUE, (Double) attribute.getValue()); - } else if (Boolean.class.equals(type)) { - jgen.writeBooleanField(Constants.ATTRIBUTE__VALUE, (Boolean) attribute.getValue()); - } else if (Version.class.equals(type)) { - jgen.writeObjectFieldStart(Constants.ATTRIBUTE__VALUE); - - Version version = (Version) attribute.getValue(); - jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MAJOR, version.getMajor()); - jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MINOR, version.getMinor()); - jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MICRO, version.getMicro()); - if (version.getQualifier() != null && !version.getQualifier().trim().isEmpty()) { - jgen.writeStringField(Constants.ATTRIBUTE__VERSION_QUALIFIER, version.getQualifier()); - } - - jgen.writeEndObject(); - } else if (List.class.equals(type)) { - jgen.writeArrayFieldStart(Constants.ATTRIBUTE__VALUE); - - for (String str : (List) attribute.getValue()) { - jgen.writeString(str); - } - jgen.writeEndArray(); - } - } - - private void serializeAsString(Attribute attribute, JsonGenerator jgen) throws IOException, JsonProcessingException { - jgen.writeStringField(Constants.ATTRIBUTE__VALUE, attribute.getStringValue()); - } -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.List; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@SuppressWarnings("unchecked") +public class AttributeSerializer extends JsonSerializer> { + + private final MetadataJsonMapperImpl metadataJsonMapperImpl; + + public AttributeSerializer(MetadataJsonMapperImpl metadataJsonMapperImpl) { + this.metadataJsonMapperImpl = metadataJsonMapperImpl; + } + + @Override + @SuppressWarnings("unchecked") + public void serialize(Attribute attribute, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + + jgen.writeStringField(Constants.ATTRIBUTE__NAME, attribute.getAttributeType().getName()); + jgen.writeStringField(Constants.ATTRIBUTE__TYPE, attribute.getAttributeType().getType().getSimpleName()); + if (!Operator.EQUAL.equals(attribute.getOperator())) { + jgen.writeStringField(Constants.ATTRIBUTE__OPERATOR, attribute.getOperator().getValue()); + } + + if (metadataJsonMapperImpl.expandAttributes()) { + serializeAsExpanded(attribute, jgen); + } else { + serializeAsString(attribute, jgen); + } + + jgen.writeEndObject(); + } + + private void serializeAsExpanded(Attribute attribute, JsonGenerator jgen) throws IOException, JsonProcessingException { + Class type = attribute.getAttributeType().getType(); + if (String.class.equals(type)) { + jgen.writeStringField(Constants.ATTRIBUTE__VALUE, (String) attribute.getValue()); + } else if (Long.class.equals(type)) { + jgen.writeNumberField(Constants.ATTRIBUTE__VALUE, (Long) attribute.getValue()); + } else if (Double.class.equals(type)) { + jgen.writeNumberField(Constants.ATTRIBUTE__VALUE, (Double) attribute.getValue()); + } else if (Boolean.class.equals(type)) { + jgen.writeBooleanField(Constants.ATTRIBUTE__VALUE, (Boolean) attribute.getValue()); + } else if (Version.class.equals(type)) { + jgen.writeObjectFieldStart(Constants.ATTRIBUTE__VALUE); + + Version version = (Version) attribute.getValue(); + jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MAJOR, version.getMajor()); + jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MINOR, version.getMinor()); + jgen.writeNumberField(Constants.ATTRIBUTE__VERSION_MICRO, version.getMicro()); + if (version.getQualifier() != null && !version.getQualifier().trim().isEmpty()) { + jgen.writeStringField(Constants.ATTRIBUTE__VERSION_QUALIFIER, version.getQualifier()); + } + + jgen.writeEndObject(); + } else if (List.class.equals(type)) { + jgen.writeArrayFieldStart(Constants.ATTRIBUTE__VALUE); + + for (String str : (List) attribute.getValue()) { + jgen.writeString(str); + } + jgen.writeEndArray(); + } + } + + private void serializeAsString(Attribute attribute, JsonGenerator jgen) throws IOException, JsonProcessingException { + jgen.writeStringField(Constants.ATTRIBUTE__VALUE, attribute.getStringValue()); + } +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/CapabilitySerializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/CapabilitySerializer.java index 1b523ab2..5e81a772 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/CapabilitySerializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/CapabilitySerializer.java @@ -1,83 +1,83 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class CapabilitySerializer extends JsonSerializer { - - @Override - public void serialize(Capability capability, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - - jgen.writeStringField(Constants.CAPABILITY__ID, capability.getId()); - jgen.writeStringField(Constants.CAPABILITY__NAMESPACE, capability.getNamespace()); - - // attributes - List> attributes = capability.getAttributes(); - if (!attributes.isEmpty()) { - jgen.writeArrayFieldStart(Constants.CAPABILITY__ATTRIBUTES); - for (Attribute attribute : attributes) { - jgen.writeObject(attribute); - } - jgen.writeEndArray(); - } - - // directives - Map directives = capability.getDirectives(); - if (!directives.isEmpty()) { - jgen.writeObjectFieldStart(Constants.CAPABILITY__DIRECTIVES); - for (Entry directive : directives.entrySet()) { - jgen.writeStringField(directive.getKey(), directive.getValue()); - } - jgen.writeEndObject(); - } - - // requirements - List requirements = capability.getRequirements(); - if (!requirements.isEmpty()) { - jgen.writeArrayFieldStart(Constants.CAPABILITY__REQUIREMENTS); - for (Requirement requirement : requirements) { - jgen.writeObject(requirement); - } - jgen.writeEndArray(); - } - - // properties - List properties = capability.getProperties(); - if (!properties.isEmpty()) { - jgen.writeArrayFieldStart(Constants.CAPABILITY__PROPERTIES); - for (Property property : properties) { - jgen.writeObject(property); - } - jgen.writeEndArray(); - } - - // children - List children = capability.getChildren(); - if (!children.isEmpty()) { - jgen.writeArrayFieldStart(Constants.CAPABILITY__CHILDREN); - for (Capability child : children) { - jgen.writeObject(child); - } - jgen.writeEndArray(); - } - - jgen.writeEndObject(); - } -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class CapabilitySerializer extends JsonSerializer { + + @Override + public void serialize(Capability capability, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + + jgen.writeStringField(Constants.CAPABILITY__ID, capability.getId()); + jgen.writeStringField(Constants.CAPABILITY__NAMESPACE, capability.getNamespace()); + + // attributes + List> attributes = capability.getAttributes(); + if (!attributes.isEmpty()) { + jgen.writeArrayFieldStart(Constants.CAPABILITY__ATTRIBUTES); + for (Attribute attribute : attributes) { + jgen.writeObject(attribute); + } + jgen.writeEndArray(); + } + + // directives + Map directives = capability.getDirectives(); + if (!directives.isEmpty()) { + jgen.writeObjectFieldStart(Constants.CAPABILITY__DIRECTIVES); + for (Entry directive : directives.entrySet()) { + jgen.writeStringField(directive.getKey(), directive.getValue()); + } + jgen.writeEndObject(); + } + + // requirements + List requirements = capability.getRequirements(); + if (!requirements.isEmpty()) { + jgen.writeArrayFieldStart(Constants.CAPABILITY__REQUIREMENTS); + for (Requirement requirement : requirements) { + jgen.writeObject(requirement); + } + jgen.writeEndArray(); + } + + // properties + List properties = capability.getProperties(); + if (!properties.isEmpty()) { + jgen.writeArrayFieldStart(Constants.CAPABILITY__PROPERTIES); + for (Property property : properties) { + jgen.writeObject(property); + } + jgen.writeEndArray(); + } + + // children + List children = capability.getChildren(); + if (!children.isEmpty()) { + jgen.writeArrayFieldStart(Constants.CAPABILITY__CHILDREN); + for (Capability child : children) { + jgen.writeObject(child); + } + jgen.writeEndArray(); + } + + jgen.writeEndObject(); + } +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/Constants.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/Constants.java index f9f5e99c..217944b7 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/Constants.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/Constants.java @@ -1,43 +1,43 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Constants { - - String REPOSITORY__URI = "uri"; - - String ATTRIBUTE__NAME = "name"; - String ATTRIBUTE__TYPE = "type"; - String ATTRIBUTE__OPERATOR = "operator"; - String ATTRIBUTE__VALUE = "value"; - String ATTRIBUTE__VERSION_MAJOR = "major"; - String ATTRIBUTE__VERSION_MINOR = "minor"; - String ATTRIBUTE__VERSION_MICRO = "micro"; - String ATTRIBUTE__VERSION_QUALIFIER = "qualifier"; - - String RESOURCE__ID = "id"; - String RESOURCE__REPOSITORY = "repository"; - String RESOURCE__CAPABILITIES = "capabilities"; - String RESOURCE__REQUIREMENTS = "requirements"; - String RESOURCE__PROPERTIES = "properties"; - - String CAPABILITY__ID = "id"; - String CAPABILITY__NAMESPACE = "namespace"; - String CAPABILITY__ATTRIBUTES = "attributes"; - String CAPABILITY__DIRECTIVES = "directives"; - String CAPABILITY__REQUIREMENTS = "requirements"; - String CAPABILITY__PROPERTIES = "properties"; - String CAPABILITY__CHILDREN = "children"; - - String REQUIREMENT__ID = "id"; - String REQUIREMENT__NAMESPACE = "namespace"; - String REQUIREMENT__ATTRIBUTES = "attributes"; - String REQUIREMENT__DIRECTIVES = "directives"; - String REQUIREMENT__CHILDREN = "children"; - - String PROPERTY__ID = "id"; - String PROPERTY__NAMESPACE = "namespace"; - String PROPERTY__ATTRIBUTES = "attributes"; -} +package cz.zcu.kiv.crce.metadata.json.internal; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Constants { + + String REPOSITORY__URI = "uri"; + + String ATTRIBUTE__NAME = "name"; + String ATTRIBUTE__TYPE = "type"; + String ATTRIBUTE__OPERATOR = "operator"; + String ATTRIBUTE__VALUE = "value"; + String ATTRIBUTE__VERSION_MAJOR = "major"; + String ATTRIBUTE__VERSION_MINOR = "minor"; + String ATTRIBUTE__VERSION_MICRO = "micro"; + String ATTRIBUTE__VERSION_QUALIFIER = "qualifier"; + + String RESOURCE__ID = "id"; + String RESOURCE__REPOSITORY = "repository"; + String RESOURCE__CAPABILITIES = "capabilities"; + String RESOURCE__REQUIREMENTS = "requirements"; + String RESOURCE__PROPERTIES = "properties"; + + String CAPABILITY__ID = "id"; + String CAPABILITY__NAMESPACE = "namespace"; + String CAPABILITY__ATTRIBUTES = "attributes"; + String CAPABILITY__DIRECTIVES = "directives"; + String CAPABILITY__REQUIREMENTS = "requirements"; + String CAPABILITY__PROPERTIES = "properties"; + String CAPABILITY__CHILDREN = "children"; + + String REQUIREMENT__ID = "id"; + String REQUIREMENT__NAMESPACE = "namespace"; + String REQUIREMENT__ATTRIBUTES = "attributes"; + String REQUIREMENT__DIRECTIVES = "directives"; + String REQUIREMENT__CHILDREN = "children"; + + String PROPERTY__ID = "id"; + String PROPERTY__NAMESPACE = "namespace"; + String PROPERTY__ATTRIBUTES = "attributes"; +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataDeserializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataDeserializer.java index 6fcc84e1..28663bbe 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataDeserializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataDeserializer.java @@ -1,490 +1,490 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; - -import javax.annotation.CheckForNull; -import javax.annotation.ParametersAreNonnullByDefault; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.DirectiveProvider; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.PropertyProvider; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.type.Version; - - -@ParametersAreNonnullByDefault -public class MetadataDeserializer { - - private static final Logger logger = LoggerFactory.getLogger(MetadataDeserializer.class); - - private final MetadataFactory metadataFactory; - - public MetadataDeserializer(MetadataFactory metadataFactory) { - this.metadataFactory = metadataFactory; - } - - Resource deserializeResource(JsonParser jp, DeserializationContext ctxt) throws IOException { - return deserializeResource((JsonNode) jp.getCodec().readTree(jp)); - } - - Requirement deserializeRequirement(JsonParser jp, DeserializationContext ctxt) throws IOException { - return deserializeRequirement((JsonNode) jp.getCodec().readTree(jp), null, null, null); - } - - Capability deserializeCapability(JsonParser jp, DeserializationContext ctxt) throws IOException { - return deserializeCapability((JsonNode) jp.getCodec().readTree(jp), null, null); - } - - Property deserializeProperty(JsonParser jp, DeserializationContext ctxt) throws IOException { - return deserializeProperty((JsonNode) jp.getCodec().readTree(jp), null); - } - - private Resource deserializeResource(JsonNode root) throws IOException, JsonProcessingException { - JsonNode id = root.findValue(Constants.RESOURCE__ID); - Resource resource = id == null ? metadataFactory.createResource() : metadataFactory.createResource(id.asText()); - - Iterator> fields = root.fields(); - while (fields.hasNext()) { - Entry node = fields.next(); - switch (node.getKey()) { -// case Constants.RESOURCE__REPOSITORY: -// deserializeRepository(resource, node.getValue()); -// continue; - - case Constants.RESOURCE__CAPABILITIES: - deserializeCapabilities(resource, null, node.getValue()); - continue; - - case Constants.RESOURCE__REQUIREMENTS: - deserializeRequirements(resource, null, null, node.getValue()); - continue; - - case Constants.RESOURCE__PROPERTIES: - deserializeProperties(resource, node.getValue()); - continue; - - default: - logger.trace("Uknown field: {}, value: {}", node.getKey(), node.getValue()); - } - } - - return resource; - } - -// private void deserializeRepository(Resource resource, JsonNode root) throws IOException { -// Iterator> fields = root.fields(); -// while (fields.hasNext()) { -// Entry node = fields.next(); -// switch (node.getKey()) { -// case Constants.REPOSITORY__URI: -// Repository repository; -// try { -// repository = metadataFactory.createRepository(new URI(node.getValue().asText())); -// } catch (URISyntaxException ex) { -// throw new IOException("Invalid URI: " + node.getValue().asText(), ex); -// } -// resource.setRepository(repository); -// return; -// -// default: -// } -// } -// } - - @SuppressWarnings("unchecked") - private void deserializeCapabilities(@CheckForNull Resource resource, @CheckForNull Capability parent, JsonNode root) { - switch (root.getNodeType()) { - case NULL: - return; - - case ARRAY: { - Iterator capabilityNodes = root.elements(); - while (capabilityNodes.hasNext()) { - deserializeCapability(capabilityNodes.next(), resource, parent); - } - break; - } - - default: - logger.warn("Array of capabilities was expected: {}", root); - } - - } - - private Capability deserializeCapability(JsonNode capabilityNode, @CheckForNull Resource resource, @CheckForNull Capability parent) - throws IllegalArgumentException { - - JsonNode namespace = capabilityNode.findValue(Constants.CAPABILITY__NAMESPACE); - if (namespace == null || !namespace.isTextual()) { - throw new IllegalArgumentException("Textual namespace is mandatory for capability: " + capabilityNode); - } - JsonNode id = capabilityNode.findValue(Constants.CAPABILITY__ID); - - final Capability capability = - id == null - ? metadataFactory.createCapability(namespace.asText()) - : metadataFactory.createCapability(namespace.asText(), id.asText()); - - if (resource != null) { - resource.addCapability(capability); - } - if (parent == null) { - if (resource != null) { - resource.addRootCapability(capability); - } - } else { - parent.addChild(capability); - } - - Iterator> fields = capabilityNode.fields(); - while (fields.hasNext()) { - Entry node = fields.next(); - switch (node.getKey()) { - case Constants.CAPABILITY__ATTRIBUTES: - deserializeAttributes( - new AttributeProviderCallback() { - - @Override - @SuppressWarnings("unchecked") - public void addAttribute(AttributeType type, Object value, Operator operator) { - capability.setAttribute(type, value, operator); - } - }, - node.getValue() - ); - continue; - - case Constants.CAPABILITY__DIRECTIVES: - deserializeDirectives(capability, node.getValue()); - continue; - - case Constants.CAPABILITY__REQUIREMENTS: - deserializeRequirements(null, capability, null, node.getValue()); - continue; - - case Constants.CAPABILITY__PROPERTIES: - deserializeProperties(capability, node.getValue()); - continue; - - case Constants.CAPABILITY__CHILDREN: - deserializeCapabilities(resource, capability, node.getValue()); - continue; - - case Constants.CAPABILITY__ID: - case Constants.CAPABILITY__NAMESPACE: - continue; - - default: - logger.debug("Ignoring unknow capability subnode, key: {}, value: {}", node.getKey(), node.getValue()); - } - } - return capability; - } - - private interface AttributeProviderCallback { - - void addAttribute(AttributeType type, T value, Operator operator); - } - - @SuppressWarnings("unchecked") - private void deserializeRequirements(@CheckForNull Resource resource, @CheckForNull Capability capability, @CheckForNull Requirement parent, JsonNode root) { - switch (root.getNodeType()) { - case NULL: - return; - - case ARRAY: { - Iterator requirementNodes = root.elements(); - while (requirementNodes.hasNext()) { - JsonNode requirementNode = requirementNodes.next(); - - deserializeRequirement(requirementNode, resource, capability, parent); - } - break; - } - - default: - logger.warn("Array of capabilities was expected: {}", root); - } - } - - private Requirement deserializeRequirement(JsonNode requirementNode, @CheckForNull Resource resource, @CheckForNull Capability capability, @CheckForNull Requirement parent) - throws IllegalArgumentException { - - JsonNode namespace = requirementNode.findValue(Constants.REQUIREMENT__NAMESPACE); - if (namespace == null || !namespace.isTextual()) { - throw new IllegalArgumentException("Textual namespace is mandatory for requirement: " + requirementNode); - } - JsonNode id = requirementNode.findValue(Constants.REQUIREMENT__ID); - - final Requirement requirement = - id == null - ? metadataFactory.createRequirement(namespace.asText()) - : metadataFactory.createRequirement(namespace.asText(), id.asText()); - - if (parent == null) { - if (resource != null) { - resource.addRequirement(requirement); - } - if (capability != null) { - capability.addRequirement(requirement); - } - } else { - parent.addChild(requirement); - } - Iterator> fields = requirementNode.fields(); - while (fields.hasNext()) { - Entry node = fields.next(); - switch (node.getKey()) { - case Constants.REQUIREMENT__ATTRIBUTES: - deserializeAttributes( - new AttributeProviderCallback() { - - @Override - @SuppressWarnings("unchecked") - public void addAttribute(AttributeType type, Object value, Operator operator) { - requirement.addAttribute(type, value, operator); - } - }, - node.getValue() - ); - continue; - - case Constants.REQUIREMENT__DIRECTIVES: - deserializeDirectives(requirement, node.getValue()); - continue; - - case Constants.REQUIREMENT__CHILDREN: - deserializeRequirements(resource, capability, requirement, node.getValue()); - continue; - - case Constants.REQUIREMENT__ID: - case Constants.REQUIREMENT__NAMESPACE: - continue; - - default: - logger.debug("Ignoring unknow requirement subnode, key: {}, value: {}", node.getKey(), node.getValue()); - } - } - return requirement; - } - - @SuppressWarnings("unchecked") - private void deserializeProperties(@CheckForNull PropertyProvider parent, JsonNode root) { - switch (root.getNodeType()) { - case NULL: - return; - - case ARRAY: { - Iterator propertyNodes = root.elements(); - while (propertyNodes.hasNext()) { - JsonNode propertyNode = propertyNodes.next(); - - deserializeProperty(propertyNode, parent); - } - break; - } - - default: - logger.warn("Array of capabilities was expected: {}", root); - } - } - - private Property deserializeProperty(JsonNode propertyNode, @CheckForNull PropertyProvider parent) throws IllegalArgumentException { - JsonNode namespace = propertyNode.findValue(Constants.PROPERTY__NAMESPACE); - if (namespace == null || !namespace.isTextual()) { - throw new IllegalArgumentException("Textual namespace is mandatory for requirement: " + propertyNode); - } - JsonNode id = propertyNode.findValue(Constants.PROPERTY__ID); - - final Property property; - if (id == null) { - property = metadataFactory.createProperty(namespace.asText()); - } else { - property = metadataFactory.createProperty(namespace.asText(), id.asText()); - } - - if (parent != null) { - parent.addProperty(property); - } - - Iterator> fields = propertyNode.fields(); - while (fields.hasNext()) { - Entry node = fields.next(); - switch (node.getKey()) { - case Constants.PROPERTY__ATTRIBUTES: - deserializeAttributes( - new AttributeProviderCallback() { - - @Override - @SuppressWarnings("unchecked") - public void addAttribute(AttributeType type, Object value, Operator operator) { - property.setAttribute(type, value, operator); - } - }, - node.getValue() - ); - continue; - - case Constants.PROPERTY__ID: - case Constants.PROPERTY__NAMESPACE: - continue; - - default: - logger.debug("Ignoring unknow property subnode, key: {}, value: {}", node.getKey(), node.getValue()); - } - } - return property; - } - - private void deserializeAttributes(AttributeProviderCallback callback, JsonNode root) { - switch (root.getNodeType()) { - case NULL: - return; - - case ARRAY: { - Iterator attributeNodes = root.elements(); - while (attributeNodes.hasNext()) { - JsonNode attributeNode = attributeNodes.next(); - - JsonNode nameNode = attributeNode.findValue(Constants.ATTRIBUTE__NAME); - JsonNode typeNode = attributeNode.findValue(Constants.ATTRIBUTE__TYPE); - JsonNode valueNode = attributeNode.findValue(Constants.ATTRIBUTE__VALUE); - JsonNode operatorNode = attributeNode.findValue(Constants.ATTRIBUTE__OPERATOR); - - if (nameNode == null || !nameNode.isTextual()) { - throw new IllegalArgumentException("Textual attribute name is mandatory: " + attributeNode); - } - String name = nameNode.asText(); - - if (typeNode != null && !typeNode.isTextual()) { - throw new IllegalArgumentException("Attribute type must be textual: " + attributeNode); - } - String type = typeNode == null ? String.class.getSimpleName() : typeNode.asText(); - - if (operatorNode != null && !operatorNode.isTextual()) { - throw new IllegalArgumentException("Attribute operator must be textual: " + attributeNode); - } - Operator operator = operatorNode == null ? Operator.EQUAL : Operator.fromValue(operatorNode.asText()); - - if (valueNode == null) { - throw new IllegalArgumentException("Attribute value is mandatory: " + attributeNode); - } - - switch (type) { - default: - case "String": - case "java.lang.String": - callback.addAttribute(new SimpleAttributeType<>(name, String.class), valueNode.asText(), operator); - continue; - - case "Long": - case "java.lang.Long": - callback.addAttribute(new SimpleAttributeType<>(name, Long.class), valueNode.asLong(), operator); - continue; - - case "Double": - case "java.lang.Double": - callback.addAttribute(new SimpleAttributeType<>(name, Double.class), valueNode.asDouble(), operator); - continue; - - case "Version": - case "cz.zcu.kiv.crce.metadata.type.Version": - callback.addAttribute(new SimpleAttributeType<>(name, Version.class), deserializeVersion(valueNode), operator); - continue; - - case "List": - case "java.util.List": - callback.addAttribute(new ListAttributeType(name), deserializeList(valueNode), operator); - continue; - - case "Boolean": - callback.addAttribute(new SimpleAttributeType<>(name, Boolean.class), valueNode.asBoolean(), operator); - continue; - - case "URI": - case "java.net.URI": - try { - callback.addAttribute(new SimpleAttributeType<>(name, URI.class), new URI(valueNode.asText()), operator); - } catch (URISyntaxException ex) { - throw new IllegalArgumentException("Invalid URI: " + valueNode.asText(), ex); - } - } - - } - break; - } - - default: - logger.warn("Array of attributes was expected: {}", root); - } - } - - private Version deserializeVersion(JsonNode root) { - if (root.isTextual()) { - return new Version(root.asText()); - } else if (root.isObject()) { - JsonNode qualifierNode = root.findValue(Constants.ATTRIBUTE__VERSION_QUALIFIER); - return new Version( - root.findValue(Constants.ATTRIBUTE__VERSION_MAJOR).asInt(), - root.findValue(Constants.ATTRIBUTE__VERSION_MINOR).asInt(), - root.findValue(Constants.ATTRIBUTE__VERSION_MICRO).asInt(), - qualifierNode == null ? null : qualifierNode.asText()); - } - throw new IllegalArgumentException("Can't parse Version value: " + root); - } - - private List deserializeList(JsonNode root) { - if (root.isArray()) { - List result = new ArrayList<>(root.size()); - Iterator iterator = root.iterator(); - while (iterator.hasNext()) { - result.add(iterator.next().asText()); - } - return result; - } else if (!root.isObject()) { - if (root.isTextual()) { - return Arrays.asList(root.asText().split(",")); - } - return Collections.singletonList(root.asText()); - } - throw new IllegalArgumentException("Can't parse List value: " + root); - } - - - private void deserializeDirectives(DirectiveProvider directiveProvider, JsonNode root) { - if (root.isObject()) { - Iterator> fields = root.fields(); - while (fields.hasNext()) { - Entry directive = fields.next(); - JsonNode value = directive.getValue(); - if (!value.isObject() && !value.isArray()) { - directiveProvider.setDirective(directive.getKey(), value.asText()); - } - } - } - } - -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import javax.annotation.CheckForNull; +import javax.annotation.ParametersAreNonnullByDefault; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.DirectiveProvider; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.PropertyProvider; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.type.Version; + + +@ParametersAreNonnullByDefault +public class MetadataDeserializer { + + private static final Logger logger = LoggerFactory.getLogger(MetadataDeserializer.class); + + private final MetadataFactory metadataFactory; + + public MetadataDeserializer(MetadataFactory metadataFactory) { + this.metadataFactory = metadataFactory; + } + + Resource deserializeResource(JsonParser jp, DeserializationContext ctxt) throws IOException { + return deserializeResource((JsonNode) jp.getCodec().readTree(jp)); + } + + Requirement deserializeRequirement(JsonParser jp, DeserializationContext ctxt) throws IOException { + return deserializeRequirement((JsonNode) jp.getCodec().readTree(jp), null, null, null); + } + + Capability deserializeCapability(JsonParser jp, DeserializationContext ctxt) throws IOException { + return deserializeCapability((JsonNode) jp.getCodec().readTree(jp), null, null); + } + + Property deserializeProperty(JsonParser jp, DeserializationContext ctxt) throws IOException { + return deserializeProperty((JsonNode) jp.getCodec().readTree(jp), null); + } + + private Resource deserializeResource(JsonNode root) throws IOException, JsonProcessingException { + JsonNode id = root.findValue(Constants.RESOURCE__ID); + Resource resource = id == null ? metadataFactory.createResource() : metadataFactory.createResource(id.asText()); + + Iterator> fields = root.fields(); + while (fields.hasNext()) { + Entry node = fields.next(); + switch (node.getKey()) { +// case Constants.RESOURCE__REPOSITORY: +// deserializeRepository(resource, node.getValue()); +// continue; + + case Constants.RESOURCE__CAPABILITIES: + deserializeCapabilities(resource, null, node.getValue()); + continue; + + case Constants.RESOURCE__REQUIREMENTS: + deserializeRequirements(resource, null, null, node.getValue()); + continue; + + case Constants.RESOURCE__PROPERTIES: + deserializeProperties(resource, node.getValue()); + continue; + + default: + logger.trace("Uknown field: {}, value: {}", node.getKey(), node.getValue()); + } + } + + return resource; + } + +// private void deserializeRepository(Resource resource, JsonNode root) throws IOException { +// Iterator> fields = root.fields(); +// while (fields.hasNext()) { +// Entry node = fields.next(); +// switch (node.getKey()) { +// case Constants.REPOSITORY__URI: +// Repository repository; +// try { +// repository = metadataFactory.createRepository(new URI(node.getValue().asText())); +// } catch (URISyntaxException ex) { +// throw new IOException("Invalid URI: " + node.getValue().asText(), ex); +// } +// resource.setRepository(repository); +// return; +// +// default: +// } +// } +// } + + @SuppressWarnings("unchecked") + private void deserializeCapabilities(@CheckForNull Resource resource, @CheckForNull Capability parent, JsonNode root) { + switch (root.getNodeType()) { + case NULL: + return; + + case ARRAY: { + Iterator capabilityNodes = root.elements(); + while (capabilityNodes.hasNext()) { + deserializeCapability(capabilityNodes.next(), resource, parent); + } + break; + } + + default: + logger.warn("Array of capabilities was expected: {}", root); + } + + } + + private Capability deserializeCapability(JsonNode capabilityNode, @CheckForNull Resource resource, @CheckForNull Capability parent) + throws IllegalArgumentException { + + JsonNode namespace = capabilityNode.findValue(Constants.CAPABILITY__NAMESPACE); + if (namespace == null || !namespace.isTextual()) { + throw new IllegalArgumentException("Textual namespace is mandatory for capability: " + capabilityNode); + } + JsonNode id = capabilityNode.findValue(Constants.CAPABILITY__ID); + + final Capability capability = + id == null + ? metadataFactory.createCapability(namespace.asText()) + : metadataFactory.createCapability(namespace.asText(), id.asText()); + + if (resource != null) { + resource.addCapability(capability); + } + if (parent == null) { + if (resource != null) { + resource.addRootCapability(capability); + } + } else { + parent.addChild(capability); + } + + Iterator> fields = capabilityNode.fields(); + while (fields.hasNext()) { + Entry node = fields.next(); + switch (node.getKey()) { + case Constants.CAPABILITY__ATTRIBUTES: + deserializeAttributes( + new AttributeProviderCallback() { + + @Override + @SuppressWarnings("unchecked") + public void addAttribute(AttributeType type, Object value, Operator operator) { + capability.setAttribute(type, value, operator); + } + }, + node.getValue() + ); + continue; + + case Constants.CAPABILITY__DIRECTIVES: + deserializeDirectives(capability, node.getValue()); + continue; + + case Constants.CAPABILITY__REQUIREMENTS: + deserializeRequirements(null, capability, null, node.getValue()); + continue; + + case Constants.CAPABILITY__PROPERTIES: + deserializeProperties(capability, node.getValue()); + continue; + + case Constants.CAPABILITY__CHILDREN: + deserializeCapabilities(resource, capability, node.getValue()); + continue; + + case Constants.CAPABILITY__ID: + case Constants.CAPABILITY__NAMESPACE: + continue; + + default: + logger.debug("Ignoring unknow capability subnode, key: {}, value: {}", node.getKey(), node.getValue()); + } + } + return capability; + } + + private interface AttributeProviderCallback { + + void addAttribute(AttributeType type, T value, Operator operator); + } + + @SuppressWarnings("unchecked") + private void deserializeRequirements(@CheckForNull Resource resource, @CheckForNull Capability capability, @CheckForNull Requirement parent, JsonNode root) { + switch (root.getNodeType()) { + case NULL: + return; + + case ARRAY: { + Iterator requirementNodes = root.elements(); + while (requirementNodes.hasNext()) { + JsonNode requirementNode = requirementNodes.next(); + + deserializeRequirement(requirementNode, resource, capability, parent); + } + break; + } + + default: + logger.warn("Array of capabilities was expected: {}", root); + } + } + + private Requirement deserializeRequirement(JsonNode requirementNode, @CheckForNull Resource resource, @CheckForNull Capability capability, @CheckForNull Requirement parent) + throws IllegalArgumentException { + + JsonNode namespace = requirementNode.findValue(Constants.REQUIREMENT__NAMESPACE); + if (namespace == null || !namespace.isTextual()) { + throw new IllegalArgumentException("Textual namespace is mandatory for requirement: " + requirementNode); + } + JsonNode id = requirementNode.findValue(Constants.REQUIREMENT__ID); + + final Requirement requirement = + id == null + ? metadataFactory.createRequirement(namespace.asText()) + : metadataFactory.createRequirement(namespace.asText(), id.asText()); + + if (parent == null) { + if (resource != null) { + resource.addRequirement(requirement); + } + if (capability != null) { + capability.addRequirement(requirement); + } + } else { + parent.addChild(requirement); + } + Iterator> fields = requirementNode.fields(); + while (fields.hasNext()) { + Entry node = fields.next(); + switch (node.getKey()) { + case Constants.REQUIREMENT__ATTRIBUTES: + deserializeAttributes( + new AttributeProviderCallback() { + + @Override + @SuppressWarnings("unchecked") + public void addAttribute(AttributeType type, Object value, Operator operator) { + requirement.addAttribute(type, value, operator); + } + }, + node.getValue() + ); + continue; + + case Constants.REQUIREMENT__DIRECTIVES: + deserializeDirectives(requirement, node.getValue()); + continue; + + case Constants.REQUIREMENT__CHILDREN: + deserializeRequirements(resource, capability, requirement, node.getValue()); + continue; + + case Constants.REQUIREMENT__ID: + case Constants.REQUIREMENT__NAMESPACE: + continue; + + default: + logger.debug("Ignoring unknow requirement subnode, key: {}, value: {}", node.getKey(), node.getValue()); + } + } + return requirement; + } + + @SuppressWarnings("unchecked") + private void deserializeProperties(@CheckForNull PropertyProvider parent, JsonNode root) { + switch (root.getNodeType()) { + case NULL: + return; + + case ARRAY: { + Iterator propertyNodes = root.elements(); + while (propertyNodes.hasNext()) { + JsonNode propertyNode = propertyNodes.next(); + + deserializeProperty(propertyNode, parent); + } + break; + } + + default: + logger.warn("Array of capabilities was expected: {}", root); + } + } + + private Property deserializeProperty(JsonNode propertyNode, @CheckForNull PropertyProvider parent) throws IllegalArgumentException { + JsonNode namespace = propertyNode.findValue(Constants.PROPERTY__NAMESPACE); + if (namespace == null || !namespace.isTextual()) { + throw new IllegalArgumentException("Textual namespace is mandatory for requirement: " + propertyNode); + } + JsonNode id = propertyNode.findValue(Constants.PROPERTY__ID); + + final Property property; + if (id == null) { + property = metadataFactory.createProperty(namespace.asText()); + } else { + property = metadataFactory.createProperty(namespace.asText(), id.asText()); + } + + if (parent != null) { + parent.addProperty(property); + } + + Iterator> fields = propertyNode.fields(); + while (fields.hasNext()) { + Entry node = fields.next(); + switch (node.getKey()) { + case Constants.PROPERTY__ATTRIBUTES: + deserializeAttributes( + new AttributeProviderCallback() { + + @Override + @SuppressWarnings("unchecked") + public void addAttribute(AttributeType type, Object value, Operator operator) { + property.setAttribute(type, value, operator); + } + }, + node.getValue() + ); + continue; + + case Constants.PROPERTY__ID: + case Constants.PROPERTY__NAMESPACE: + continue; + + default: + logger.debug("Ignoring unknow property subnode, key: {}, value: {}", node.getKey(), node.getValue()); + } + } + return property; + } + + private void deserializeAttributes(AttributeProviderCallback callback, JsonNode root) { + switch (root.getNodeType()) { + case NULL: + return; + + case ARRAY: { + Iterator attributeNodes = root.elements(); + while (attributeNodes.hasNext()) { + JsonNode attributeNode = attributeNodes.next(); + + JsonNode nameNode = attributeNode.findValue(Constants.ATTRIBUTE__NAME); + JsonNode typeNode = attributeNode.findValue(Constants.ATTRIBUTE__TYPE); + JsonNode valueNode = attributeNode.findValue(Constants.ATTRIBUTE__VALUE); + JsonNode operatorNode = attributeNode.findValue(Constants.ATTRIBUTE__OPERATOR); + + if (nameNode == null || !nameNode.isTextual()) { + throw new IllegalArgumentException("Textual attribute name is mandatory: " + attributeNode); + } + String name = nameNode.asText(); + + if (typeNode != null && !typeNode.isTextual()) { + throw new IllegalArgumentException("Attribute type must be textual: " + attributeNode); + } + String type = typeNode == null ? String.class.getSimpleName() : typeNode.asText(); + + if (operatorNode != null && !operatorNode.isTextual()) { + throw new IllegalArgumentException("Attribute operator must be textual: " + attributeNode); + } + Operator operator = operatorNode == null ? Operator.EQUAL : Operator.fromValue(operatorNode.asText()); + + if (valueNode == null) { + throw new IllegalArgumentException("Attribute value is mandatory: " + attributeNode); + } + + switch (type) { + default: + case "String": + case "java.lang.String": + callback.addAttribute(new SimpleAttributeType<>(name, String.class), valueNode.asText(), operator); + continue; + + case "Long": + case "java.lang.Long": + callback.addAttribute(new SimpleAttributeType<>(name, Long.class), valueNode.asLong(), operator); + continue; + + case "Double": + case "java.lang.Double": + callback.addAttribute(new SimpleAttributeType<>(name, Double.class), valueNode.asDouble(), operator); + continue; + + case "Version": + case "cz.zcu.kiv.crce.metadata.type.Version": + callback.addAttribute(new SimpleAttributeType<>(name, Version.class), deserializeVersion(valueNode), operator); + continue; + + case "List": + case "java.util.List": + callback.addAttribute(new ListAttributeType(name), deserializeList(valueNode), operator); + continue; + + case "Boolean": + callback.addAttribute(new SimpleAttributeType<>(name, Boolean.class), valueNode.asBoolean(), operator); + continue; + + case "URI": + case "java.net.URI": + try { + callback.addAttribute(new SimpleAttributeType<>(name, URI.class), new URI(valueNode.asText()), operator); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid URI: " + valueNode.asText(), ex); + } + } + + } + break; + } + + default: + logger.warn("Array of attributes was expected: {}", root); + } + } + + private Version deserializeVersion(JsonNode root) { + if (root.isTextual()) { + return new Version(root.asText()); + } else if (root.isObject()) { + JsonNode qualifierNode = root.findValue(Constants.ATTRIBUTE__VERSION_QUALIFIER); + return new Version( + root.findValue(Constants.ATTRIBUTE__VERSION_MAJOR).asInt(), + root.findValue(Constants.ATTRIBUTE__VERSION_MINOR).asInt(), + root.findValue(Constants.ATTRIBUTE__VERSION_MICRO).asInt(), + qualifierNode == null ? null : qualifierNode.asText()); + } + throw new IllegalArgumentException("Can't parse Version value: " + root); + } + + private List deserializeList(JsonNode root) { + if (root.isArray()) { + List result = new ArrayList<>(root.size()); + Iterator iterator = root.iterator(); + while (iterator.hasNext()) { + result.add(iterator.next().asText()); + } + return result; + } else if (!root.isObject()) { + if (root.isTextual()) { + return Arrays.asList(root.asText().split(",")); + } + return Collections.singletonList(root.asText()); + } + throw new IllegalArgumentException("Can't parse List value: " + root); + } + + + private void deserializeDirectives(DirectiveProvider directiveProvider, JsonNode root) { + if (root.isObject()) { + Iterator> fields = root.fields(); + while (fields.hasNext()) { + Entry directive = fields.next(); + JsonNode value = directive.getValue(); + if (!value.isObject() && !value.isArray()) { + directiveProvider.setDirective(directive.getKey(), value.asText()); + } + } + } + } + +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataJsonMapperImpl.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataJsonMapperImpl.java index 68529174..bec70238 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataJsonMapperImpl.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/MetadataJsonMapperImpl.java @@ -1,143 +1,143 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.Dictionary; - -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.Init; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.module.SimpleModule; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Entity; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = {MetadataJsonMapper.class, ManagedService.class}, properties = { - @org.apache.felix.dm.annotation.api.Property(name = "service.pid", value = "cz.zcu.kiv.crce.metadata.json") -}) -public class MetadataJsonMapperImpl implements MetadataJsonMapper, ManagedService { - - private static final Logger logger = LoggerFactory.getLogger(MetadataJsonMapperImpl.class); - - public static final String CFG__JSON_PRETTY_PRINT = "json.pretty-print"; - public static final String CFG__JSON_EXPAND_ATTRIBUTE_VALUES = "json.expand-attribute-values"; - - @ServiceDependency private volatile MetadataFactory metadataFactory; - private ObjectMapper mapper; - - private boolean prettyPrint = false; - private boolean expandAttributes = false; - - @Init - @SuppressWarnings("unchecked") - final void init() { - mapper = new ObjectMapper(); - - SimpleModule module = new SimpleModule(); // "resource", new Version(1, 0, 0, null) - - module.addSerializer(Resource.class, new ResourceSerializer()); - module.addSerializer(Capability.class, new CapabilitySerializer()); - module.addSerializer(Requirement.class, new RequirementSerializer()); - module.addSerializer((Class>) (Class) Attribute.class, new AttributeSerializer(this)); - module.addSerializer((Class) (Class) Property.class, new PropertySerializer()); - - final MetadataDeserializer deserializer = new MetadataDeserializer(metadataFactory); - - module.addDeserializer(Resource.class, new JsonDeserializer() { - @Override - public Resource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return deserializer.deserializeResource(jp, ctxt); - } - }); - - module.addDeserializer(Capability.class, new JsonDeserializer() { - @Override - public Capability deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return deserializer.deserializeCapability(jp, ctxt); - } - }); - - module.addDeserializer(Requirement.class, new JsonDeserializer() { - @Override - public Requirement deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return deserializer.deserializeRequirement(jp, ctxt); - } - }); - - module.addDeserializer(Property.class, new JsonDeserializer() { - @Override - public Property deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return deserializer.deserializeProperty(jp, ctxt); - } - }); - - mapper.registerModule(module); - } - - @Override - public String serialize(Entity entity) { - return serialize(entity, prettyPrint); - } - - @Override - public String serialize(Entity entity, boolean prettyPrint) { - try { - ObjectWriter writer = prettyPrint ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer(); - return writer.writeValueAsString(entity); - } catch (JsonProcessingException ex) { - throw new IllegalStateException(ex); - } - } - - @Override - public Resource deserialize(String json) { - return deserialize(json, Resource.class); - } - - @Override - public T deserialize(String json, Class entity) { - try { - return mapper.readValue(json, entity); - } catch (IOException ex) { - throw new IllegalStateException(ex); - } - } - - @Override - public void updated(Dictionary properties) throws ConfigurationException { - if (properties != null) { - Object value = properties.get(CFG__JSON_PRETTY_PRINT); - prettyPrint = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false - - value = properties.get(CFG__JSON_EXPAND_ATTRIBUTE_VALUES); - expandAttributes = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false - - logger.info("MetadataJsonMapper configured: pretty-print={}", prettyPrint); - } - } - - boolean expandAttributes() { - return expandAttributes; - } -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.Dictionary; + +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.Init; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.module.SimpleModule; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Entity; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = {MetadataJsonMapper.class, ManagedService.class}, properties = { + @org.apache.felix.dm.annotation.api.Property(name = "service.pid", value = "cz.zcu.kiv.crce.metadata.json") +}) +public class MetadataJsonMapperImpl implements MetadataJsonMapper, ManagedService { + + private static final Logger logger = LoggerFactory.getLogger(MetadataJsonMapperImpl.class); + + public static final String CFG__JSON_PRETTY_PRINT = "json.pretty-print"; + public static final String CFG__JSON_EXPAND_ATTRIBUTE_VALUES = "json.expand-attribute-values"; + + @ServiceDependency private volatile MetadataFactory metadataFactory; + private ObjectMapper mapper; + + private boolean prettyPrint = false; + private boolean expandAttributes = false; + + @Init + @SuppressWarnings("unchecked") + final void init() { + mapper = new ObjectMapper(); + + SimpleModule module = new SimpleModule(); // "resource", new Version(1, 0, 0, null) + + module.addSerializer(Resource.class, new ResourceSerializer()); + module.addSerializer(Capability.class, new CapabilitySerializer()); + module.addSerializer(Requirement.class, new RequirementSerializer()); + module.addSerializer((Class>) (Class) Attribute.class, new AttributeSerializer(this)); + module.addSerializer((Class) (Class) Property.class, new PropertySerializer()); + + final MetadataDeserializer deserializer = new MetadataDeserializer(metadataFactory); + + module.addDeserializer(Resource.class, new JsonDeserializer() { + @Override + public Resource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + return deserializer.deserializeResource(jp, ctxt); + } + }); + + module.addDeserializer(Capability.class, new JsonDeserializer() { + @Override + public Capability deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + return deserializer.deserializeCapability(jp, ctxt); + } + }); + + module.addDeserializer(Requirement.class, new JsonDeserializer() { + @Override + public Requirement deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + return deserializer.deserializeRequirement(jp, ctxt); + } + }); + + module.addDeserializer(Property.class, new JsonDeserializer() { + @Override + public Property deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + return deserializer.deserializeProperty(jp, ctxt); + } + }); + + mapper.registerModule(module); + } + + @Override + public String serialize(Entity entity) { + return serialize(entity, prettyPrint); + } + + @Override + public String serialize(Entity entity, boolean prettyPrint) { + try { + ObjectWriter writer = prettyPrint ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer(); + return writer.writeValueAsString(entity); + } catch (JsonProcessingException ex) { + throw new IllegalStateException(ex); + } + } + + @Override + public Resource deserialize(String json) { + return deserialize(json, Resource.class); + } + + @Override + public T deserialize(String json, Class entity) { + try { + return mapper.readValue(json, entity); + } catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + @Override + public void updated(Dictionary properties) throws ConfigurationException { + if (properties != null) { + Object value = properties.get(CFG__JSON_PRETTY_PRINT); + prettyPrint = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false + + value = properties.get(CFG__JSON_EXPAND_ATTRIBUTE_VALUES); + expandAttributes = value != null && value instanceof String && Boolean.valueOf(((String) value).trim()); // default false + + logger.info("MetadataJsonMapper configured: pretty-print={}", prettyPrint); + } + } + + boolean expandAttributes() { + return expandAttributes; + } +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/PropertySerializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/PropertySerializer.java index c5f5abbe..ddc4c567 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/PropertySerializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/PropertySerializer.java @@ -1,38 +1,38 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Property; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class PropertySerializer extends JsonSerializer { - - @Override - public void serialize(Property property, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - - jgen.writeStringField(Constants.PROPERTY__ID, property.getId()); - jgen.writeStringField(Constants.PROPERTY__NAMESPACE, property.getNamespace()); - - List> attributes = property.getAttributes(); - if (!attributes.isEmpty()) { - jgen.writeArrayFieldStart(Constants.CAPABILITY__ATTRIBUTES); - for (Attribute attribute : attributes) { - jgen.writeObject(attribute); - } - jgen.writeEndArray(); - } - - jgen.writeEndObject(); - } -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.List; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Property; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class PropertySerializer extends JsonSerializer { + + @Override + public void serialize(Property property, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + + jgen.writeStringField(Constants.PROPERTY__ID, property.getId()); + jgen.writeStringField(Constants.PROPERTY__NAMESPACE, property.getNamespace()); + + List> attributes = property.getAttributes(); + if (!attributes.isEmpty()) { + jgen.writeArrayFieldStart(Constants.CAPABILITY__ATTRIBUTES); + for (Attribute attribute : attributes) { + jgen.writeObject(attribute); + } + jgen.writeEndArray(); + } + + jgen.writeEndObject(); + } +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/RequirementSerializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/RequirementSerializer.java index bfef8a04..60e506c2 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/RequirementSerializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/RequirementSerializer.java @@ -1,61 +1,61 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Requirement; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class RequirementSerializer extends JsonSerializer { - - @Override - public void serialize(Requirement requirement, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - - jgen.writeStringField(Constants.REQUIREMENT__ID, requirement.getId()); - jgen.writeStringField(Constants.REQUIREMENT__NAMESPACE, requirement.getNamespace()); - - // attributes - List> attributes = requirement.getAttributes(); - if (!attributes.isEmpty()) { - jgen.writeArrayFieldStart(Constants.REQUIREMENT__ATTRIBUTES); - for (Attribute attribute : attributes) { - jgen.writeObject(attribute); - } - jgen.writeEndArray(); - } - - // directives - Map directives = requirement.getDirectives(); - if (!directives.isEmpty()) { - jgen.writeObjectFieldStart(Constants.REQUIREMENT__DIRECTIVES); - for (Entry directive : directives.entrySet()) { - jgen.writeStringField(directive.getKey(), directive.getValue()); - } - jgen.writeEndObject(); - } - - // children - List children = requirement.getChildren(); - if (!children.isEmpty()) { - jgen.writeArrayFieldStart(Constants.REQUIREMENT__CHILDREN); - for (Requirement child : requirement.getChildren()) { - jgen.writeObject(child); - } - jgen.writeEndArray(); - } - - jgen.writeEndObject(); - } -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Requirement; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class RequirementSerializer extends JsonSerializer { + + @Override + public void serialize(Requirement requirement, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + + jgen.writeStringField(Constants.REQUIREMENT__ID, requirement.getId()); + jgen.writeStringField(Constants.REQUIREMENT__NAMESPACE, requirement.getNamespace()); + + // attributes + List> attributes = requirement.getAttributes(); + if (!attributes.isEmpty()) { + jgen.writeArrayFieldStart(Constants.REQUIREMENT__ATTRIBUTES); + for (Attribute attribute : attributes) { + jgen.writeObject(attribute); + } + jgen.writeEndArray(); + } + + // directives + Map directives = requirement.getDirectives(); + if (!directives.isEmpty()) { + jgen.writeObjectFieldStart(Constants.REQUIREMENT__DIRECTIVES); + for (Entry directive : directives.entrySet()) { + jgen.writeStringField(directive.getKey(), directive.getValue()); + } + jgen.writeEndObject(); + } + + // children + List children = requirement.getChildren(); + if (!children.isEmpty()) { + jgen.writeArrayFieldStart(Constants.REQUIREMENT__CHILDREN); + for (Requirement child : requirement.getChildren()) { + jgen.writeObject(child); + } + jgen.writeEndArray(); + } + + jgen.writeEndObject(); + } +} diff --git a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/ResourceSerializer.java b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/ResourceSerializer.java index 23066d08..b9c3d0dd 100644 --- a/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/ResourceSerializer.java +++ b/core/crce-metadata-json-impl/src/main/java/cz/zcu/kiv/crce/metadata/json/internal/ResourceSerializer.java @@ -1,62 +1,62 @@ -package cz.zcu.kiv.crce.metadata.json.internal; - -import java.io.IOException; -import java.util.List; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ResourceSerializer extends JsonSerializer { - - @Override - public void serialize(Resource resource, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - - jgen.writeStringField(Constants.RESOURCE__ID, resource.getId()); -// jgen.writeObjectField(Constants.RESOURCE__REPOSITORY, resource.getRepository()); - - // capabilities - List capabilities = resource.getRootCapabilities(); - if (!capabilities.isEmpty()) { - jgen.writeArrayFieldStart(Constants.RESOURCE__CAPABILITIES); - for (Capability capability : capabilities) { - jgen.writeObject(capability); - } - jgen.writeEndArray(); - } - - // requirements - List requirements = resource.getRequirements(); - if (!requirements.isEmpty()) { - jgen.writeArrayFieldStart(Constants.RESOURCE__REQUIREMENTS); - for (Requirement capability : requirements) { - jgen.writeObject(capability); - } - jgen.writeEndArray(); - } - - // properties - List properties = resource.getProperties(); - if (!properties.isEmpty()) { - jgen.writeArrayFieldStart(Constants.RESOURCE__PROPERTIES); - for (Property property : properties) { - jgen.writeObject(property); - } - jgen.writeEndArray(); - } - - jgen.writeEndObject(); - } - -} +package cz.zcu.kiv.crce.metadata.json.internal; + +import java.io.IOException; +import java.util.List; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ResourceSerializer extends JsonSerializer { + + @Override + public void serialize(Resource resource, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + + jgen.writeStringField(Constants.RESOURCE__ID, resource.getId()); +// jgen.writeObjectField(Constants.RESOURCE__REPOSITORY, resource.getRepository()); + + // capabilities + List capabilities = resource.getRootCapabilities(); + if (!capabilities.isEmpty()) { + jgen.writeArrayFieldStart(Constants.RESOURCE__CAPABILITIES); + for (Capability capability : capabilities) { + jgen.writeObject(capability); + } + jgen.writeEndArray(); + } + + // requirements + List requirements = resource.getRequirements(); + if (!requirements.isEmpty()) { + jgen.writeArrayFieldStart(Constants.RESOURCE__REQUIREMENTS); + for (Requirement capability : requirements) { + jgen.writeObject(capability); + } + jgen.writeEndArray(); + } + + // properties + List properties = resource.getProperties(); + if (!properties.isEmpty()) { + jgen.writeArrayFieldStart(Constants.RESOURCE__PROPERTIES); + for (Property property : properties) { + jgen.writeObject(property); + } + jgen.writeEndArray(); + } + + jgen.writeEndObject(); + } + +} diff --git a/core/crce-metadata-service-api/osgi.bnd b/core/crce-metadata-service-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-metadata-service-api/osgi.bnd +++ b/core/crce-metadata-service-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-metadata-service-api/pom.xml b/core/crce-metadata-service-api/pom.xml index 9205a403..548f823c 100644 --- a/core/crce-metadata-service-api/pom.xml +++ b/core/crce-metadata-service-api/pom.xml @@ -1,58 +1,58 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-service-api - 3.0.1-SNAPSHOT - bundle - - CRCE - Core - Metadata Service API - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-service-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.service.api - ${namespace}.metadata.service - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-service-api + 3.0.1-SNAPSHOT + bundle + + CRCE - Core - Metadata Service API + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-service-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.service.api + ${namespace}.metadata.service + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/MetadataService.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/MetadataService.java index 1dbbe3be..a483d9de 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/MetadataService.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/MetadataService.java @@ -1,130 +1,130 @@ -package cz.zcu.kiv.crce.metadata.service; - -import java.net.URI; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface MetadataService { - - @Nonnull - Capability getIdentity(Resource resource); - - @Nonnull - String getPresentationName(Resource resource); - - void setPresentationName(Resource resource, String name); - - @Nonnull - String getPresentationName(Capability capability); - - @Nonnull - String getPresentationName(Requirement requirement); - - @Nonnull - String getPresentationName(Property property); - - @Nonnull - String getPresentationName(Attribute attribute); - - @Nonnull - String getExternalId( @Nonnull Resource resource); - - void setExternalId(@Nonnull Resource resource, String externalId); - - @Nonnull - URI getUri(Resource resource); - - void setUri(Resource resource, URI uri); - - /** - * - * @param resource - * @param uri - * @throws IllegalArgumentException If the given URI syntax is not valid. - */ - void setUri(Resource resource, String uri) throws IllegalArgumentException; - - @Nonnull - String getFileName(Resource resource); - - void setFileName(Resource resource, String fileName); - - long getSize(Resource resource); - - void setSize(Resource resource, long size); - - @Nonnull - List getCategories(Resource resource); - - void addCategory(Resource resource, String category); - - void removeCategory(Resource resource, String category); - - /** - * Safely adds the given capability to the resource including capability children. - * @param resource - * @param capability - */ - void addRootCapability(Resource resource, Capability capability); - - /** - * Safely removes capability from the resource including capability children. - * @param resource - * @param capability - */ - void removeCapability(Resource resource, Capability capability); - - /** - * Safely adds the given child capability into children of the parent one including - * fixing of references to the parent resource. - * @param parent - * @param child - */ -// void addChild(Capability parent, Capability child); - - void addRequirement(Resource resource, Requirement requirement); - - void removeRequirement(Resource resource, Requirement requirement); - - /** - * Returns a capability of the given namespace which exists only as a singleton - * in scope of the given resource.

- * If the requested capability doesn't exist, then a new one is created and set as - * a root capability. - * - * @param resource - * @param namespace - * @return - */ - @Nonnull - Capability getSingletonCapability(Resource resource, String namespace); - - /** - * Creates requirement for particular resource name (crce.identity name) - * @param name desired value - * @return requirement enforcing the constraint - */ - Requirement createIdentityRequirement(String name); - - /** - * Creates requirement for particular resource name (crce.identity name) and - * version (crce.identity.version) - * @param name desired name value - * @param version desired version value - * @return requirement enforcing the constraints - */ - Requirement createIdentityRequirement(String name, String version); -} +package cz.zcu.kiv.crce.metadata.service; + +import java.net.URI; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface MetadataService { + + @Nonnull + Capability getIdentity(Resource resource); + + @Nonnull + String getPresentationName(Resource resource); + + void setPresentationName(Resource resource, String name); + + @Nonnull + String getPresentationName(Capability capability); + + @Nonnull + String getPresentationName(Requirement requirement); + + @Nonnull + String getPresentationName(Property property); + + @Nonnull + String getPresentationName(Attribute attribute); + + @Nonnull + String getExternalId( @Nonnull Resource resource); + + void setExternalId(@Nonnull Resource resource, String externalId); + + @Nonnull + URI getUri(Resource resource); + + void setUri(Resource resource, URI uri); + + /** + * + * @param resource + * @param uri + * @throws IllegalArgumentException If the given URI syntax is not valid. + */ + void setUri(Resource resource, String uri) throws IllegalArgumentException; + + @Nonnull + String getFileName(Resource resource); + + void setFileName(Resource resource, String fileName); + + long getSize(Resource resource); + + void setSize(Resource resource, long size); + + @Nonnull + List getCategories(Resource resource); + + void addCategory(Resource resource, String category); + + void removeCategory(Resource resource, String category); + + /** + * Safely adds the given capability to the resource including capability children. + * @param resource + * @param capability + */ + void addRootCapability(Resource resource, Capability capability); + + /** + * Safely removes capability from the resource including capability children. + * @param resource + * @param capability + */ + void removeCapability(Resource resource, Capability capability); + + /** + * Safely adds the given child capability into children of the parent one including + * fixing of references to the parent resource. + * @param parent + * @param child + */ +// void addChild(Capability parent, Capability child); + + void addRequirement(Resource resource, Requirement requirement); + + void removeRequirement(Resource resource, Requirement requirement); + + /** + * Returns a capability of the given namespace which exists only as a singleton + * in scope of the given resource.

+ * If the requested capability doesn't exist, then a new one is created and set as + * a root capability. + * + * @param resource + * @param namespace + * @return + */ + @Nonnull + Capability getSingletonCapability(Resource resource, String namespace); + + /** + * Creates requirement for particular resource name (crce.identity name) + * @param name desired value + * @return requirement enforcing the constraint + */ + Requirement createIdentityRequirement(String name); + + /** + * Creates requirement for particular resource name (crce.identity name) and + * version (crce.identity.version) + * @param name desired name value + * @param version desired version value + * @return requirement enforcing the constraints + */ + Requirement createIdentityRequirement(String name, String version); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/CapabilityValidationResult.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/CapabilityValidationResult.java index ad936d30..312bec2f 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/CapabilityValidationResult.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/CapabilityValidationResult.java @@ -1,27 +1,27 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Capability; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface CapabilityValidationResult extends ValidationResult { - - void setCapability(Capability capability); - - @Nullable - Capability getCapability(); - - @Nonnull - List getChildResults(); - - void addChildResult(CapabilityValidationResult result); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Capability; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface CapabilityValidationResult extends ValidationResult { + + void setCapability(Capability capability); + + @Nullable + Capability getCapability(); + + @Nonnull + List getChildResults(); + + void addChildResult(CapabilityValidationResult result); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/MetadataValidator.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/MetadataValidator.java index 1eabcd4b..453c63a4 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/MetadataValidator.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/MetadataValidator.java @@ -1,79 +1,79 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * Service for validation of metadata entities. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface MetadataValidator { - - /** - * Validates the given resource including child entities (capabilities, requirements, properties). - * - * @param resource - * @return Validation result. - */ - @Nonnull - ResourceValidationResult validate(Resource resource); - - /** - * Validates the given resource and optionally validates its child entities (capabilities, requirements, properties). - * - * @param resource - * @param includeChildren - * @return - */ - @Nonnull - ResourceValidationResult validate(Resource resource, boolean includeChildren); - - /** - * Validates the given capability including child capabilities. - * @param capability - * @return - */ - @Nonnull - CapabilityValidationResult validate(Capability capability); - - /** - * Validates the given capability and optionally validates its child capabilities. - * @param capability - * @param includeChildren - * @return - */ - @Nonnull - CapabilityValidationResult validate(Capability capability, boolean includeChildren); - - /** - * Validates the given requirement including child requirements. - * @param requirement - * @return - */ - @Nonnull - RequirementValidationResult validate(Requirement requirement); - - /** - * Validates the given requirement and optionally validates its child requirements. - * @param requirement - * @param includeChildren - * @return - */ - @Nonnull - RequirementValidationResult validate(Requirement requirement, boolean includeChildren); - - /** - * Validates the given property including child properties. - * @param property - * @return - */ - @Nonnull - PropertyValidationResult validate(Property property); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * Service for validation of metadata entities. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface MetadataValidator { + + /** + * Validates the given resource including child entities (capabilities, requirements, properties). + * + * @param resource + * @return Validation result. + */ + @Nonnull + ResourceValidationResult validate(Resource resource); + + /** + * Validates the given resource and optionally validates its child entities (capabilities, requirements, properties). + * + * @param resource + * @param includeChildren + * @return + */ + @Nonnull + ResourceValidationResult validate(Resource resource, boolean includeChildren); + + /** + * Validates the given capability including child capabilities. + * @param capability + * @return + */ + @Nonnull + CapabilityValidationResult validate(Capability capability); + + /** + * Validates the given capability and optionally validates its child capabilities. + * @param capability + * @param includeChildren + * @return + */ + @Nonnull + CapabilityValidationResult validate(Capability capability, boolean includeChildren); + + /** + * Validates the given requirement including child requirements. + * @param requirement + * @return + */ + @Nonnull + RequirementValidationResult validate(Requirement requirement); + + /** + * Validates the given requirement and optionally validates its child requirements. + * @param requirement + * @param includeChildren + * @return + */ + @Nonnull + RequirementValidationResult validate(Requirement requirement, boolean includeChildren); + + /** + * Validates the given property including child properties. + * @param property + * @return + */ + @Nonnull + PropertyValidationResult validate(Property property); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/PropertyValidationResult.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/PropertyValidationResult.java index d628010a..0e1bffa0 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/PropertyValidationResult.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/PropertyValidationResult.java @@ -1,20 +1,20 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - - -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Property; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface PropertyValidationResult extends ValidationResult { - - void setProperty(Property property); - - @Nullable - Property getProperty(); -} +package cz.zcu.kiv.crce.metadata.service.validation; + + +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Property; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface PropertyValidationResult extends ValidationResult { + + void setProperty(Property property); + + @Nullable + Property getProperty(); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/Reason.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/Reason.java index 4d7e5b94..d03948ed 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/Reason.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/Reason.java @@ -1,14 +1,14 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Reason { - - String getId(); - - ReasonType getType(); - - String getText(); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Reason { + + String getId(); + + ReasonType getType(); + + String getText(); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/RequirementValidationResult.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/RequirementValidationResult.java index ea87bf1f..6a264316 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/RequirementValidationResult.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/RequirementValidationResult.java @@ -1,27 +1,27 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Requirement; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface RequirementValidationResult extends ValidationResult { - - void setRequirement(Requirement requirement); - - @Nullable - Requirement getRequirement(); - - @Nonnull - List getChildResults(); - - void addChildResult(RequirementValidationResult result); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Requirement; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface RequirementValidationResult extends ValidationResult { + + void setRequirement(Requirement requirement); + + @Nullable + Requirement getRequirement(); + + @Nonnull + List getChildResults(); + + void addChildResult(RequirementValidationResult result); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ResourceValidationResult.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ResourceValidationResult.java index 2fa6eda0..4fbbaf44 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ResourceValidationResult.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ResourceValidationResult.java @@ -1,37 +1,37 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ResourceValidationResult extends ValidationResult { - - void setResource(Resource resource); - - @Nullable - Resource getResource(); - - @Nonnull - List getCapabilityValidationResults(); - - void addCapabilityValidationResult(CapabilityValidationResult result); - - @Nonnull - List getRequirementValidationResults(); - - void addRequirementValidationResult(RequirementValidationResult result); - - @Nonnull - List getPropertyValidationResults(); - - void addPropertyValidationResult(PropertyValidationResult result); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ResourceValidationResult extends ValidationResult { + + void setResource(Resource resource); + + @Nullable + Resource getResource(); + + @Nonnull + List getCapabilityValidationResults(); + + void addCapabilityValidationResult(CapabilityValidationResult result); + + @Nonnull + List getRequirementValidationResults(); + + void addRequirementValidationResult(RequirementValidationResult result); + + @Nonnull + List getPropertyValidationResults(); + + void addPropertyValidationResult(PropertyValidationResult result); +} diff --git a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ValidationResult.java b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ValidationResult.java index 76859786..940f4db7 100644 --- a/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ValidationResult.java +++ b/core/crce-metadata-service-api/src/main/java/cz/zcu/kiv/crce/metadata/service/validation/ValidationResult.java @@ -1,46 +1,46 @@ -package cz.zcu.kiv.crce.metadata.service.validation; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Common validation result interface. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ValidationResult { - - String getEntityId(); - - void setEntityId(String id); - - /** - * Indicates whether the whole validated content is valid.

- * Validated content can be structured in hierarchy tree. If any validated entity is not valid, - * then the whole parent structure (which the entity is child of) is not valid. - * @return true if the whole validated content is valid, false otherwise. - */ - boolean isContextValid(); - - /** - * Sets validity of the validated content. - * @param valid content validity. - */ - void setContextValid(boolean valid); - - boolean isEntityValid(); - - void setEntityValid(boolean valid); - - /** - * Returns the list of reasons why the validated content is not valid. - * @return - */ - @Nonnull - List getReasons(); - - void addReason(Reason reason); -} +package cz.zcu.kiv.crce.metadata.service.validation; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Common validation result interface. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ValidationResult { + + String getEntityId(); + + void setEntityId(String id); + + /** + * Indicates whether the whole validated content is valid.

+ * Validated content can be structured in hierarchy tree. If any validated entity is not valid, + * then the whole parent structure (which the entity is child of) is not valid. + * @return true if the whole validated content is valid, false otherwise. + */ + boolean isContextValid(); + + /** + * Sets validity of the validated content. + * @param valid content validity. + */ + void setContextValid(boolean valid); + + boolean isEntityValid(); + + void setEntityValid(boolean valid); + + /** + * Returns the list of reasons why the validated content is not valid. + * @return + */ + @Nonnull + List getReasons(); + + void addReason(Reason reason); +} diff --git a/core/crce-metadata-service-impl/osgi.bnd b/core/crce-metadata-service-impl/osgi.bnd index 8247c5ee..df4ea477 100644 --- a/core/crce-metadata-service-impl/osgi.bnd +++ b/core/crce-metadata-service-impl/osgi.bnd @@ -1,4 +1,4 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + diff --git a/core/crce-metadata-service-impl/pom.xml b/core/crce-metadata-service-impl/pom.xml index 5aca588c..c803f136 100644 --- a/core/crce-metadata-service-impl/pom.xml +++ b/core/crce-metadata-service-impl/pom.xml @@ -1,77 +1,77 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-metadata-service-impl - 3.0.1-SNAPSHOT - bundle - - CRCE - Core - Metadata Service Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-metadata-service-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.metadata.service.impl - ${namespace}.metadata.service - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-service-api - 3.0.0 - - - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-metadata-service-impl + 3.0.1-SNAPSHOT + bundle + + CRCE - Core - Metadata Service Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-metadata-service-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.metadata.service.impl + ${namespace}.metadata.service + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-service-api + 3.0.0 + + + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/MetadataServiceImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/MetadataServiceImpl.java index 1243e0f6..e953a1ab 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/MetadataServiceImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/MetadataServiceImpl.java @@ -1,370 +1,370 @@ -package cz.zcu.kiv.crce.metadata.service.internal; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nonnull; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; -import org.apache.felix.dm.annotation.api.Start; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = MetadataService.class) -public class MetadataServiceImpl implements MetadataService { - - private static final Logger logger = LoggerFactory.getLogger(MetadataServiceImpl.class); - - @ServiceDependency - private MetadataFactory metadataFactory; - - @Start - public void activate() { - logger.info("CRCE MetadataService started."); - } - - @Override - public Capability getIdentity(Resource resource) { - return getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - } - - @Override - public String getPresentationName(Resource resource) { - if (resource == null) { - throw new IllegalArgumentException("Resource is null."); - } - - String name = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); - - if (name == null || name.isEmpty()) { - logger.warn("Resource with id {} has no name specified.", resource.getId()); - name = "unknown-name:" + resource.getId(); - } - return name; - } - - @Override - public void setPresentationName(Resource resource, String name) { - getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__NAME, name); - } - - @Override - public String getExternalId(@Nonnull Resource resource) { - String id = getIdentity(resource).getAttributeValue(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID); - - if(id == null) { - id = "unknown-external-id: " + resource.getId(); - } - - return id; - } - - @Override - public void setExternalId(@Nonnull Resource resource, String externalId) { - getIdentity(resource).setAttribute(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID, externalId); - } - - @Override - public String getPresentationName(Capability capability) { - if (capability == null) { - throw new IllegalArgumentException("Capability is null."); - } - - String name = capability.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); - - if (name == null || name.isEmpty()) { - logger.warn("Capability with id {} has no name specified.", capability.getId()); - name = "unknown-name:" + capability.getId(); - } - return name; - } - - @Override - public String getPresentationName(Requirement requirement) { - if (requirement == null) { - throw new IllegalArgumentException("Requirement is null."); - } - List> attributes = requirement.getAttributes(NsCrceIdentity.ATTRIBUTE__NAME); - - String name; - if (attributes.isEmpty()) { - logger.warn("Requirement with id {} has no name specified.", requirement.getId()); - name = "unknown-name:" + requirement.getId(); - } else if (attributes.size() == 1) { - name = attributes.get(0).getAttributeType().getName(); - } else { - Set set = new HashSet<>(); - for (Attribute attribute : attributes) { - set.add(attribute.getAttributeType().getName()); - } - if (set.size() == 1) { - name = set.iterator().next(); - } else { - Iterator it = set.iterator(); - StringBuilder sb = new StringBuilder("("); - sb.append(it.next()); - while (it.hasNext()) { - sb.append(",").append(it.next()); - } - sb.append(")"); - name = sb.toString(); - } - } - - return name; - } - - @Override - public String getPresentationName(Property property) { - if (property == null) { - throw new IllegalArgumentException("Attribute is null."); - } - String name = property.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); - - if (name == null || name.isEmpty()) { - logger.warn("Capability with id {} has no name specified.", property.getId()); - name = "unknown-name:" + property.getId(); - } - return name; - } - - @Override - public String getPresentationName(Attribute attribute) { - if (attribute == null) { - throw new IllegalArgumentException("Attribute is null."); - } - return attribute.getAttributeType().getName(); - } - - @Override - public URI getUri(Resource resource) { - URI uri = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__URI); - if (uri == null) { - throw new IllegalStateException("URI is null, resource: " + resource.getId()); - } - return uri; - } - -// @Override -// public URI getRelativeUri(Resource resource) { -// URI absolute = getUri(resource); -// Repository repository = resource.getRepository(); -// if (repository != null) { -// URI repositoryUri = repository.getUri(); -// return repositoryUri.relativize(absolute); -// } -// return absolute; -// } - - @Override - public void setUri(Resource resource, URI uri) { - getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__URI, uri); - } - - @Override - public void setUri(Resource resource, String uri) throws IllegalArgumentException { - try { - setUri(resource, new URI(uri)); - } catch (URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public String getFileName(Resource resource) { - String fileName = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__FILE_NAME); - if (fileName == null) { - throw new IllegalStateException("File name attribute is null"); - } - return fileName; - } - - @Override - public void setFileName(Resource resource, String fileName) { - getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__FILE_NAME, fileName); - } - - @Override - public long getSize(Resource resource) { - Long size = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE); - if (size == null) { - throw new IllegalStateException("Size attribute is null"); // -1 would be optionally returned - } - return size; - } - - @Override - public void setSize(Resource resource, long size) { - getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__SIZE, size); - } - - @Override - public List getCategories(Resource resource) { - List categories = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); - if (categories == null) { - return Collections.emptyList(); - } - return categories; - } - - @Override - public void addCategory(Resource resource, String category) { - Capability identity = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - List categories = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); - if (categories == null) { - categories = new ArrayList<>(); - identity.setAttribute(NsCrceIdentity.ATTRIBUTE__CATEGORIES, categories); - } - if (!categories.contains(category)) { - categories.add(category); - } - } - - @Override - public void removeCategory(Resource resource, String category) { - List categories = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); - if (categories != null && !categories.isEmpty()) { - categories.remove(category); - } - } - - @Override - public void addRootCapability(Resource resource, Capability capability) { - List rootCapabilities = resource.getRootCapabilities(capability.getNamespace()); - if (!rootCapabilities.contains(capability)) { - resource.addRootCapability(capability); - } - - addCapabilityTree(resource, capability); - } - - private void addCapabilityTree(@Nonnull Resource resource, @Nonnull Capability capability) { - List capabilities = resource.getCapabilities(capability.getNamespace()); - if (!capabilities.contains(capability)) { - resource.addCapability(capability); - } - - for (Capability child : capability.getChildren()) { - addCapabilityTree(resource, child); - } - } - - @Override - public void removeCapability(Resource resource, Capability capability) { - resource.removeCapability(capability); - resource.removeRootCapability(capability); - - for (Capability child : capability.getChildren()) { - removeCapability(resource, child); - } - } - -// @Override -// public void addChild(Capability parent, Capability child) { -// if (!parent.getChildren().contains(child)) { -// parent.addChild(child); -// child.setParent(parent); -// Resource resource = parent.getResource(); -// if (resource != null) { -// addChildTree(resource, child); -// } -// } -// } - -// private void addChildTree(@Nonnull Resource resource, @Nonnull Capability capability) { -// if (!resource.getCapabilities(capability.getNamespace()).contains(capability)) { -// resource.addCapability(capability); -// } -// capability.setResource(resource); -// for (Capability child : capability.getChildren()) { -// addChildTree(resource, child); -// } -// } - - @Override - public void addRequirement(Resource resource, Requirement requirement) { - List requirements = resource.getRequirements(requirement.getNamespace()); - if (!requirements.contains(requirement)) { - resource.addRequirement(requirement); - } - - addRequirementTree(resource, requirement); - } - - private void addRequirementTree(@Nonnull Resource resource, @Nonnull Requirement requirement) { - for (Requirement child : requirement.getChildren()) { - addRequirementTree(resource, child); - } - } - - @Override - public void removeRequirement(Resource resource, Requirement requirement) { - resource.removeRequirement(requirement); - removeRequirementTree(requirement); - } - - private void removeRequirementTree(@Nonnull Requirement requirement) { - for (Requirement child : requirement.getChildren()) { - removeRequirementTree(child); - } - } - - // --- - - @Nonnull - @Override - public Capability getSingletonCapability(@Nonnull Resource resource, @Nonnull String namespace) { - List capabilities = resource.getCapabilities(namespace); - - assert capabilities.size() < 2; - - Capability capability; - if (capabilities.isEmpty()) { - capability = metadataFactory.createCapability(namespace); - resource.addCapability(capability); - resource.addRootCapability(capability); - } else { - capability = capabilities.get(0); - } - - assert capability != null; - - return capability; - } - - @Override - public Requirement createIdentityRequirement(String name) { - Requirement req = metadataFactory.createRequirement(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - req.addAttribute(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID, name); - return req; - } - - @Override - public Requirement createIdentityRequirement(String name, String version) { - Requirement req = createIdentityRequirement(name); - req.addAttribute(NsCrceIdentity.ATTRIBUTE__VERSION, new Version(version)); - return req; - } -} +package cz.zcu.kiv.crce.metadata.service.internal; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nonnull; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; +import org.apache.felix.dm.annotation.api.Start; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = MetadataService.class) +public class MetadataServiceImpl implements MetadataService { + + private static final Logger logger = LoggerFactory.getLogger(MetadataServiceImpl.class); + + @ServiceDependency + private MetadataFactory metadataFactory; + + @Start + public void activate() { + logger.info("CRCE MetadataService started."); + } + + @Override + public Capability getIdentity(Resource resource) { + return getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + } + + @Override + public String getPresentationName(Resource resource) { + if (resource == null) { + throw new IllegalArgumentException("Resource is null."); + } + + String name = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); + + if (name == null || name.isEmpty()) { + logger.warn("Resource with id {} has no name specified.", resource.getId()); + name = "unknown-name:" + resource.getId(); + } + return name; + } + + @Override + public void setPresentationName(Resource resource, String name) { + getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__NAME, name); + } + + @Override + public String getExternalId(@Nonnull Resource resource) { + String id = getIdentity(resource).getAttributeValue(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID); + + if(id == null) { + id = "unknown-external-id: " + resource.getId(); + } + + return id; + } + + @Override + public void setExternalId(@Nonnull Resource resource, String externalId) { + getIdentity(resource).setAttribute(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID, externalId); + } + + @Override + public String getPresentationName(Capability capability) { + if (capability == null) { + throw new IllegalArgumentException("Capability is null."); + } + + String name = capability.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); + + if (name == null || name.isEmpty()) { + logger.warn("Capability with id {} has no name specified.", capability.getId()); + name = "unknown-name:" + capability.getId(); + } + return name; + } + + @Override + public String getPresentationName(Requirement requirement) { + if (requirement == null) { + throw new IllegalArgumentException("Requirement is null."); + } + List> attributes = requirement.getAttributes(NsCrceIdentity.ATTRIBUTE__NAME); + + String name; + if (attributes.isEmpty()) { + logger.warn("Requirement with id {} has no name specified.", requirement.getId()); + name = "unknown-name:" + requirement.getId(); + } else if (attributes.size() == 1) { + name = attributes.get(0).getAttributeType().getName(); + } else { + Set set = new HashSet<>(); + for (Attribute attribute : attributes) { + set.add(attribute.getAttributeType().getName()); + } + if (set.size() == 1) { + name = set.iterator().next(); + } else { + Iterator it = set.iterator(); + StringBuilder sb = new StringBuilder("("); + sb.append(it.next()); + while (it.hasNext()) { + sb.append(",").append(it.next()); + } + sb.append(")"); + name = sb.toString(); + } + } + + return name; + } + + @Override + public String getPresentationName(Property property) { + if (property == null) { + throw new IllegalArgumentException("Attribute is null."); + } + String name = property.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); + + if (name == null || name.isEmpty()) { + logger.warn("Capability with id {} has no name specified.", property.getId()); + name = "unknown-name:" + property.getId(); + } + return name; + } + + @Override + public String getPresentationName(Attribute attribute) { + if (attribute == null) { + throw new IllegalArgumentException("Attribute is null."); + } + return attribute.getAttributeType().getName(); + } + + @Override + public URI getUri(Resource resource) { + URI uri = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__URI); + if (uri == null) { + throw new IllegalStateException("URI is null, resource: " + resource.getId()); + } + return uri; + } + +// @Override +// public URI getRelativeUri(Resource resource) { +// URI absolute = getUri(resource); +// Repository repository = resource.getRepository(); +// if (repository != null) { +// URI repositoryUri = repository.getUri(); +// return repositoryUri.relativize(absolute); +// } +// return absolute; +// } + + @Override + public void setUri(Resource resource, URI uri) { + getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__URI, uri); + } + + @Override + public void setUri(Resource resource, String uri) throws IllegalArgumentException { + try { + setUri(resource, new URI(uri)); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(e); + } + } + + @Override + public String getFileName(Resource resource) { + String fileName = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__FILE_NAME); + if (fileName == null) { + throw new IllegalStateException("File name attribute is null"); + } + return fileName; + } + + @Override + public void setFileName(Resource resource, String fileName) { + getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__FILE_NAME, fileName); + } + + @Override + public long getSize(Resource resource) { + Long size = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE); + if (size == null) { + throw new IllegalStateException("Size attribute is null"); // -1 would be optionally returned + } + return size; + } + + @Override + public void setSize(Resource resource, long size) { + getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).setAttribute(NsCrceIdentity.ATTRIBUTE__SIZE, size); + } + + @Override + public List getCategories(Resource resource) { + List categories = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); + if (categories == null) { + return Collections.emptyList(); + } + return categories; + } + + @Override + public void addCategory(Resource resource, String category) { + Capability identity = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + List categories = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); + if (categories == null) { + categories = new ArrayList<>(); + identity.setAttribute(NsCrceIdentity.ATTRIBUTE__CATEGORIES, categories); + } + if (!categories.contains(category)) { + categories.add(category); + } + } + + @Override + public void removeCategory(Resource resource, String category) { + List categories = getSingletonCapability(resource, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY).getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); + if (categories != null && !categories.isEmpty()) { + categories.remove(category); + } + } + + @Override + public void addRootCapability(Resource resource, Capability capability) { + List rootCapabilities = resource.getRootCapabilities(capability.getNamespace()); + if (!rootCapabilities.contains(capability)) { + resource.addRootCapability(capability); + } + + addCapabilityTree(resource, capability); + } + + private void addCapabilityTree(@Nonnull Resource resource, @Nonnull Capability capability) { + List capabilities = resource.getCapabilities(capability.getNamespace()); + if (!capabilities.contains(capability)) { + resource.addCapability(capability); + } + + for (Capability child : capability.getChildren()) { + addCapabilityTree(resource, child); + } + } + + @Override + public void removeCapability(Resource resource, Capability capability) { + resource.removeCapability(capability); + resource.removeRootCapability(capability); + + for (Capability child : capability.getChildren()) { + removeCapability(resource, child); + } + } + +// @Override +// public void addChild(Capability parent, Capability child) { +// if (!parent.getChildren().contains(child)) { +// parent.addChild(child); +// child.setParent(parent); +// Resource resource = parent.getResource(); +// if (resource != null) { +// addChildTree(resource, child); +// } +// } +// } + +// private void addChildTree(@Nonnull Resource resource, @Nonnull Capability capability) { +// if (!resource.getCapabilities(capability.getNamespace()).contains(capability)) { +// resource.addCapability(capability); +// } +// capability.setResource(resource); +// for (Capability child : capability.getChildren()) { +// addChildTree(resource, child); +// } +// } + + @Override + public void addRequirement(Resource resource, Requirement requirement) { + List requirements = resource.getRequirements(requirement.getNamespace()); + if (!requirements.contains(requirement)) { + resource.addRequirement(requirement); + } + + addRequirementTree(resource, requirement); + } + + private void addRequirementTree(@Nonnull Resource resource, @Nonnull Requirement requirement) { + for (Requirement child : requirement.getChildren()) { + addRequirementTree(resource, child); + } + } + + @Override + public void removeRequirement(Resource resource, Requirement requirement) { + resource.removeRequirement(requirement); + removeRequirementTree(requirement); + } + + private void removeRequirementTree(@Nonnull Requirement requirement) { + for (Requirement child : requirement.getChildren()) { + removeRequirementTree(child); + } + } + + // --- + + @Nonnull + @Override + public Capability getSingletonCapability(@Nonnull Resource resource, @Nonnull String namespace) { + List capabilities = resource.getCapabilities(namespace); + + assert capabilities.size() < 2; + + Capability capability; + if (capabilities.isEmpty()) { + capability = metadataFactory.createCapability(namespace); + resource.addCapability(capability); + resource.addRootCapability(capability); + } else { + capability = capabilities.get(0); + } + + assert capability != null; + + return capability; + } + + @Override + public Requirement createIdentityRequirement(String name) { + Requirement req = metadataFactory.createRequirement(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + req.addAttribute(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID, name); + return req; + } + + @Override + public Requirement createIdentityRequirement(String name, String version) { + Requirement req = createIdentityRequirement(name); + req.addAttribute(NsCrceIdentity.ATTRIBUTE__VERSION, new Version(version)); + return req; + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/AbstractValidationResult.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/AbstractValidationResult.java index 29d6a925..e1ea8e85 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/AbstractValidationResult.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/AbstractValidationResult.java @@ -1,64 +1,64 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import cz.zcu.kiv.crce.metadata.service.validation.Reason; -import cz.zcu.kiv.crce.metadata.service.validation.ValidationResult; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class AbstractValidationResult implements ValidationResult { - - protected String entityId; - protected final List reasons = new ArrayList<>(); - protected boolean contextValid = true; - protected boolean entityValid = true; - - @Override - public String getEntityId() { - return entityId; - } - - @Override - public void setEntityId(String id) { - this.entityId = id; - } - - @Override - public boolean isContextValid() { - return contextValid; - } - - public void setContextValid(boolean valid) { - this.contextValid = valid; - } - - @Override - public boolean isEntityValid() { - return entityValid; - } - - @Override - public void setEntityValid(boolean valid) { - this.entityValid = valid; - } - - @Override - public List getReasons() { - return reasons; - } - - @Override - public void addReason(@Nonnull Reason reason) { - reasons.add(reason); - } - - @Override - public String toString() { - return "AbstractValidationResult{" + "reasons=" + reasons + ", contextValid=" + contextValid + ", entityValid=" + entityValid + '}'; - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import cz.zcu.kiv.crce.metadata.service.validation.Reason; +import cz.zcu.kiv.crce.metadata.service.validation.ValidationResult; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class AbstractValidationResult implements ValidationResult { + + protected String entityId; + protected final List reasons = new ArrayList<>(); + protected boolean contextValid = true; + protected boolean entityValid = true; + + @Override + public String getEntityId() { + return entityId; + } + + @Override + public void setEntityId(String id) { + this.entityId = id; + } + + @Override + public boolean isContextValid() { + return contextValid; + } + + public void setContextValid(boolean valid) { + this.contextValid = valid; + } + + @Override + public boolean isEntityValid() { + return entityValid; + } + + @Override + public void setEntityValid(boolean valid) { + this.entityValid = valid; + } + + @Override + public List getReasons() { + return reasons; + } + + @Override + public void addReason(@Nonnull Reason reason) { + reasons.add(reason); + } + + @Override + public String toString() { + return "AbstractValidationResult{" + "reasons=" + reasons + ", contextValid=" + contextValid + ", entityValid=" + entityValid + '}'; + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/CapabilityValidationResultImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/CapabilityValidationResultImpl.java index 6e99c6c2..03f8ce3f 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/CapabilityValidationResultImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/CapabilityValidationResultImpl.java @@ -1,58 +1,58 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.Reason; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class CapabilityValidationResultImpl extends AbstractValidationResult implements CapabilityValidationResult { - - private final List childResults = new ArrayList<>(); - private Capability capability; - - @Override - public void setCapability(Capability capability) { - this.capability = capability; - } - - @Override - public Capability getCapability() { - return capability; - } - - @Override - public List getChildResults() { - return childResults; - } - - @Override - public void addChildResult(@Nonnull CapabilityValidationResult result) { - childResults.add(result); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Capability context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); - sb.append("Capability"); - if (capability != null) { - sb.append(" - ").append(capability.getNamespace()).append(" - ").append(capability.getId()); - } - sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); - for (Reason reason : getReasons()) { - sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); - } - for (CapabilityValidationResult capabilityValidationResult : childResults) { - sb.append(capabilityValidationResult.toString()); - } - return sb.toString(); - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.Reason; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class CapabilityValidationResultImpl extends AbstractValidationResult implements CapabilityValidationResult { + + private final List childResults = new ArrayList<>(); + private Capability capability; + + @Override + public void setCapability(Capability capability) { + this.capability = capability; + } + + @Override + public Capability getCapability() { + return capability; + } + + @Override + public List getChildResults() { + return childResults; + } + + @Override + public void addChildResult(@Nonnull CapabilityValidationResult result) { + childResults.add(result); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Capability context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); + sb.append("Capability"); + if (capability != null) { + sb.append(" - ").append(capability.getNamespace()).append(" - ").append(capability.getId()); + } + sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); + for (Reason reason : getReasons()) { + sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); + } + for (CapabilityValidationResult capabilityValidationResult : childResults) { + sb.append(capabilityValidationResult.toString()); + } + return sb.toString(); + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/MetadataValidatorImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/MetadataValidatorImpl.java index ba0dffc1..77428e7f 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/MetadataValidatorImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/MetadataValidatorImpl.java @@ -1,210 +1,210 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.Start; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.ReasonType; -import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = MetadataValidator.class) -public class MetadataValidatorImpl implements MetadataValidator, ManagedService { - - private static final Logger logger = LoggerFactory.getLogger(MetadataValidatorImpl.class); - - public static final String CFG__STRUCTURE_VALIDATION = "structure-validation"; - - private boolean structureValidationEnabled = true; - - @Start - public void activate() { - logger.info("CRCE Validator started."); - } - - @Override - public ResourceValidationResult validate(Resource resource) { - return validate(resource, true); - } - - @Override - public ResourceValidationResult validate(Resource resource, boolean includeChildren) { - ResourceValidationResult result = new ResourceValidationResultImpl(); - result.setResource(resource); - - if (includeChildren) { - // --- Capabilities validation --- - // Capabilities not processed in capability tree (only for structure validation) - Set remaining = null; - if (structureValidationEnabled) { - remaining = new HashSet<>(resource.getCapabilities()); - } - // Validate capability tree - List rootCapabilities = resource.getRootCapabilities(); - for (Capability capability : rootCapabilities) { - CapabilityValidationResult capabilityResult = validate(capability, resource, remaining, includeChildren); - if (!capabilityResult.isContextValid()) { - result.setContextValid(false); - } - result.addCapabilityValidationResult(capabilityResult); - } - // Validate structure of all capabilities - if (structureValidationEnabled && remaining != null && !remaining.isEmpty()) { - for (Capability capability : remaining) { - CapabilityValidationResult capabilityResult = new CapabilityValidationResultImpl(); - capabilityResult.addReason( - new ReasonImpl(ReasonType.CAPABILITY_TREE, capability.getId(), - "Capability from list of all capabilities is not in hierarchy tree.")); - capabilityResult.setContextValid(false); - capabilityResult.setEntityValid(false); - result.addCapabilityValidationResult(capabilityResult); - } - result.setContextValid(false); - } - - // --- Requirements validation --- - List requirements = resource.getRequirements(); - for (Requirement requirement : requirements) { - RequirementValidationResult requirementResult = validateRecursive(requirement, resource, includeChildren); - if (!requirementResult.isContextValid()) { - result.setContextValid(false); - } - result.addRequirementValidationResult(requirementResult); - } - // --- Properties validation --- - } - - return result; - } - - @Override - public CapabilityValidationResult validate(Capability capability) { - return validate(capability, true); - } - - @Override - public CapabilityValidationResult validate(Capability capability, boolean includeChildren) { - return validate(capability, null, null, includeChildren); - } - - @Nonnull - private CapabilityValidationResult validate(Capability capability, Resource resource, Set remaining, boolean includeChildren) { - CapabilityValidationResult result = validateRecursive(capability, resource, remaining, includeChildren); - return result; - } - - /** - * - * @param capability Validated capability. - * @param resource Parent resource. - * @param remaining Unprocessed capabilities. - * @param includeChildren - * @return - */ - @Nonnull - private CapabilityValidationResult validateRecursive( - @Nonnull Capability capability, @CheckForNull Resource resource, - @CheckForNull Set remaining, boolean includeChildren) { - - CapabilityValidationResult result = new CapabilityValidationResultImpl(); - result.setCapability(capability); - - if (structureValidationEnabled && remaining != null && !remaining.remove(capability)) { - result.addReason(new ReasonImpl(ReasonType.CAPABILITY_TREE, capability.getId(), - "Capability from hierarchy tree is not on list of all capabilities.")); - result.setContextValid(false); - result.setEntityValid(false); - } - - if (includeChildren) { - for (Capability child : capability.getChildren()) { - CapabilityValidationResult childResult = validateRecursive(child, resource, remaining, includeChildren); - if (!childResult.isContextValid()) { - result.setContextValid(false); - } - } - } - - return result; - } - - @Override - public RequirementValidationResult validate(Requirement requirement) { - RequirementValidationResult result = validateRecursive(requirement, null, true); - return result; - } - - @Override - public RequirementValidationResult validate(Requirement requirement, boolean includeChildren) { - return validateRecursive(requirement, null, includeChildren); - } - - @Nonnull - private RequirementValidationResult validateRecursive(@Nonnull Requirement requirement, @CheckForNull Resource resource, boolean includeChildren) { - - RequirementValidationResult result = new RequirementValidationResultImpl(); - result.setRequirement(requirement); - - if (includeChildren) { - for (Requirement child : requirement.getChildren()) { - RequirementValidationResult childResult = validateRecursive(child, resource, includeChildren); - if (!childResult.isContextValid()) { - result.setContextValid(false); - } - } - } - - return result; - } - - @Override - public PropertyValidationResult validate(Property property) { - PropertyValidationResult result = new PropertyValidationResultImpl(); - - result.setProperty(property); - - return result; - } - - @Override - public void updated(Dictionary properties) throws ConfigurationException { - String structureValidation = (String) properties.get(CFG__STRUCTURE_VALIDATION); - if (structureValidation != null) { - switch (structureValidation) { - case "true": - case "enabled": - structureValidationEnabled = true; - break; - - case "false": - case "disabled": - default: - structureValidationEnabled = false; - } - } - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import java.util.Dictionary; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; + +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.Start; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.ReasonType; +import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = MetadataValidator.class) +public class MetadataValidatorImpl implements MetadataValidator, ManagedService { + + private static final Logger logger = LoggerFactory.getLogger(MetadataValidatorImpl.class); + + public static final String CFG__STRUCTURE_VALIDATION = "structure-validation"; + + private boolean structureValidationEnabled = true; + + @Start + public void activate() { + logger.info("CRCE Validator started."); + } + + @Override + public ResourceValidationResult validate(Resource resource) { + return validate(resource, true); + } + + @Override + public ResourceValidationResult validate(Resource resource, boolean includeChildren) { + ResourceValidationResult result = new ResourceValidationResultImpl(); + result.setResource(resource); + + if (includeChildren) { + // --- Capabilities validation --- + // Capabilities not processed in capability tree (only for structure validation) + Set remaining = null; + if (structureValidationEnabled) { + remaining = new HashSet<>(resource.getCapabilities()); + } + // Validate capability tree + List rootCapabilities = resource.getRootCapabilities(); + for (Capability capability : rootCapabilities) { + CapabilityValidationResult capabilityResult = validate(capability, resource, remaining, includeChildren); + if (!capabilityResult.isContextValid()) { + result.setContextValid(false); + } + result.addCapabilityValidationResult(capabilityResult); + } + // Validate structure of all capabilities + if (structureValidationEnabled && remaining != null && !remaining.isEmpty()) { + for (Capability capability : remaining) { + CapabilityValidationResult capabilityResult = new CapabilityValidationResultImpl(); + capabilityResult.addReason( + new ReasonImpl(ReasonType.CAPABILITY_TREE, capability.getId(), + "Capability from list of all capabilities is not in hierarchy tree.")); + capabilityResult.setContextValid(false); + capabilityResult.setEntityValid(false); + result.addCapabilityValidationResult(capabilityResult); + } + result.setContextValid(false); + } + + // --- Requirements validation --- + List requirements = resource.getRequirements(); + for (Requirement requirement : requirements) { + RequirementValidationResult requirementResult = validateRecursive(requirement, resource, includeChildren); + if (!requirementResult.isContextValid()) { + result.setContextValid(false); + } + result.addRequirementValidationResult(requirementResult); + } + // --- Properties validation --- + } + + return result; + } + + @Override + public CapabilityValidationResult validate(Capability capability) { + return validate(capability, true); + } + + @Override + public CapabilityValidationResult validate(Capability capability, boolean includeChildren) { + return validate(capability, null, null, includeChildren); + } + + @Nonnull + private CapabilityValidationResult validate(Capability capability, Resource resource, Set remaining, boolean includeChildren) { + CapabilityValidationResult result = validateRecursive(capability, resource, remaining, includeChildren); + return result; + } + + /** + * + * @param capability Validated capability. + * @param resource Parent resource. + * @param remaining Unprocessed capabilities. + * @param includeChildren + * @return + */ + @Nonnull + private CapabilityValidationResult validateRecursive( + @Nonnull Capability capability, @CheckForNull Resource resource, + @CheckForNull Set remaining, boolean includeChildren) { + + CapabilityValidationResult result = new CapabilityValidationResultImpl(); + result.setCapability(capability); + + if (structureValidationEnabled && remaining != null && !remaining.remove(capability)) { + result.addReason(new ReasonImpl(ReasonType.CAPABILITY_TREE, capability.getId(), + "Capability from hierarchy tree is not on list of all capabilities.")); + result.setContextValid(false); + result.setEntityValid(false); + } + + if (includeChildren) { + for (Capability child : capability.getChildren()) { + CapabilityValidationResult childResult = validateRecursive(child, resource, remaining, includeChildren); + if (!childResult.isContextValid()) { + result.setContextValid(false); + } + } + } + + return result; + } + + @Override + public RequirementValidationResult validate(Requirement requirement) { + RequirementValidationResult result = validateRecursive(requirement, null, true); + return result; + } + + @Override + public RequirementValidationResult validate(Requirement requirement, boolean includeChildren) { + return validateRecursive(requirement, null, includeChildren); + } + + @Nonnull + private RequirementValidationResult validateRecursive(@Nonnull Requirement requirement, @CheckForNull Resource resource, boolean includeChildren) { + + RequirementValidationResult result = new RequirementValidationResultImpl(); + result.setRequirement(requirement); + + if (includeChildren) { + for (Requirement child : requirement.getChildren()) { + RequirementValidationResult childResult = validateRecursive(child, resource, includeChildren); + if (!childResult.isContextValid()) { + result.setContextValid(false); + } + } + } + + return result; + } + + @Override + public PropertyValidationResult validate(Property property) { + PropertyValidationResult result = new PropertyValidationResultImpl(); + + result.setProperty(property); + + return result; + } + + @Override + public void updated(Dictionary properties) throws ConfigurationException { + String structureValidation = (String) properties.get(CFG__STRUCTURE_VALIDATION); + if (structureValidation != null) { + switch (structureValidation) { + case "true": + case "enabled": + structureValidationEnabled = true; + break; + + case "false": + case "disabled": + default: + structureValidationEnabled = false; + } + } + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/PropertyValidationResultImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/PropertyValidationResultImpl.java index d3c587e8..ac5412fe 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/PropertyValidationResultImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/PropertyValidationResultImpl.java @@ -1,40 +1,40 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - - -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.Reason; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class PropertyValidationResultImpl extends AbstractValidationResult implements PropertyValidationResult { - - private Property property; - - @Override - public void setProperty(Property property) { - this.property = property; - } - - @Override - public Property getProperty() { - return property; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Property context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); - sb.append("Property"); - if (property != null) { - sb.append(" - ").append(property.getNamespace()).append(" - ").append(property.getId()); - } - sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); - for (Reason reason : getReasons()) { - sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); - } - return sb.toString(); - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + + +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.Reason; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class PropertyValidationResultImpl extends AbstractValidationResult implements PropertyValidationResult { + + private Property property; + + @Override + public void setProperty(Property property) { + this.property = property; + } + + @Override + public Property getProperty() { + return property; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Property context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); + sb.append("Property"); + if (property != null) { + sb.append(" - ").append(property.getNamespace()).append(" - ").append(property.getId()); + } + sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); + for (Reason reason : getReasons()) { + sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); + } + return sb.toString(); + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ReasonImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ReasonImpl.java index 720ba01e..f784cff7 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ReasonImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ReasonImpl.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import cz.zcu.kiv.crce.metadata.service.validation.Reason; -import cz.zcu.kiv.crce.metadata.service.validation.ReasonType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ReasonImpl implements Reason { - - private final ReasonType type; - private final String id; - private final String text; - - public ReasonImpl(ReasonType type, String id, String text) { - this.type = type; - this.id = id; - this.text = text; - } - - @Override - public ReasonType getType() { - return type; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getText() { - return text; - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import cz.zcu.kiv.crce.metadata.service.validation.Reason; +import cz.zcu.kiv.crce.metadata.service.validation.ReasonType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ReasonImpl implements Reason { + + private final ReasonType type; + private final String id; + private final String text; + + public ReasonImpl(ReasonType type, String id, String text) { + this.type = type; + this.id = id; + this.text = text; + } + + @Override + public ReasonType getType() { + return type; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getText() { + return text; + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/RequirementValidationResultImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/RequirementValidationResultImpl.java index 1987e5b2..9bb45499 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/RequirementValidationResultImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/RequirementValidationResultImpl.java @@ -1,58 +1,58 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.service.validation.Reason; -import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -class RequirementValidationResultImpl extends AbstractValidationResult implements RequirementValidationResult { - - private final List childResults = new ArrayList<>(); - private Requirement requirement; - - @Override - public Requirement getRequirement() { - return requirement; - } - - @Override - public void setRequirement(Requirement requirement) { - this.requirement = requirement; - } - - @Override - public List getChildResults() { - return childResults; - } - - @Override - public void addChildResult(@Nonnull RequirementValidationResult result) { - childResults.add(result); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Requirement context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); - sb.append("Requirement"); - if (requirement != null) { - sb.append(" - ").append(requirement.getNamespace()).append(" - ").append(requirement.getId()); - } - sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); - for (Reason reason : getReasons()) { - sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); - } - for (RequirementValidationResult requirementValidationResult : childResults) { - sb.append(requirementValidationResult.toString()); - } - return sb.toString(); - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.service.validation.Reason; +import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +class RequirementValidationResultImpl extends AbstractValidationResult implements RequirementValidationResult { + + private final List childResults = new ArrayList<>(); + private Requirement requirement; + + @Override + public Requirement getRequirement() { + return requirement; + } + + @Override + public void setRequirement(Requirement requirement) { + this.requirement = requirement; + } + + @Override + public List getChildResults() { + return childResults; + } + + @Override + public void addChildResult(@Nonnull RequirementValidationResult result) { + childResults.add(result); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Requirement context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); + sb.append("Requirement"); + if (requirement != null) { + sb.append(" - ").append(requirement.getNamespace()).append(" - ").append(requirement.getId()); + } + sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); + for (Reason reason : getReasons()) { + sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); + } + for (RequirementValidationResult requirementValidationResult : childResults) { + sb.append(requirementValidationResult.toString()); + } + return sb.toString(); + } +} diff --git a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ResourceValidationResultImpl.java b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ResourceValidationResultImpl.java index a59fd485..3ca2f737 100644 --- a/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ResourceValidationResultImpl.java +++ b/core/crce-metadata-service-impl/src/main/java/cz/zcu/kiv/crce/metadata/service/internal/validation/ResourceValidationResultImpl.java @@ -1,87 +1,87 @@ -package cz.zcu.kiv.crce.metadata.service.internal.validation; - -import java.util.ArrayList; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.Reason; -import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; -import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class ResourceValidationResultImpl extends AbstractValidationResult implements ResourceValidationResult { - - private final List capabilityValidationResults = new ArrayList<>(); - private final List requirementValidationResults = new ArrayList<>(); - private final List propertyValidationResults = new ArrayList<>(); - private Resource resource; - - @Override - public Resource getResource() { - return resource; - } - - @Override - public void setResource(Resource resource) { - this.resource = resource; - } - - @Override - public List getCapabilityValidationResults() { - return capabilityValidationResults; - } - - @Override - public void addCapabilityValidationResult(CapabilityValidationResult result) { - capabilityValidationResults.add(result); - } - - @Override - public List getRequirementValidationResults() { - return requirementValidationResults; - } - - @Override - public void addRequirementValidationResult(RequirementValidationResult result) { - requirementValidationResults.add(result); - } - - @Override - public List getPropertyValidationResults() { - return propertyValidationResults; - } - - @Override - public void addPropertyValidationResult(PropertyValidationResult result) { - propertyValidationResults.add(result); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Resource context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); - sb.append("Resource"); - if (resource != null) { - sb.append(" ").append(resource.getId()); - } - sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); - for (Reason reason : getReasons()) { - sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); - } - for (CapabilityValidationResult capabilityValidationResult : capabilityValidationResults) { - sb.append(capabilityValidationResult.toString()); - } - for (RequirementValidationResult requirementValidationResult : requirementValidationResults) { - sb.append(requirementValidationResult.toString()); - } - for (PropertyValidationResult propertyValidationResult : propertyValidationResults) { - sb.append(propertyValidationResult.toString()); - } - return sb.toString(); - } -} +package cz.zcu.kiv.crce.metadata.service.internal.validation; + +import java.util.ArrayList; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.validation.CapabilityValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.PropertyValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.Reason; +import cz.zcu.kiv.crce.metadata.service.validation.RequirementValidationResult; +import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class ResourceValidationResultImpl extends AbstractValidationResult implements ResourceValidationResult { + + private final List capabilityValidationResults = new ArrayList<>(); + private final List requirementValidationResults = new ArrayList<>(); + private final List propertyValidationResults = new ArrayList<>(); + private Resource resource; + + @Override + public Resource getResource() { + return resource; + } + + @Override + public void setResource(Resource resource) { + this.resource = resource; + } + + @Override + public List getCapabilityValidationResults() { + return capabilityValidationResults; + } + + @Override + public void addCapabilityValidationResult(CapabilityValidationResult result) { + capabilityValidationResults.add(result); + } + + @Override + public List getRequirementValidationResults() { + return requirementValidationResults; + } + + @Override + public void addRequirementValidationResult(RequirementValidationResult result) { + requirementValidationResults.add(result); + } + + @Override + public List getPropertyValidationResults() { + return propertyValidationResults; + } + + @Override + public void addPropertyValidationResult(PropertyValidationResult result) { + propertyValidationResults.add(result); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Resource context: ").append(isContextValid() ? "valid" : "invalid").append("\r\n"); + sb.append("Resource"); + if (resource != null) { + sb.append(" ").append(resource.getId()); + } + sb.append(": ").append(isEntityValid() ? "valid" : "invalid").append("\r\n"); + for (Reason reason : getReasons()) { + sb.append(" ").append(reason.getId()).append(" - ").append(reason.getType()).append(" - ").append(reason.getText()).append("\r\n"); + } + for (CapabilityValidationResult capabilityValidationResult : capabilityValidationResults) { + sb.append(capabilityValidationResult.toString()); + } + for (RequirementValidationResult requirementValidationResult : requirementValidationResults) { + sb.append(requirementValidationResult.toString()); + } + for (PropertyValidationResult propertyValidationResult : propertyValidationResults) { + sb.append(propertyValidationResult.toString()); + } + return sb.toString(); + } +} diff --git a/core/crce-plugin-api/osgi.bnd b/core/crce-plugin-api/osgi.bnd index ed49a253..874da744 100644 --- a/core/crce-plugin-api/osgi.bnd +++ b/core/crce-plugin-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator diff --git a/core/crce-plugin-api/pom.xml b/core/crce-plugin-api/pom.xml index 7a20350d..78c1dc23 100644 --- a/core/crce-plugin-api/pom.xml +++ b/core/crce-plugin-api/pom.xml @@ -1,52 +1,52 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1-SNAPSHOT - - - - crce-plugin-api - 2.1.1-SNAPSHOT - bundle - - CRCE - Core - Plugin API - - - https://github.com/ReliSA/crce/tree/master/core/crce-plugin-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.plugin - ${namespace}.plugin - - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1-SNAPSHOT + + + + crce-plugin-api + 2.1.1-SNAPSHOT + bundle + + CRCE - Core - Plugin API + + + https://github.com/ReliSA/crce/tree/master/core/crce-plugin-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.plugin + ${namespace}.plugin + + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/AbstractPlugin.java b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/AbstractPlugin.java index 5ab8b7d9..055f740e 100644 --- a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/AbstractPlugin.java +++ b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/AbstractPlugin.java @@ -1,208 +1,208 @@ -package cz.zcu.kiv.crce.plugin; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Dictionary; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.Version; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventAdmin; - -/** - * This abstract class implements all methods of Plugin interface. - * It can be extended of any plugin - it's recommended to keep unified - * behaviour of plugins. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public abstract class AbstractPlugin implements Plugin, Comparable, ManagedService { - - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") - private volatile BundleContext context; - - @SuppressWarnings("UseOfObsoleteCollectionType") - private Dictionary properties = new java.util.Hashtable<>(); - private String id = this.getClass().getName(); - private Version version = new Version("0.0.0"); - private int priority = 0; - private List keywords = Collections.emptyList(); - private String description = "Abstract plugin"; - - @Override - public String getPluginId() { - return id; - } - - @Override - public Version getPluginVersion() { - return version; - } - - @Override - public int getPluginPriority() { - return priority; - } - - @Override - public String getPluginDescription() { - return description; - } - - @Override - public List getPluginKeywords() { - return keywords; - } - - @Override - public final int compareTo(Plugin o) { - int thisVal = this.getPluginPriority(); - int anotherVal = o.getPluginPriority(); - - if (thisVal == anotherVal) { - return this.getPluginId().compareTo(o.getPluginId()); - } - - return thisVal < anotherVal ? 1 : -1; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final AbstractPlugin other = (AbstractPlugin) obj; - if (this.id == null ? other.id != null : !this.id.equals(other.id)) { - return false; - } - if (this.version.compareTo(other.version) != 0) { - return false; - } - return this.priority == other.priority; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 37 * hash + (this.id != null ? this.id.hashCode() : 0); - hash = 37 * hash + this.version.hashCode(); - hash = 37 * hash + this.priority; - return hash; - } - - @SuppressWarnings("unused") - private void init() { - if (properties.get(CFG_ID) == null) { - id = getClass().getName(); - } - if (properties.get(CFG_VERSION) == null) { - version = context.getBundle().getVersion(); - } - if (properties.get(CFG_DESCRIPTION) == null) { - description = "Implementation of: " + getClass().getName(); - } - if (properties.get(CFG_PRIORITY) == null) { - priority = 0; - } - if (properties.get(CFG_KEYWORDS) == null) { - keywords = Collections.emptyList(); - } - } - - @Override - public void updated(Dictionary properties) throws ConfigurationException { - if (properties != null) { - try { - String value; - - // configure ID - if ((value = (String) properties.get(CFG_ID)) != null) { - if ("".equals(value.trim())) { - throw new ConfigurationException(CFG_ID, "Plugin ID can not be empty", null); - } - id = value; - } - - // configure VERSION - if ((value = (String) properties.get(CFG_VERSION)) != null) { - try { - version = Version.parseVersion(value); - } catch (IllegalArgumentException e) { - throw new ConfigurationException(CFG_VERSION, "Improperly formated version", e); - } - } - - // configure PRIORITY - if ((value = (String) properties.get(CFG_PRIORITY)) != null) { - try { - priority = Integer.parseInt(value); - } catch (NumberFormatException e) { - switch (value.trim().toUpperCase()) { - case PRIORITY_MAX_VALUE: - priority = Integer.MAX_VALUE; - break; - case PRIORITY_MIN_VALUE: - priority = Integer.MIN_VALUE; - break; - default: - throw new ConfigurationException(CFG_PRIORITY, "Priority must be an integer", e); - } - } - } - - // configure KEYWORDS - if ((value = (String) properties.get(CFG_KEYWORDS)) != null) { - if ("".equals(value.trim())) { - keywords = Collections.emptyList(); - } else { - String[] split = value.split(","); - keywords = Arrays.asList(split); - } - } - - // configure DESCRIPTION - if ((value = (String) properties.get(CFG_DESCRIPTION)) != null) { - description = value; - } - - } finally { - ServiceReference ref = context.getServiceReference(EventAdmin.class); - if (ref != null) { - EventAdmin eventAdmin = context.getService(ref); - - Map props = new HashMap<>(); - - props.put(PluginManager.PROPERTY_PLUGIN_ID, id); - props.put(PluginManager.PROPERTY_PLUGIN_VERSION, version.toString()); - props.put(PluginManager.PROPERTY_PLUGIN_PRIORITY, priority); - props.put(PluginManager.PROPERTY_PLUGIN_DESCRIPTION, description); - props.put(PluginManager.PROPERTY_PLUGIN_KEYWORDS, keywords.toString()); - - Set types = new HashSet<>(); - - for (Class cl = this.getClass(); cl != Object.class; cl = cl.getSuperclass()) { - for (Class iface : cl.getInterfaces()) { - types.add(iface.getName()); - } - } - - props.put(PluginManager.PROPERTY_PLUGIN_TYPES, types.toString()); - - eventAdmin.sendEvent(new Event(PluginManager.TOPIC_PLUGIN_CONFIGURED, props)); - } - } - } - - this.properties = properties; - } -} +package cz.zcu.kiv.crce.plugin; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.Version; +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventAdmin; + +/** + * This abstract class implements all methods of Plugin interface. + * It can be extended of any plugin2 - it's recommended to keep unified + * behaviour of plugins. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public abstract class AbstractPlugin implements Plugin, Comparable, ManagedService { + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") + private volatile BundleContext context; + + @SuppressWarnings("UseOfObsoleteCollectionType") + private Dictionary properties = new java.util.Hashtable<>(); + private String id = this.getClass().getName(); + private Version version = new Version("0.0.0"); + private int priority = 0; + private List keywords = Collections.emptyList(); + private String description = "Abstract plugin2"; + + @Override + public String getPluginId() { + return id; + } + + @Override + public Version getPluginVersion() { + return version; + } + + @Override + public int getPluginPriority() { + return priority; + } + + @Override + public String getPluginDescription() { + return description; + } + + @Override + public List getPluginKeywords() { + return keywords; + } + + @Override + public final int compareTo(Plugin o) { + int thisVal = this.getPluginPriority(); + int anotherVal = o.getPluginPriority(); + + if (thisVal == anotherVal) { + return this.getPluginId().compareTo(o.getPluginId()); + } + + return thisVal < anotherVal ? 1 : -1; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AbstractPlugin other = (AbstractPlugin) obj; + if (this.id == null ? other.id != null : !this.id.equals(other.id)) { + return false; + } + if (this.version.compareTo(other.version) != 0) { + return false; + } + return this.priority == other.priority; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 37 * hash + (this.id != null ? this.id.hashCode() : 0); + hash = 37 * hash + this.version.hashCode(); + hash = 37 * hash + this.priority; + return hash; + } + + @SuppressWarnings("unused") + private void init() { + if (properties.get(CFG_ID) == null) { + id = getClass().getName(); + } + if (properties.get(CFG_VERSION) == null) { + version = context.getBundle().getVersion(); + } + if (properties.get(CFG_DESCRIPTION) == null) { + description = "Implementation of: " + getClass().getName(); + } + if (properties.get(CFG_PRIORITY) == null) { + priority = 0; + } + if (properties.get(CFG_KEYWORDS) == null) { + keywords = Collections.emptyList(); + } + } + + @Override + public void updated(Dictionary properties) throws ConfigurationException { + if (properties != null) { + try { + String value; + + // configure ID + if ((value = (String) properties.get(CFG_ID)) != null) { + if ("".equals(value.trim())) { + throw new ConfigurationException(CFG_ID, "Plugin ID can not be empty", null); + } + id = value; + } + + // configure VERSION + if ((value = (String) properties.get(CFG_VERSION)) != null) { + try { + version = Version.parseVersion(value); + } catch (IllegalArgumentException e) { + throw new ConfigurationException(CFG_VERSION, "Improperly formated version", e); + } + } + + // configure PRIORITY + if ((value = (String) properties.get(CFG_PRIORITY)) != null) { + try { + priority = Integer.parseInt(value); + } catch (NumberFormatException e) { + switch (value.trim().toUpperCase()) { + case PRIORITY_MAX_VALUE: + priority = Integer.MAX_VALUE; + break; + case PRIORITY_MIN_VALUE: + priority = Integer.MIN_VALUE; + break; + default: + throw new ConfigurationException(CFG_PRIORITY, "Priority must be an integer", e); + } + } + } + + // configure KEYWORDS + if ((value = (String) properties.get(CFG_KEYWORDS)) != null) { + if ("".equals(value.trim())) { + keywords = Collections.emptyList(); + } else { + String[] split = value.split(","); + keywords = Arrays.asList(split); + } + } + + // configure DESCRIPTION + if ((value = (String) properties.get(CFG_DESCRIPTION)) != null) { + description = value; + } + + } finally { + ServiceReference ref = context.getServiceReference(EventAdmin.class); + if (ref != null) { + EventAdmin eventAdmin = context.getService(ref); + + Map props = new HashMap<>(); + + props.put(PluginManager.PROPERTY_PLUGIN_ID, id); + props.put(PluginManager.PROPERTY_PLUGIN_VERSION, version.toString()); + props.put(PluginManager.PROPERTY_PLUGIN_PRIORITY, priority); + props.put(PluginManager.PROPERTY_PLUGIN_DESCRIPTION, description); + props.put(PluginManager.PROPERTY_PLUGIN_KEYWORDS, keywords.toString()); + + Set types = new HashSet<>(); + + for (Class cl = this.getClass(); cl != Object.class; cl = cl.getSuperclass()) { + for (Class iface : cl.getInterfaces()) { + types.add(iface.getName()); + } + } + + props.put(PluginManager.PROPERTY_PLUGIN_TYPES, types.toString()); + + eventAdmin.sendEvent(new Event(PluginManager.TOPIC_PLUGIN_CONFIGURED, props)); + } + } + } + + this.properties = properties; + } +} diff --git a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/Plugin.java b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/Plugin.java index 3e07a549..dc7fe15f 100644 --- a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/Plugin.java +++ b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/Plugin.java @@ -1,97 +1,97 @@ -package cz.zcu.kiv.crce.plugin; - -import java.util.List; - -import javax.annotation.Nonnull; -import org.osgi.framework.Version; - -/** - * Common plugin interface. Every plugin must implement it. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Plugin extends Comparable { - - /** - * Configuration property name for plugin ID. - *

The value should follow the rules for bundle symbolic name. - */ - String CFG_ID = "plugin.id"; - /** - * Configuration property name for plugin version. - *

The value must follow the rules for OSGi version. - */ - String CFG_VERSION = "plugin.version"; - /** - * Configuration property name for plugin priority. - *

The value must be an integer or PRIORITY_MAX_VALUE and - * PRIORITY_MIN_VALUE constants. - */ - String CFG_PRIORITY = "plugin.priority"; - /** - * Configuration property name for plugin keywords. - *

The value must be a string or list of strings separated by comma. - */ - String CFG_KEYWORDS = "plugin.keywords"; - /** - * Configuration property name for plugin description. - *

The value should be a human readable description including spaces and - * punctuation. - */ - String CFG_DESCRIPTION = "plugin.description"; - - /** - * This value can be set to a plugin priority configuration property as - * a maximal possible value. - */ - String PRIORITY_MAX_VALUE = "MAX"; - /** - * This value can be set to a plugin priority configuration property as - * a minimal possible value. - */ - String PRIORITY_MIN_VALUE = "MIN"; - - /** - * Returns the plugin unique identification. - * - * @return the plugin indentification. - */ - @Nonnull - String getPluginId(); - - /** - * Returns the version of plugin. - * - * @return the version of plugin. - */ - @Nonnull - Version getPluginVersion(); - - /** - * Returns plugin priority. If more plugins of the same type are present, - * the one with the highest priority will be used. - * - * @return the priority of plugin. - */ - int getPluginPriority(); - - /** - * Returns the human-readable description of plugin. - * - * @return the human-readable description of plugin. - */ - @Nonnull - String getPluginDescription(); - - /** - * Returns an optional array of plugin keywords or zero-length array if no - * keyword is specified. - * - *

Keywords can be used to more precise specifying of plugin(s) returned - * by PluginManager. - * - * @return an array of keywords. - */ - @Nonnull - List getPluginKeywords(); -} +package cz.zcu.kiv.crce.plugin; + +import java.util.List; + +import javax.annotation.Nonnull; +import org.osgi.framework.Version; + +/** + * Common plugin2 interface. Every plugin2 must implement it. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Plugin extends Comparable { + + /** + * Configuration property name for plugin2 ID. + *

The value should follow the rules for bundle symbolic name. + */ + String CFG_ID = "plugin2.id"; + /** + * Configuration property name for plugin2 version. + *

The value must follow the rules for OSGi version. + */ + String CFG_VERSION = "plugin2.version"; + /** + * Configuration property name for plugin2 priority. + *

The value must be an integer or PRIORITY_MAX_VALUE and + * PRIORITY_MIN_VALUE constants. + */ + String CFG_PRIORITY = "plugin2.priority"; + /** + * Configuration property name for plugin2 keywords. + *

The value must be a string or list of strings separated by comma. + */ + String CFG_KEYWORDS = "plugin2.keywords"; + /** + * Configuration property name for plugin2 description. + *

The value should be a human readable description including spaces and + * punctuation. + */ + String CFG_DESCRIPTION = "plugin2.description"; + + /** + * This value can be set to a plugin2 priority configuration property as + * a maximal possible value. + */ + String PRIORITY_MAX_VALUE = "MAX"; + /** + * This value can be set to a plugin2 priority configuration property as + * a minimal possible value. + */ + String PRIORITY_MIN_VALUE = "MIN"; + + /** + * Returns the plugin2 unique identification. + * + * @return the plugin2 indentification. + */ + @Nonnull + String getPluginId(); + + /** + * Returns the version of plugin2. + * + * @return the version of plugin2. + */ + @Nonnull + Version getPluginVersion(); + + /** + * Returns plugin2 priority. If more plugins of the same type are present, + * the one with the highest priority will be used. + * + * @return the priority of plugin2. + */ + int getPluginPriority(); + + /** + * Returns the human-readable description of plugin2. + * + * @return the human-readable description of plugin2. + */ + @Nonnull + String getPluginDescription(); + + /** + * Returns an optional array of plugin2 keywords or zero-length array if no + * keyword is specified. + * + *

Keywords can be used to more precise specifying of plugin2(s) returned + * by PluginManager. + * + * @return an array of keywords. + */ + @Nonnull + List getPluginKeywords(); +} diff --git a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/PluginManager.java b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/PluginManager.java index 166011e6..e9c827a5 100644 --- a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/PluginManager.java +++ b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/PluginManager.java @@ -1,128 +1,128 @@ -package cz.zcu.kiv.crce.plugin; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Plugin manager is responsible to register, unregister and provide plugins. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface PluginManager { - - String NO_KEYWORDS = ""; - - String TOPIC_PLUGIN_REGISTERED = PluginManager.class.getName().replace(".", "/") + "/REGISTERED"; - String TOPIC_PLUGIN_UNREGISTERED = PluginManager.class.getName().replace(".", "/") + "/UNREGISTERED"; - String TOPIC_PLUGIN_CONFIGURED = PluginManager.class.getName().replace(".", "/") + "/CONFIGURED"; - - String PROPERTY_PLUGIN_ID = "id"; - String PROPERTY_PLUGIN_VERSION = "version"; - String PROPERTY_PLUGIN_PRIORITY = "priority"; - String PROPERTY_PLUGIN_DESCRIPTION = "description"; - String PROPERTY_PLUGIN_KEYWORDS = "keywords"; - String PROPERTY_PLUGIN_TYPES = "types"; - - /** - * Returns all registered plugins ordered by their priority. - * - * @return an array containing all registered plugins. - */ - @Nonnull - List getPlugins(); - - /** - * Returns all registered instances of plugins with the specified type. - * - *

Returned array is sort by plugins priority. - * - *

Example usage: - *

- *
-     * PluginManager pm = ... // get instance
-     * ResourceDAO[] daos = pm.getPlugins(ResourceDAO.class);
-     * 
- *
- * - * @param - * @param type the Class object representing the type of - * plugins in returned array. - * @return the array with plugins of given type. - */ - @Nonnull - List getPlugins(Class type); - - - // TODO is the following necessary? should be inclusive or exclusive regarding keywords? -// /** -// * Returns all registered instances of plugins with the specified type and -// * keywords. -// * -// *

Returned array is sort by plugins' priority and contains plugins -// * registered with specified keywords only. If keywords are null -// * or are not specified, then all plugins of given type are returned. -// * If keyword is a zero-length string, then all plugins of given type with -// * no keyword are returned. -// * -// * @param -// * @param type the Class object representing the type of -// * plugins in returned array. -// * @param keywords an optional array of keywords specifying the selection -// * of plugins. -// * @return the array with plugins of given type and keywords. -// */ -// T[] getPlugins(Class type, String... keywords); - - /** - * Returns all registered instances of plugins with the specified type and - * keyword. - * - *

Returned array is sort by plugins' priority and contains plugins - * registered with specified keyword only. If keyword is null, - * then all plugins of given type are returned. - * If keyword is a NO_KEYWORDS string, then all plugins of given - * type with no keyword are returned. - * - * @param - * @param type the Class object representing the type of - * plugins in returned array. - * @param keyword a keyword specifying the selection of plugins. - * @return the array with plugins of specified type and with given keyword. - */ - @Nonnull - List getPlugins(Class type, @Nullable String keyword); - - /** - * Returns an instance of preferred plugin implementation of specified type. - * - *

If more implementations of plugin with given type are present, - * then the one with the highest priority is returned. - * - * @param - * @param type the Class object representing the type of - * returned plugin. - * @return the instance of plugin. - */ - @Nonnull - T getPlugin(Class type); - - /** - * Returns an instance of preferred plugin implementation of specified type - * and keyword. - * - *

If more implementations of plugin with given type and keyword are - * present, then the one with the highest priority is returned. - * - * @param - * @param type the Class object representing the type of - * returned plugin. - * @param keyword a keyword specifying the selection of plugins. - * @return the instance of plugin. - */ - @Nonnull - T getPlugin(Class type, @Nullable String keyword); -} +package cz.zcu.kiv.crce.plugin; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Plugin manager is responsible to register, unregister and provide plugins. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface PluginManager { + + String NO_KEYWORDS = ""; + + String TOPIC_PLUGIN_REGISTERED = PluginManager.class.getName().replace(".", "/") + "/REGISTERED"; + String TOPIC_PLUGIN_UNREGISTERED = PluginManager.class.getName().replace(".", "/") + "/UNREGISTERED"; + String TOPIC_PLUGIN_CONFIGURED = PluginManager.class.getName().replace(".", "/") + "/CONFIGURED"; + + String PROPERTY_PLUGIN_ID = "id"; + String PROPERTY_PLUGIN_VERSION = "version"; + String PROPERTY_PLUGIN_PRIORITY = "priority"; + String PROPERTY_PLUGIN_DESCRIPTION = "description"; + String PROPERTY_PLUGIN_KEYWORDS = "keywords"; + String PROPERTY_PLUGIN_TYPES = "types"; + + /** + * Returns all registered plugins ordered by their priority. + * + * @return an array containing all registered plugins. + */ + @Nonnull + List getPlugins(); + + /** + * Returns all registered instances of plugins with the specified type. + * + *

Returned array is sort by plugins priority. + * + *

Example usage: + *

+ *
+     * PluginManager pm = ... // get instance
+     * ResourceDAO[] daos = pm.getPlugins(ResourceDAO.class);
+     * 
+ *
+ * + * @param + * @param type the Class object representing the type of + * plugins in returned array. + * @return the array with plugins of given type. + */ + @Nonnull + List getPlugins(Class type); + + + // TODO is the following necessary? should be inclusive or exclusive regarding keywords? +// /** +// * Returns all registered instances of plugins with the specified type and +// * keywords. +// * +// *

Returned array is sort by plugins' priority and contains plugins +// * registered with specified keywords only. If keywords are null +// * or are not specified, then all plugins of given type are returned. +// * If keyword is a zero-length string, then all plugins of given type with +// * no keyword are returned. +// * +// * @param +// * @param type the Class object representing the type of +// * plugins in returned array. +// * @param keywords an optional array of keywords specifying the selection +// * of plugins. +// * @return the array with plugins of given type and keywords. +// */ +// T[] getPlugins(Class type, String... keywords); + + /** + * Returns all registered instances of plugins with the specified type and + * keyword. + * + *

Returned array is sort by plugins' priority and contains plugins + * registered with specified keyword only. If keyword is null, + * then all plugins of given type are returned. + * If keyword is a NO_KEYWORDS string, then all plugins of given + * type with no keyword are returned. + * + * @param + * @param type the Class object representing the type of + * plugins in returned array. + * @param keyword a keyword specifying the selection of plugins. + * @return the array with plugins of specified type and with given keyword. + */ + @Nonnull + List getPlugins(Class type, @Nullable String keyword); + + /** + * Returns an instance of preferred plugin2 implementation of specified type. + * + *

If more implementations of plugin2 with given type are present, + * then the one with the highest priority is returned. + * + * @param + * @param type the Class object representing the type of + * returned plugin2. + * @return the instance of plugin2. + */ + @Nonnull + T getPlugin(Class type); + + /** + * Returns an instance of preferred plugin2 implementation of specified type + * and keyword. + * + *

If more implementations of plugin2 with given type and keyword are + * present, then the one with the highest priority is returned. + * + * @param + * @param type the Class object representing the type of + * returned plugin2. + * @param keyword a keyword specifying the selection of plugins. + * @return the instance of plugin2. + */ + @Nonnull + T getPlugin(Class type, @Nullable String keyword); +} diff --git a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/Activator.java b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/Activator.java index 152a7fdf..00da7ef8 100644 --- a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/Activator.java +++ b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/Activator.java @@ -1,37 +1,37 @@ -package cz.zcu.kiv.crce.plugin.internal; - -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.plugin.PluginManager; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; - -import org.osgi.framework.BundleContext; -import org.osgi.service.event.EventAdmin; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase { - - static final PluginManagerImpl pluginManager = new PluginManagerImpl(); - - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - - manager.add(createComponent() - .setInterface(PluginManager.class.getName(), null) - .setImplementation(pluginManager) - .add(createServiceDependency().setRequired(true).setService(EventAdmin.class)) - .add(createServiceDependency().setRequired(false).setCallbacks("register", "unregister").setService(Plugin.class)) - ); - - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - // nothing yet - } - -} +package cz.zcu.kiv.crce.plugin.internal; + +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.plugin.PluginManager; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; + +import org.osgi.framework.BundleContext; +import org.osgi.service.event.EventAdmin; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase { + + static final PluginManagerImpl pluginManager = new PluginManagerImpl(); + + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + + manager.add(createComponent() + .setInterface(PluginManager.class.getName(), null) + .setImplementation(pluginManager) + .add(createServiceDependency().setRequired(true).setService(EventAdmin.class)) + .add(createServiceDependency().setRequired(false).setCallbacks("register", "unregister").setService(Plugin.class)) + ); + + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + // nothing yet + } + +} diff --git a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/PluginManagerImpl.java b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/PluginManagerImpl.java index f0fe6651..1e14aa81 100644 --- a/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/PluginManagerImpl.java +++ b/core/crce-plugin-api/src/main/java/cz/zcu/kiv/crce/plugin/internal/PluginManagerImpl.java @@ -1,248 +1,248 @@ -package cz.zcu.kiv.crce.plugin.internal; - -import static cz.zcu.kiv.crce.plugin.PluginManager.*; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.osgi.service.event.Event; -import org.osgi.service.event.EventAdmin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.plugin.PluginManager; - -/** - * Implementation of PluginManager. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class PluginManagerImpl implements PluginManager { - - private static final Logger logger = LoggerFactory.getLogger(PluginManagerImpl.class); - - private static final String ROOT_CLASS = "java.lang.Object"; - private volatile EventAdmin eventAdmin; /* injected by dependency manager */ - - /** - * Map of maps containing sets of plugins associated with a keyword. - * The key to outer map is a plugin type, value is inner map. - * The key to inner map is a keyword associated to a set of plugins. - */ - private final Map, Map>> plugins = new HashMap<>(); - - @Override - public synchronized List getPlugins() { - return getPlugins(Plugin.class); - } - - @Override - public List getPlugins(Class type) { - return getPluginsIncl(type, new String[]{null}); - } - - @Override - public List getPlugins(Class type, String keyword) { - return getPluginsIncl(type, keyword); - } - - /** - * Implementation of getPlugins() with inclusive multiple keywords - * (returning all plugins of specified type with at least one of - * given keywords). - * - * @param - * @param type - * @param keywords - * @return - */ - @SuppressWarnings("unchecked") - private synchronized List getPluginsIncl(Class type, String... keywords) { - if (keywords == null || keywords.length == 0) { - keywords = new String[]{null}; - } - Map> map = plugins.get(type); - if (map == null) { - return Collections.emptyList(); - } - - Set out = new TreeSet<>(); - for (String keyword : keywords) { - Set set = (Set) map.get(keyword); - if (set != null) { - out.addAll(set); - } - } -// List result = -// T[] array = (T[]) java.lang.reflect.Array.newInstance(type, out.size()); -// T[] sorted = out.toArray(array); -// Arrays.sort(sorted); - return new ArrayList<>(out); - } - - @Override - public T getPlugin(Class type) { - return getPlugin(type, null); - } - - @Override - public synchronized T getPlugin(Class type, String keyword) { - Map> map = plugins.get(type); - if (map == null) { - return getProxy(type); - } - Set set = map.get(keyword); - if (set == null || set.isEmpty()) { - return getProxy(type); - } - Set sorted = new TreeSet<>(set); - @SuppressWarnings("unchecked") - T t = (T) sorted.iterator().next(); - return t; - } - - @SuppressWarnings("unchecked") - private T getProxy(Class type) { - return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return null; - } - - }); - } - - /** - * Callback method called on adding new plugin. - * @param plugin - */ - synchronized void register(Plugin plugin) { - Set types = new HashSet<>(); - addRecursive(plugin.getClass(), plugin, types); - - logger.info("Plugin registered: {}", plugin.getPluginId()); - - Map properties = new HashMap<>(); - properties.put(PROPERTY_PLUGIN_ID, plugin.getPluginId()); - properties.put(PROPERTY_PLUGIN_VERSION, plugin.getPluginVersion().toString()); - properties.put(PROPERTY_PLUGIN_PRIORITY, plugin.getPluginPriority()); - properties.put(PROPERTY_PLUGIN_DESCRIPTION, plugin.getPluginDescription()); - properties.put(PROPERTY_PLUGIN_KEYWORDS, plugin.getPluginKeywords().toString()); - properties.put(PROPERTY_PLUGIN_TYPES, types.toString()); - - eventAdmin.sendEvent(new Event(TOPIC_PLUGIN_REGISTERED, properties)); - } - - /** - * Callback method called on removing existing plugin. - * @param plugin - */ - synchronized void unregister(Plugin plugin) { - Set types = new HashSet<>(); - removeRecursive(plugin.getClass(), plugin, types); - - logger.info("Plugin unregistered: {}", plugin.getPluginId()); - - Map properties = new HashMap<>(); - properties.put(PROPERTY_PLUGIN_ID, plugin.getPluginId()); - properties.put(PROPERTY_PLUGIN_VERSION, plugin.getPluginVersion().toString()); - properties.put(PROPERTY_PLUGIN_PRIORITY, plugin.getPluginPriority()); - properties.put(PROPERTY_PLUGIN_DESCRIPTION, plugin.getPluginDescription()); - properties.put(PROPERTY_PLUGIN_KEYWORDS, plugin.getPluginKeywords().toString()); - properties.put(PROPERTY_PLUGIN_TYPES, types.toString()); - - eventAdmin.sendEvent(new Event(TOPIC_PLUGIN_REGISTERED, properties)); - } - - private void removeRecursive(Class clazz, Plugin plugin, Set types) { - if (ROOT_CLASS.equals(clazz.getName())) { - return; - } - for (Class iface : clazz.getInterfaces()) { - types.add(clazz.getName()); - Map> map = plugins.get(iface); - if (map == null) { - continue; - } - Set set; - if (plugin.getPluginKeywords().isEmpty()) { - if ((set = map.get(NO_KEYWORDS)) != null) { - set.remove(plugin); - } - } else { - for (String keyword : plugin.getPluginKeywords()) { - if ((set = map.get(keyword)) != null) { - set.remove(plugin); - } - } - } - if ((set = map.get(null)) != null) { - set.remove(plugin); - } - } - removeRecursive(clazz.getSuperclass(), plugin, types); - } - - private void addRecursive(Class clazz, Plugin plugin, Set types) { - if (ROOT_CLASS.equals(clazz.getName())) { - return; - } - for (Class iface : clazz.getInterfaces()) { - types.add(iface.getName()); - if (plugin.getPluginKeywords().isEmpty()) { - add(iface, plugin, NO_KEYWORDS); - } else { - for (String keyword : plugin.getPluginKeywords()) { - add(iface, plugin, keyword); - } - } - add(iface, plugin, null); - } - addRecursive(clazz.getSuperclass(), plugin, types); - } - - @SuppressWarnings("unchecked") - private void add(Class iface, Plugin plugin, String keyword) { - Map> map = plugins.get(iface); - if (map == null) { - map = new HashMap<>(); - plugins.put(iface, map); - } - Set set = map.get(keyword); - if (set == null) { - set = new HashSet<>(); - map.put(keyword, set); - } - ((Set) set).add(plugin); - } - - @Override - public synchronized String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Plugins:\n"); - for (Class clazz : plugins.keySet()) { - sb.append(" ").append(clazz.getName()).append(":\n"); - Map> map = plugins.get(clazz); - for (Map.Entry> entry : map.entrySet()) { - String keyword = entry.getKey(); - sb.append(" ").append(keyword == null ? "[null]" : (NO_KEYWORDS.equals(keyword)) ? "[none]" : keyword).append(":\n"); - for (Plugin plugin : entry.getValue()) { - sb.append(" ").append(plugin.getPluginId()).append("\n"); - } - } - } - - return sb.toString(); - } -} +package cz.zcu.kiv.crce.plugin.internal; + +import static cz.zcu.kiv.crce.plugin.PluginManager.*; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.osgi.service.event.Event; +import org.osgi.service.event.EventAdmin; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.plugin.PluginManager; + +/** + * Implementation of PluginManager. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class PluginManagerImpl implements PluginManager { + + private static final Logger logger = LoggerFactory.getLogger(PluginManagerImpl.class); + + private static final String ROOT_CLASS = "java.lang.Object"; + private volatile EventAdmin eventAdmin; /* injected by dependency manager */ + + /** + * Map of maps containing sets of plugins associated with a keyword. + * The key to outer map is a plugin2 type, value is inner map. + * The key to inner map is a keyword associated to a set of plugins. + */ + private final Map, Map>> plugins = new HashMap<>(); + + @Override + public synchronized List getPlugins() { + return getPlugins(Plugin.class); + } + + @Override + public List getPlugins(Class type) { + return getPluginsIncl(type, new String[]{null}); + } + + @Override + public List getPlugins(Class type, String keyword) { + return getPluginsIncl(type, keyword); + } + + /** + * Implementation of getPlugins() with inclusive multiple keywords + * (returning all plugins of specified type with at least one of + * given keywords). + * + * @param + * @param type + * @param keywords + * @return + */ + @SuppressWarnings("unchecked") + private synchronized List getPluginsIncl(Class type, String... keywords) { + if (keywords == null || keywords.length == 0) { + keywords = new String[]{null}; + } + Map> map = plugins.get(type); + if (map == null) { + return Collections.emptyList(); + } + + Set out = new TreeSet<>(); + for (String keyword : keywords) { + Set set = (Set) map.get(keyword); + if (set != null) { + out.addAll(set); + } + } +// List result = +// T[] array = (T[]) java.lang.reflect.Array.newInstance(type, out.size()); +// T[] sorted = out.toArray(array); +// Arrays.sort(sorted); + return new ArrayList<>(out); + } + + @Override + public T getPlugin(Class type) { + return getPlugin(type, null); + } + + @Override + public synchronized T getPlugin(Class type, String keyword) { + Map> map = plugins.get(type); + if (map == null) { + return getProxy(type); + } + Set set = map.get(keyword); + if (set == null || set.isEmpty()) { + return getProxy(type); + } + Set sorted = new TreeSet<>(set); + @SuppressWarnings("unchecked") + T t = (T) sorted.iterator().next(); + return t; + } + + @SuppressWarnings("unchecked") + private T getProxy(Class type) { + return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return null; + } + + }); + } + + /** + * Callback method called on adding new plugin2. + * @param plugin + */ + synchronized void register(Plugin plugin) { + Set types = new HashSet<>(); + addRecursive(plugin.getClass(), plugin, types); + + logger.info("Plugin registered: {}", plugin.getPluginId()); + + Map properties = new HashMap<>(); + properties.put(PROPERTY_PLUGIN_ID, plugin.getPluginId()); + properties.put(PROPERTY_PLUGIN_VERSION, plugin.getPluginVersion().toString()); + properties.put(PROPERTY_PLUGIN_PRIORITY, plugin.getPluginPriority()); + properties.put(PROPERTY_PLUGIN_DESCRIPTION, plugin.getPluginDescription()); + properties.put(PROPERTY_PLUGIN_KEYWORDS, plugin.getPluginKeywords().toString()); + properties.put(PROPERTY_PLUGIN_TYPES, types.toString()); + + eventAdmin.sendEvent(new Event(TOPIC_PLUGIN_REGISTERED, properties)); + } + + /** + * Callback method called on removing existing plugin2. + * @param plugin + */ + synchronized void unregister(Plugin plugin) { + Set types = new HashSet<>(); + removeRecursive(plugin.getClass(), plugin, types); + + logger.info("Plugin unregistered: {}", plugin.getPluginId()); + + Map properties = new HashMap<>(); + properties.put(PROPERTY_PLUGIN_ID, plugin.getPluginId()); + properties.put(PROPERTY_PLUGIN_VERSION, plugin.getPluginVersion().toString()); + properties.put(PROPERTY_PLUGIN_PRIORITY, plugin.getPluginPriority()); + properties.put(PROPERTY_PLUGIN_DESCRIPTION, plugin.getPluginDescription()); + properties.put(PROPERTY_PLUGIN_KEYWORDS, plugin.getPluginKeywords().toString()); + properties.put(PROPERTY_PLUGIN_TYPES, types.toString()); + + eventAdmin.sendEvent(new Event(TOPIC_PLUGIN_REGISTERED, properties)); + } + + private void removeRecursive(Class clazz, Plugin plugin, Set types) { + if (ROOT_CLASS.equals(clazz.getName())) { + return; + } + for (Class iface : clazz.getInterfaces()) { + types.add(clazz.getName()); + Map> map = plugins.get(iface); + if (map == null) { + continue; + } + Set set; + if (plugin.getPluginKeywords().isEmpty()) { + if ((set = map.get(NO_KEYWORDS)) != null) { + set.remove(plugin); + } + } else { + for (String keyword : plugin.getPluginKeywords()) { + if ((set = map.get(keyword)) != null) { + set.remove(plugin); + } + } + } + if ((set = map.get(null)) != null) { + set.remove(plugin); + } + } + removeRecursive(clazz.getSuperclass(), plugin, types); + } + + private void addRecursive(Class clazz, Plugin plugin, Set types) { + if (ROOT_CLASS.equals(clazz.getName())) { + return; + } + for (Class iface : clazz.getInterfaces()) { + types.add(iface.getName()); + if (plugin.getPluginKeywords().isEmpty()) { + add(iface, plugin, NO_KEYWORDS); + } else { + for (String keyword : plugin.getPluginKeywords()) { + add(iface, plugin, keyword); + } + } + add(iface, plugin, null); + } + addRecursive(clazz.getSuperclass(), plugin, types); + } + + @SuppressWarnings("unchecked") + private void add(Class iface, Plugin plugin, String keyword) { + Map> map = plugins.get(iface); + if (map == null) { + map = new HashMap<>(); + plugins.put(iface, map); + } + Set set = map.get(keyword); + if (set == null) { + set = new HashSet<>(); + map.put(keyword, set); + } + ((Set) set).add(plugin); + } + + @Override + public synchronized String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Plugins:\n"); + for (Class clazz : plugins.keySet()) { + sb.append(" ").append(clazz.getName()).append(":\n"); + Map> map = plugins.get(clazz); + for (Map.Entry> entry : map.entrySet()) { + String keyword = entry.getKey(); + sb.append(" ").append(keyword == null ? "[null]" : (NO_KEYWORDS.equals(keyword)) ? "[none]" : keyword).append(":\n"); + for (Plugin plugin : entry.getValue()) { + sb.append(" ").append(plugin.getPluginId()).append("\n"); + } + } + } + + return sb.toString(); + } +} diff --git a/core/crce-repository-api/osgi.bnd b/core/crce-repository-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-repository-api/osgi.bnd +++ b/core/crce-repository-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-repository-api/pom.xml b/core/crce-repository-api/pom.xml index df6f9e58..c188a933 100644 --- a/core/crce-repository-api/pom.xml +++ b/core/crce-repository-api/pom.xml @@ -1,61 +1,61 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-repository-api - 2.2.0-SNAPSHOT - bundle - - CRCE - Core - Repository API - - - https://github.com/ReliSA/crce/tree/master/core/crce-repository-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.repository.api - ${namespace}.repository - - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-plugin-api - 2.1.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-repository-api + 2.2.0-SNAPSHOT + bundle + + CRCE - Core - Repository API + + + https://github.com/ReliSA/crce/tree/master/core/crce-repository-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.repository.api + ${namespace}.repository + + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-plugin-api + 2.1.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Buffer.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Buffer.java index a08c158b..5984950b 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Buffer.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Buffer.java @@ -1,59 +1,59 @@ -package cz.zcu.kiv.crce.repository; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * This interface defines a temporary store for uploading artifacts before putting - * them to the permanent store. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface Buffer extends Store { - - /** - * Puts a new resource into resource buffer. - * - * @param name A name of uploaded file. - * @param resource Uploaded resource. - * @return - * @throws IOException - * @throws RefusedArtifactException - */ - @Nonnull - Resource put(String name, InputStream resource) throws IOException, RefusedArtifactException; - - /** - * Commits uploaded resources to the configured store. - *

If move is true then resources will be removed - * from the buffer. Returned list constains resources successfully commited - * to the store. - * - * @param move if true, commited resources are removed from the - * buffer. - * @return list of commited resources. - * @throws IOException - */ - @Nonnull - List commit(boolean move) throws IOException; - - /** - * Commits only the given resources to the configured store. - *

If move is true then resources will be removed - * from the buffer. Returned list constains resources successfully commited - * to the store. - * - * @param resources - * @param move - * @return - * @throws IOException - */ - @Nonnull - List commit(List resources, boolean move) throws IOException; -} +package cz.zcu.kiv.crce.repository; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * This interface defines a temporary store for uploading artifacts before putting + * them to the permanent store. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface Buffer extends Store { + + /** + * Puts a new resource into resource buffer. + * + * @param name A name of uploaded file. + * @param resource Uploaded resource. + * @return + * @throws IOException + * @throws RefusedArtifactException + */ + @Nonnull + Resource put(String name, InputStream resource) throws IOException, RefusedArtifactException; + + /** + * Commits uploaded resources to the configured store. + *

If move is true then resources will be removed + * from the buffer. Returned list constains resources successfully commited + * to the store. + * + * @param move if true, commited resources are removed from the + * buffer. + * @return list of commited resources. + * @throws IOException + */ + @Nonnull + List commit(boolean move) throws IOException; + + /** + * Commits only the given resources to the configured store. + *

If move is true then resources will be removed + * from the buffer. Returned list constains resources successfully commited + * to the store. + * + * @param resources + * @param move + * @return + * @throws IOException + */ + @Nonnull + List commit(List resources, boolean move) throws IOException; +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/RefusedArtifactException.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/RefusedArtifactException.java index 1470ac8c..9fee1c93 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/RefusedArtifactException.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/RefusedArtifactException.java @@ -1,45 +1,45 @@ -package cz.zcu.kiv.crce.repository; - -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Throwed if artifact put into the Buffer or Store is revoked and can not be stored. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public class RefusedArtifactException extends Exception { - - private static final long serialVersionUID = 3732119005799739933L; - - public enum REASON { - /** - * General reason for revoking, no special care needed. - */ - UNSPECIFIED, - /** - * Revoked because there has been another resource of the same symbolic name - * in the buffer. - */ - ALREADY_IN_BUFFER - } - - private REASON reason; - - public RefusedArtifactException(String reason) { - this(reason, REASON.UNSPECIFIED); - } - - public RefusedArtifactException(String reasonDesc, REASON reason) { - super(reasonDesc); - this.reason = reason; - } - - public REASON getReason() { - return reason; - } - - public void setReason(REASON reason) { - this.reason = reason; - } -} +package cz.zcu.kiv.crce.repository; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Throwed if artifact put into the Buffer or Store is revoked and can not be stored. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public class RefusedArtifactException extends Exception { + + private static final long serialVersionUID = 3732119005799739933L; + + public enum REASON { + /** + * General reason for revoking, no special care needed. + */ + UNSPECIFIED, + /** + * Revoked because there has been another resource of the same symbolic name + * in the buffer. + */ + ALREADY_IN_BUFFER + } + + private REASON reason; + + public RefusedArtifactException(String reason) { + this(reason, REASON.UNSPECIFIED); + } + + public RefusedArtifactException(String reasonDesc, REASON reason) { + super(reasonDesc); + this.reason = reason; + } + + public REASON getReason() { + return reason; + } + + public void setReason(REASON reason) { + this.reason = reason; + } +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionData.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionData.java index c91dbb08..a00d4670 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionData.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionData.java @@ -1,13 +1,13 @@ -package cz.zcu.kiv.crce.repository; - -import javax.annotation.Nonnull; - -/** - * This interface defines a session-dependend data for instances of Buffer. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface SessionData { - - @Nonnull - Buffer getBuffer(); -} +package cz.zcu.kiv.crce.repository; + +import javax.annotation.Nonnull; + +/** + * This interface defines a session-dependend data for instances of Buffer. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface SessionData { + + @Nonnull + Buffer getBuffer(); +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionRegister.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionRegister.java index 0d3a916c..bcc6da70 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionRegister.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/SessionRegister.java @@ -1,34 +1,34 @@ -package cz.zcu.kiv.crce.repository; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -/** - * Implementing class of this interface can instantiate and register Buffer. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface SessionRegister { - - String SERVICE_SESSION_ID = "service.sid"; - - /** - * Registers session data with Buffer for given ID. - * @param sessionId - */ - void registerSession(String sessionId); - - /** - * Unregisters and erase session data with Buffer for given ID. - * @param sessionId - */ - void unregisterSession(String sessionId); - - /** - * Registers session data with Buffer for given ID and returns it. - * @param sessionId - * @return - */ - @Nonnull - SessionData getSessionData(String sessionId); -} +package cz.zcu.kiv.crce.repository; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Implementing class of this interface can instantiate and register Buffer. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface SessionRegister { + + String SERVICE_SESSION_ID = "service.sid"; + + /** + * Registers session data with Buffer for given ID. + * @param sessionId + */ + void registerSession(String sessionId); + + /** + * Unregisters and erase session data with Buffer for given ID. + * @param sessionId + */ + void unregisterSession(String sessionId); + + /** + * Registers session data with Buffer for given ID and returns it. + * @param sessionId + * @return + */ + @Nonnull + SessionData getSessionData(String sessionId); +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Store.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Store.java index d9851990..cea78a75 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Store.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/Store.java @@ -1,67 +1,67 @@ -package cz.zcu.kiv.crce.repository; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.repository.plugins.Executable; - -/** - * This interface defines permanent store for artifacts. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface Store { - - /** - * Puts resource to the Store. - * - * @param resource - * @return - * @throws IOException - * @throws RefusedArtifactException - */ - @Nonnull - Resource put(Resource resource) throws IOException, RefusedArtifactException; - - /** - * Removes the resource from this buffer and returns true, if - * the buffer contained the given resource before removing, false - * otherwise. - * - * @param resource Resource to be removed from this buffer. - * @return true, if the buffer contained the resource before - * removing. - * @throws IOException - */ - boolean remove(Resource resource) throws IOException; - - /** - * Returns list of resources stored in the Store. - * @return list of stored resources. - */ - @Nonnull - List getResources(); - - @Nonnull - List getResources(Requirement requirement); - - @Nonnull - List getResources(Set requirement); - - /** - * TODO analyze requirements for this method: - * - add an executable plugin - * @param resources - * @param executable - * @param properties - */ - void execute(List resources, Executable executable, @CheckForNull Properties properties); -} +package cz.zcu.kiv.crce.repository; + +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.repository.plugins.Executable; + +/** + * This interface defines permanent store for artifacts. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface Store { + + /** + * Puts resource to the Store. + * + * @param resource + * @return + * @throws IOException + * @throws RefusedArtifactException + */ + @Nonnull + Resource put(Resource resource) throws IOException, RefusedArtifactException; + + /** + * Removes the resource from this buffer and returns true, if + * the buffer contained the given resource before removing, false + * otherwise. + * + * @param resource Resource to be removed from this buffer. + * @return true, if the buffer contained the resource before + * removing. + * @throws IOException + */ + boolean remove(Resource resource) throws IOException; + + /** + * Returns list of resources stored in the Store. + * @return list of stored resources. + */ + @Nonnull + List getResources(); + + @Nonnull + List getResources(Requirement requirement); + + @Nonnull + List getResources(Set requirement); + + /** + * TODO analyze requirements for this method: + * - add an executable plugin2 + * @param resources + * @param executable + * @param properties + */ + void execute(List resources, Executable executable, @CheckForNull Properties properties); +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractActionHandler.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractActionHandler.java index cbf8f7a3..a44edff7 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractActionHandler.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractActionHandler.java @@ -1,122 +1,122 @@ -package cz.zcu.kiv.crce.repository.plugins; - -import java.util.List; -import java.util.Properties; - -import cz.zcu.kiv.crce.plugin.AbstractPlugin; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; - -/** - * Abstract implementation of ActionHandler which do nothing and - * it's methods return unmodified argument. - * - *

This class is recommended to be used as superclass for all implementations - * of ActionHandler so then it's not necessary to implement all - * methods. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public abstract class AbstractActionHandler extends AbstractPlugin implements ActionHandler { - - @Override - public boolean isExclusive() { - return false; - } - - @Override - public Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { - return resource; - } - - @Override - public List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { - return resources; - } - - @Override - public List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { - return resources; - } - - @Override - public List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store) { - return resources; - } - - @Override - public List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store) { - return resources; - } - - @Override - public String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException { - return name; - } - - @Override - public Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { - return resource; - } - - @Override - public Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer) { - return resource; - } - - @Override - public Resource afterDownloadFromBuffer(Resource resource, Buffer buffer) { - return resource; - } - - @Override - public Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer) { - return resource; - } - - @Override - public Resource afterDeleteFromBuffer(Resource resource, Buffer buffer) { - return resource; - } - - @Override - public List beforeBufferCommit(List resources, Buffer buffer, Store store) { - return resources; - } - - @Override - public List afterBufferCommit(List resources, Buffer buffer, Store store) { - return resources; - } - - @Override - public Resource beforeDeleteFromStore(Resource resource, Store store) { - return resource; - } - - @Override - public Resource afterDeleteFromStore(Resource resource, Store store) { - return resource; - } - - @Override - public Resource beforePutToStore(Resource resource, Store store) throws RefusedArtifactException { - return resource; - } - - @Override - public Resource afterPutToStore(Resource resource, Store store) throws RefusedArtifactException { - return resource; - } - - @Override - public Resource beforeDownloadFromStore(Resource resource, Store store) { - return resource; - } - - @Override - public Resource afterDownloadFromStore(Resource resource, Store store) { - return resource; - } -} +package cz.zcu.kiv.crce.repository.plugins; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.plugin.AbstractPlugin; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.Store; + +import java.util.List; +import java.util.Properties; + +/** + * Abstract implementation of ActionHandler which do nothing and + * it's methods return unmodified argument. + * + *

This class is recommended to be used as superclass for all implementations + * of ActionHandler so then it's not necessary to implement all + * methods. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public abstract class AbstractActionHandler extends AbstractPlugin implements ActionHandler { + + @Override + public boolean isExclusive() { + return false; + } + + @Override + public Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { + return resource; + } + + @Override + public List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { + return resources; + } + + @Override + public List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { + return resources; + } + + @Override + public List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store) { + return resources; + } + + @Override + public List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store) { + return resources; + } + + @Override + public String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException { + return name; + } + + @Override + public Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { + return resource; + } + + @Override + public Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer) { + return resource; + } + + @Override + public Resource afterDownloadFromBuffer(Resource resource, Buffer buffer) { + return resource; + } + + @Override + public Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer) { + return resource; + } + + @Override + public Resource afterDeleteFromBuffer(Resource resource, Buffer buffer) { + return resource; + } + + @Override + public List beforeBufferCommit(List resources, Buffer buffer, Store store) { + return resources; + } + + @Override + public List afterBufferCommit(List resources, Buffer buffer, Store store) { + return resources; + } + + @Override + public Resource beforeDeleteFromStore(Resource resource, Store store) { + return resource; + } + + @Override + public Resource afterDeleteFromStore(Resource resource, Store store) { + return resource; + } + + @Override + public Resource beforePutToStore(Resource resource, Store store) throws RefusedArtifactException { + return resource; + } + + @Override + public Resource afterPutToStore(Resource resource, Store store) throws RefusedArtifactException { + return resource; + } + + @Override + public Resource beforeDownloadFromStore(Resource resource, Store store) { + return resource; + } + + @Override + public Resource afterDownloadFromStore(Resource resource, Store store) { + return resource; + } +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractExecutable.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractExecutable.java index 2a93a316..f286b70b 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractExecutable.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/AbstractExecutable.java @@ -1,22 +1,22 @@ -package cz.zcu.kiv.crce.repository.plugins; - -import java.util.Properties; - -import cz.zcu.kiv.crce.plugin.AbstractPlugin; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public abstract class AbstractExecutable extends AbstractPlugin implements Executable { - - @Override - public boolean isExclusive() { - return false; - } - - @Override - public Properties getProperties() { - return new Properties(); - } -} +package cz.zcu.kiv.crce.repository.plugins; + +import java.util.Properties; + +import cz.zcu.kiv.crce.plugin.AbstractPlugin; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public abstract class AbstractExecutable extends AbstractPlugin implements Executable { + + @Override + public boolean isExclusive() { + return false; + } + + @Override + public Properties getProperties() { + return new Properties(); + } +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/ActionHandler.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/ActionHandler.java index d0bf5dfb..a4b2735c 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/ActionHandler.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/ActionHandler.java @@ -1,114 +1,114 @@ -package cz.zcu.kiv.crce.repository.plugins; - -import java.util.List; -import java.util.Properties; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; - -/** - * This interface defines an executable handler of various events which can - * occur during resource life-time. - * - *

Default execution of handlers is synchronous so the calling method - * will wait for the result of execution. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface ActionHandler extends Plugin { - - String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException; - - /** - * Invoked when an artifact is uploaded into upload buffer. - * - * @param resource - * @param name - * @param buffer - * @return - * @throws RefusedArtifactException - */ - Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException; - - Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException; - - - Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer); - - Resource afterDownloadFromBuffer(Resource resource, Buffer buffer); - - - List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer); - - List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer); - - - Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer); - - /** - * Invoked when resource is revoked deleted from buffer. - * - * @param resource - * @param buffer - * @return - */ - Resource afterDeleteFromBuffer(Resource resource, Buffer buffer); - - - List beforeBufferCommit(List resources, Buffer buffer, Store store); - - List afterBufferCommit(List resources, Buffer buffer, Store store); - - - Resource beforePutToStore(Resource resource, Store store) throws RefusedArtifactException; - - /** - * Invoked when resource is commited from buffer to repository. - * - * @param resource - * @param store - * @return - * @throws RefusedArtifactException - */ - Resource afterPutToStore(Resource resource, Store store) throws RefusedArtifactException; - - - Resource beforeDownloadFromStore(Resource resource, Store store); - - Resource afterDownloadFromStore(Resource resource, Store store); - - - Resource beforeDeleteFromStore(Resource resource, Store store); - - Resource afterDeleteFromStore(Resource resource, Store store); - - /** - * TODO proposed variant: - * Resource[] onExecuteInStore(Resource[] resources, Store store); - * - * TODO how to choose, which plugins will be executed? do an Executable plugin - * and pass it (or set of such plugins) as method parameter? - * or all plugins will be executed with no choice? - * - * - * @param resources - * @param executable - * @param properties - * @param store - * @return - */ - List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store); - - List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store); - - /** - * Returns true if implementing action handler modifies binary - * content of processed artifacts (not metadata!), false - * otherwise (content read-only handler). - * @return - */ - boolean isExclusive(); -} +package cz.zcu.kiv.crce.repository.plugins; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.Store; + +import java.util.List; +import java.util.Properties; + +/** + * This interface defines an executable handler of various events which can + * occur during resource life-time. + * + *

Default execution of handlers is synchronous so the calling method + * will wait for the result of execution. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface ActionHandler extends Plugin { + + String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException; + + /** + * Invoked when an artifact is uploaded into upload buffer. + * + * @param resource + * @param name + * @param buffer + * @return + * @throws RefusedArtifactException + */ + Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException; + + Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException; + + + Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer); + + Resource afterDownloadFromBuffer(Resource resource, Buffer buffer); + + + List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer); + + List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer); + + + Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer); + + /** + * Invoked when resource is revoked deleted from buffer. + * + * @param resource + * @param buffer + * @return + */ + Resource afterDeleteFromBuffer(Resource resource, Buffer buffer); + + + List beforeBufferCommit(List resources, Buffer buffer, Store store); + + List afterBufferCommit(List resources, Buffer buffer, Store store); + + + Resource beforePutToStore(Resource resource, Store store) throws RefusedArtifactException; + + /** + * Invoked when resource is commited from buffer to repository. + * + * @param resource + * @param store + * @return + * @throws RefusedArtifactException + */ + Resource afterPutToStore(Resource resource, Store store) throws RefusedArtifactException; + + + Resource beforeDownloadFromStore(Resource resource, Store store); + + Resource afterDownloadFromStore(Resource resource, Store store); + + + Resource beforeDeleteFromStore(Resource resource, Store store); + + Resource afterDeleteFromStore(Resource resource, Store store); + + /** + * TODO proposed variant: + * Resource[] onExecuteInStore(Resource[] resources, Store store); + * + * TODO how to choose, which plugins will be executed? do an Executable plugin2 + * and pass it (or set of such plugins) as method parameter? + * or all plugins will be executed with no choice? + * + * + * @param resources + * @param executable + * @param properties + * @param store + * @return + */ + List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store); + + List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store); + + /** + * Returns true if implementing action handler modifies binary + * content of processed artifacts (not metadata!), false + * otherwise (content read-only handler). + * @return + */ + boolean isExclusive(); +} diff --git a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/Executable.java b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/Executable.java index 7d0351d1..e60f0cc2 100644 --- a/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/Executable.java +++ b/core/crce-repository-api/src/main/java/cz/zcu/kiv/crce/repository/plugins/Executable.java @@ -1,81 +1,81 @@ -package cz.zcu.kiv.crce.repository.plugins; - -import java.util.List; -import java.util.Properties; - -import javax.annotation.Nonnull; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.Store; - -/* - * Zmeny od schuzky 2011-03-24: - * - dve metody pro spousteni, jedna pro spousteni nad bufferem (docasnem - * uploadovacim ulozisti), druha pro spousteni nad store (trvalem ulozisti); - * - misto Repository (mnozina Resourcu dostupnych v bufferu nebo v store) se - * predava reference na Store, prip. i Buffer, z nich je referenci na Repository - * mozno ziskat, ale krome toho lze se Store i Bufferem manipulovat (napr. - * mazat z nej Resourcy nebo i spustit dalsi Executable plugin). - * - pridana metoda pro zajisteni vyhradniho (neparalelniho behu). - */ -/** - * This interface specifies the kind of plugin which can be executed at any time - * by external event, e.g. on user's request. - * - *

The selection of resources contains resources that are to be e.g. tested. - * Other resources, that are not the point of execution but can be used as - * supporting resources, can be obtained from repository of given Store or Buffer. - * - *

Calling of executables can be asynchronous so there is no guarantee - * that the calling method will wait for the end of execution. - * - *

Executing of Executable plugins can be threaded (in dependence on - * implementation of Store/Buffer). If the implementation of Executable needs to - * be run exclusively, it have to return true from isExclusive() - * method. It can be useful e.g. in case of changing data of artifact (e.g. - * manifest of bundle) - in this case it ensures that the metadata will be valid - * during the execution of other Executable plugins. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Executable extends Plugin { - - /** - * Executes the plugin on the selection of resources stored in buffer. - * - * @param resources the set of resources that this plugin will run on. - * @param buffer - * @param store - * @param properties plugin configuration properties. - */ - void executeOnBuffer(@Nonnull List resources, @Nonnull Store store, @Nonnull Buffer buffer, @Nonnull Properties properties); - - /** - * Executes the plugin on the selection of resources stored in store. - * - * @param resources the set of resources that this plugin will run on. - * @param store - * @param properties plugin configuration properties. - */ - void executeOnStore(@Nonnull List resources, @Nonnull Store store, @Nonnull Properties properties); - - /** - * Returns true if the plugin needs to be executed exclusively - * (no other Executables will be executed at the same time until execution - * of this plugin finishes). - * @return true if the plugin needs to be executed exclusively. - */ - boolean isExclusive(); - - /** - * Returns the instance of Properties which can be used to - * reconfigure this plugin for specific execution. - * Note: Implementing class is responsible to clean changed properties - * after execution if needed. - * @return the instance of Properties. - */ - @Nonnull - Properties getProperties(); -} +package cz.zcu.kiv.crce.repository.plugins; + +import java.util.List; +import java.util.Properties; + +import javax.annotation.Nonnull; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.Store; + +/* + * Zmeny od schuzky 2011-03-24: + * - dve metody pro spousteni, jedna pro spousteni nad bufferem (docasnem + * uploadovacim ulozisti), druha pro spousteni nad store (trvalem ulozisti); + * - misto Repository (mnozina Resourcu dostupnych v bufferu nebo v store) se + * predava reference na Store, prip. i Buffer, z nich je referenci na Repository + * mozno ziskat, ale krome toho lze se Store i Bufferem manipulovat (napr. + * mazat z nej Resourcy nebo i spustit dalsi Executable plugin2). + * - pridana metoda pro zajisteni vyhradniho (neparalelniho behu). + */ +/** + * This interface specifies the kind of plugin2 which can be executed at any time + * by external event, e.g. on user's request. + * + *

The selection of resources contains resources that are to be e.g. tested. + * Other resources, that are not the point of execution but can be used as + * supporting resources, can be obtained from repository of given Store or Buffer. + * + *

Calling of executables can be asynchronous so there is no guarantee + * that the calling method will wait for the end of execution. + * + *

Executing of Executable plugins can be threaded (in dependence on + * implementation of Store/Buffer). If the implementation of Executable needs to + * be run exclusively, it have to return true from isExclusive() + * method. It can be useful e.g. in case of changing data of artifact (e.g. + * manifest of bundle) - in this case it ensures that the metadata will be valid + * during the execution of other Executable plugins. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Executable extends Plugin { + + /** + * Executes the plugin2 on the selection of resources stored in buffer. + * + * @param resources the set of resources that this plugin2 will run on. + * @param buffer + * @param store + * @param properties plugin2 configuration properties. + */ + void executeOnBuffer(@Nonnull List resources, @Nonnull Store store, @Nonnull Buffer buffer, @Nonnull Properties properties); + + /** + * Executes the plugin2 on the selection of resources stored in store. + * + * @param resources the set of resources that this plugin2 will run on. + * @param store + * @param properties plugin2 configuration properties. + */ + void executeOnStore(@Nonnull List resources, @Nonnull Store store, @Nonnull Properties properties); + + /** + * Returns true if the plugin2 needs to be executed exclusively + * (no other Executables will be executed at the same time until execution + * of this plugin2 finishes). + * @return true if the plugin2 needs to be executed exclusively. + */ + boolean isExclusive(); + + /** + * Returns the instance of Properties which can be used to + * reconfigure this plugin2 for specific execution. + * Note: Implementing class is responsible to clean changed properties + * after execution if needed. + * @return the instance of Properties. + */ + @Nonnull + Properties getProperties(); +} diff --git a/core/crce-repository-impl/osgi.bnd b/core/crce-repository-impl/osgi.bnd index 27d897d9..541a4a69 100644 --- a/core/crce-repository-impl/osgi.bnd +++ b/core/crce-repository-impl/osgi.bnd @@ -1,10 +1,10 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Export-Package: - -Embed-Dependency:\ - plexus-utils +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Export-Package: + +Embed-Dependency:\ + plexus-utils diff --git a/core/crce-repository-impl/pom.xml b/core/crce-repository-impl/pom.xml index dc50f4aa..e8b0b63a 100644 --- a/core/crce-repository-impl/pom.xml +++ b/core/crce-repository-impl/pom.xml @@ -1,116 +1,116 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-repository-impl - 2.2.0-SNAPSHOT - bundle - - CRCE - Core - Repository Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-repository-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.repository.filebased.impl - ${namespace}.repository.filebased - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - org.apache.felix - org.osgi.service.obr - - - - - - commons-io - commons-io - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-service-api - 3.0.0 - - - ${project.groupId} - crce-metadata-dao-api - 3.0.0-SNAPSHOT - - - ${project.groupId} - crce-plugin-api - 2.1.0 - - - ${project.groupId} - crce-repository-api - 2.2.0-SNAPSHOT - - - ${project.groupId} - crce-resolver-api - 2.2.0-SNAPSHOT - - - ${project.groupId} - crce-metadata-indexer-api - 2.1.0 - - - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-repository-impl + 2.2.0-SNAPSHOT + bundle + + CRCE - Core - Repository Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-repository-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.repository.filebased.impl + ${namespace}.repository.filebased + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + org.apache.felix + org.osgi.service.obr + + + + + + commons-io + commons-io + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-service-api + 3.0.0 + + + ${project.groupId} + crce-metadata-dao-api + 3.0.0-SNAPSHOT + + + ${project.groupId} + crce-plugin-api + 2.1.0 + + + ${project.groupId} + crce-repository-api + 2.2.0-SNAPSHOT + + + ${project.groupId} + crce-resolver-api + 2.2.0-SNAPSHOT + + + ${project.groupId} + crce-metadata-indexer-api + 2.1.0 + + + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/Activator.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/Activator.java index 5668fd58..d8935587 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/Activator.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/Activator.java @@ -1,189 +1,189 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Dictionary; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.felix.dm.Component; -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedServiceFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * Activator of this bundle. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase implements ManagedServiceFactory { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - public static final String PID = "cz.zcu.kiv.crce.repository.filebased"; - - public static final String CFG_PROPERTY__STORE_URI = "store.uri"; - - /** - * PID to component. - */ - private final Map components = new HashMap<>(); - /** - * PID to URI. - */ - private final Map uris = new HashMap<>(); - - private volatile DependencyManager dependencyManager; /* injected by dependency manager */ - - @Override - public void init(BundleContext bc, DependencyManager dm) throws Exception { - logger.debug("Initializing filebased repository."); - - Properties props = new Properties(); - props.put(Constants.SERVICE_PID, PID); - dm.add(createComponent() - .setInterface(ManagedServiceFactory.class.getName(), props) - .setImplementation(this) - ); - - dm.add(createComponent() - .setInterface(SessionRegister.class.getName(), null) - .setImplementation(SessionRegisterImpl.class) - ); - - dm.add(createComponent() - .setInterface(Plugin.class.getName(), null) - .setImplementation(PriorityActionHandler.class) - .add(createServiceDependency().setRequired(true).setService(PluginManager.class)) - ); - } - - @Override - public void destroy(BundleContext bc, DependencyManager dm) throws Exception { - for (Component component : components.values()) { - dependencyManager.remove(component); - } - logger.debug("Filebased repository destroyed."); - } - - @Override - public String getName() { - return "Filebased repository store factory."; - } - - @Override - public void updated(String pid, Dictionary properties) throws ConfigurationException { - logger.trace("ManagedServiceFactory updated with pid: {}", pid); - - if (properties == null) { - logger.warn("Repository ({}) configuration is empty!", pid); - return; - } - - logger.debug("Updating filebased repository ({}) configuration: {}", properties); - - String path = (String) properties.get(CFG_PROPERTY__STORE_URI); - - URI uri; - File file = null; - try { - uri = new URI(path); - if (uri.getScheme() == null) { - file = new File(path); - uri = file.toURI(); - } else if ("file".equals(uri.getScheme())) { - file = new File(uri); - } else { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Unsupported URI scheme for filebased repository: " + uri.getScheme()); - } - } catch (URISyntaxException ex) { - logger.warn("Invalid URI syntax: " + path, ex); - file = new File(path); - uri = file.toURI(); - } - - final String absolutePath = file.getAbsolutePath(); - - logger.debug("Repository URI: {}, file: {}", uri, absolutePath); - - if (!file.exists() && !file.mkdirs()) { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Can not create directory on the given path: " + path); - } - - if (!file.isDirectory()) { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Store URI is not a directory: " + path); - } - - for (Map.Entry entry : uris.entrySet()) { - if (entry.getValue().equals(absolutePath) && !entry.getKey().equals(pid)) { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, - "Another repository (PID: " + entry.getKey() + ") is already configured for this path: " + absolutePath); - } - } - - String oldPath = uris.get(pid); - if (oldPath != null) { - if (oldPath.equals(absolutePath)) { - logger.debug("Repository (PID: {}) is already configured for this path: {}", pid, absolutePath); - return; - } else { - deleted(pid); - } - } - - Properties props = new Properties(); - props.put("id", pid); - props.put("name", "Filebased: " + file.getName()); - - Component storeComponent = createComponent() - .setInterface(Store.class.getName(), props) - .setImplementation(new FilebasedStoreImpl(file)) -// .add(dependencyManager.createConfigurationDependency().setPid(pid).setPropagate(true)) - .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceDAO.class)) - .add(createServiceDependency().setRequired(true).setService(RepositoryDAO.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataValidator.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceLoader.class)) - .add(createServiceDependency().setRequired(true).setService(IdentityIndexer.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceIndexerService.class)) - .add(createServiceDependency().setRequired(true).setService(PluginManager.class)); - - logger.debug("Registering repository store: {}", storeComponent); - - uris.put(pid, absolutePath); - components.put(pid, storeComponent); - dependencyManager.add(storeComponent); - } - - @Override - public void deleted(String pid) { - Component storeComponent = components.remove(pid); - if (storeComponent != null) { - logger.debug("Unregistering repository store: {}", storeComponent); - - dependencyManager.remove(storeComponent); - uris.remove(pid); - } - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.felix.dm.Component; +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedServiceFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * Activator of this bundle. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase implements ManagedServiceFactory { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + public static final String PID = "cz.zcu.kiv.crce.repository.filebased"; + + public static final String CFG_PROPERTY__STORE_URI = "store.uri"; + + /** + * PID to component. + */ + private final Map components = new HashMap<>(); + /** + * PID to URI. + */ + private final Map uris = new HashMap<>(); + + private volatile DependencyManager dependencyManager; /* injected by dependency manager */ + + @Override + public void init(BundleContext bc, DependencyManager dm) throws Exception { + logger.debug("Initializing filebased repository."); + + Properties props = new Properties(); + props.put(Constants.SERVICE_PID, PID); + dm.add(createComponent() + .setInterface(ManagedServiceFactory.class.getName(), props) + .setImplementation(this) + ); + + dm.add(createComponent() + .setInterface(SessionRegister.class.getName(), null) + .setImplementation(SessionRegisterImpl.class) + ); + + dm.add(createComponent() + .setInterface(Plugin.class.getName(), null) + .setImplementation(PriorityActionHandler.class) + .add(createServiceDependency().setRequired(true).setService(PluginManager.class)) + ); + } + + @Override + public void destroy(BundleContext bc, DependencyManager dm) throws Exception { + for (Component component : components.values()) { + dependencyManager.remove(component); + } + logger.debug("Filebased repository destroyed."); + } + + @Override + public String getName() { + return "Filebased repository store factory."; + } + + @Override + public void updated(String pid, Dictionary properties) throws ConfigurationException { + logger.trace("ManagedServiceFactory updated with pid: {}", pid); + + if (properties == null) { + logger.warn("Repository ({}) configuration is empty!", pid); + return; + } + + logger.debug("Updating filebased repository ({}) configuration: {}", properties); + + String path = (String) properties.get(CFG_PROPERTY__STORE_URI); + + URI uri; + File file = null; + try { + uri = new URI(path); + if (uri.getScheme() == null) { + file = new File(path); + uri = file.toURI(); + } else if ("file".equals(uri.getScheme())) { + file = new File(uri); + } else { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Unsupported URI scheme for filebased repository: " + uri.getScheme()); + } + } catch (URISyntaxException ex) { + logger.warn("Invalid URI syntax: " + path, ex); + file = new File(path); + uri = file.toURI(); + } + + final String absolutePath = file.getAbsolutePath(); + + logger.debug("Repository URI: {}, file: {}", uri, absolutePath); + + if (!file.exists() && !file.mkdirs()) { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Can not create directory on the given path: " + path); + } + + if (!file.isDirectory()) { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Store URI is not a directory: " + path); + } + + for (Map.Entry entry : uris.entrySet()) { + if (entry.getValue().equals(absolutePath) && !entry.getKey().equals(pid)) { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, + "Another repository (PID: " + entry.getKey() + ") is already configured for this path: " + absolutePath); + } + } + + String oldPath = uris.get(pid); + if (oldPath != null) { + if (oldPath.equals(absolutePath)) { + logger.debug("Repository (PID: {}) is already configured for this path: {}", pid, absolutePath); + return; + } else { + deleted(pid); + } + } + + Properties props = new Properties(); + props.put("id", pid); + props.put("name", "Filebased: " + file.getName()); + + Component storeComponent = createComponent() + .setInterface(Store.class.getName(), props) + .setImplementation(new FilebasedStoreImpl(file)) +// .add(dependencyManager.createConfigurationDependency().setPid(pid).setPropagate(true)) + .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceDAO.class)) + .add(createServiceDependency().setRequired(true).setService(RepositoryDAO.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataValidator.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceLoader.class)) + .add(createServiceDependency().setRequired(true).setService(IdentityIndexer.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceIndexerService.class)) + .add(createServiceDependency().setRequired(true).setService(PluginManager.class)); + + logger.debug("Registering repository store: {}", storeComponent); + + uris.put(pid, absolutePath); + components.put(pid, storeComponent); + dependencyManager.add(storeComponent); + } + + @Override + public void deleted(String pid) { + Component storeComponent = components.remove(pid); + if (storeComponent != null) { + logger.debug("Unregistering repository store: {}", storeComponent); + + dependencyManager.remove(storeComponent); + uris.remove(pid); + } + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/BufferImpl.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/BufferImpl.java index 0e0fd7bd..2f186811 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/BufferImpl.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/BufferImpl.java @@ -1,410 +1,410 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import javax.annotation.Nonnull; - -import org.osgi.framework.BundleContext; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventConstants; -import org.osgi.service.event.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.plugins.ActionHandler; -import cz.zcu.kiv.crce.repository.plugins.Executable; - -/** - * Filebased implementation of Buffer. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class BufferImpl implements Buffer, EventHandler { - - // injected by dependency manager - private volatile BundleContext context; - private volatile PluginManager pluginManager; - private volatile Store store; - private volatile MetadataFactory metadataFactory; - private volatile ResourceDAO resourceDAO; - private volatile RepositoryDAO repositoryDAO; - private volatile ResourceIndexerService resourceIndexerService; - private volatile MetadataService metadataService; - private volatile MetadataValidator metadataValidator; - private volatile IdentityIndexer identityIndexer; - // injected by dependency manager - - private final int BUFFER_SIZE = 8 * 1024; - private final Dictionary sessionProperties; - - private File baseDir; - private Repository repository; - - private static final Logger logger = LoggerFactory.getLogger(BufferImpl.class); - - @SuppressWarnings("UseOfObsoleteCollectionType") - public BufferImpl(String sessionId) { - sessionProperties = new Hashtable<>(); - sessionProperties.put(SessionRegister.SERVICE_SESSION_ID, sessionId); - } - - /* - * Called by dependency manager - */ - @SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"}) - void init() { - Dictionary props = new Hashtable<>(); - props.put(EventConstants.EVENT_TOPIC, PluginManager.class.getName().replace(".", "/") + "/*"); - props.put(EventConstants.EVENT_FILTER, "(" + PluginManager.PROPERTY_PLUGIN_TYPES + "=*" + ResourceDAO.class.getName() + "*)"); - context.registerService(EventHandler.class.getName(), this, props); - - baseDir = context.getDataFile(sessionProperties.get(SessionRegister.SERVICE_SESSION_ID)); - if (!baseDir.exists()) { - if (!baseDir.mkdirs()) { - logger.error("Could not create buffer directory {}, session: {}", - baseDir, sessionProperties.get(SessionRegister.SERVICE_SESSION_ID)); - } - } else if (!baseDir.isDirectory()) { - throw new IllegalStateException("Base directory is not a directory: " + baseDir); - } - if (!baseDir.exists()) { - throw new IllegalStateException("Base directory for Buffer was not created: " + baseDir, new IOException("Can not create directory")); - } - } - - /* - * Called by dependency manager - */ - void start() { - try { - repository = repositoryDAO.loadRepository(baseDir.toURI()); - } catch (IOException ex) { - logger.error("Could not load repository for {}", baseDir, ex); - } - - if (repository == null) { - repository = metadataFactory.createRepository(baseDir.toURI()); - try { - repositoryDAO.saveRepository(repository); - } catch (IOException ex) { - logger.error("Could not save repository for {}", baseDir, ex); - } - } - } - - /* - * Called by dependency manager - */ - synchronized void stop() { -// m_repository = null; - for (File file : baseDir.listFiles()) { - if (!file.delete()) { - file.deleteOnExit(); - logger.warn("Can not delete file from destroyed buffer, deleteOnExit was set: {}", file); - } - } - if (!baseDir.delete()) { - baseDir.deleteOnExit(); - logger.warn("Can not delete file from destroyed buffer's base dir, deleteOnExit was set: {}", baseDir); - } - } - - - @Override - public void handleEvent(final Event event) { -// final Object lock = this; -// new Thread(new Runnable() { -// -// @Override -// public void run() { -// synchronized (lock) { -// m_repository = null; -// } -// } -// }).start(); -// } - -// private synchronized void loadRepository() { -// RepositoryDAO rd = m_pluginManager.getPlugin(RepositoryDAO.class); -// -// try { -// m_repository = rd.getRepository(m_baseDir.toURI()); -// } catch (IOException ex) { -// logger.error("Could not get repository for URI: {}", m_baseDir.toURI(), ex); -// m_repository = m_pluginManager.getPlugin(MetadataFactory.class).createRepository(m_baseDir.toURI()); -// } - } - - @Override - public Resource put(Resource resource) throws IOException, RefusedArtifactException { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public synchronized Resource put(String name, InputStream artifact) throws IOException, RefusedArtifactException { - String name2 = pluginManager.getPlugin(ActionHandler.class).beforeUploadToBuffer(name, this); - if (name2 == null || artifact == null || "".equals(name2)) { - throw new RefusedArtifactException("No file name was given on uploading to buffer"); - } - - File file = File.createTempFile("res", ".tmp", baseDir); - try (FileOutputStream output = new FileOutputStream(file)) { - byte[] buffer = new byte[BUFFER_SIZE]; - for (int count = artifact.read(buffer); count != -1; count = artifact.read(buffer)) { - output.write(buffer, 0, count); - } - } - -// Resource resource = resourceDAO.loadResource(file.toURI()); - Resource resource = null; - if (resource == null) { - resource = resourceIndexerService.indexResource(file); - } - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - - identityIndexer.preIndex(file, name2, resource); - - String presentationName = metadataService.getPresentationName(resource); - if (presentationName.trim().isEmpty() || presentationName.startsWith("unknown-name:")) { - metadataService.setPresentationName(resource, name2); - } - - Resource tmp; - try { - tmp = pluginManager.getPlugin(ActionHandler.class).onUploadToBuffer(resource, this, name2); - } catch (RefusedArtifactException e) { - if (!file.delete()) { - logger.error( "Can not delete file of revoked artifact: {}", file.getPath()); - } - throw e; - } - - identityIndexer.postIndex(file, resource); - - if (tmp == null) { - logger.error( "ActionHandler onUploadToBuffer returned null resource, using original"); - } else { - resource = tmp; - } - - ResourceValidationResult validationResult = metadataValidator.validate(resource); - if (!validationResult.isContextValid()) { - logger.error("Uploaded Resource {} is not valid:\r\n{}", resource.getId(), validationResult); - throw new RefusedArtifactException("Resource is not valid."); - } - - logger.info("Uploaded resource {} is valid.", resource.getId()); - - metadataService.getIdentity(resource).setAttribute("status", String.class, "buffered"); - - resourceDAO.saveResource(resource); - - return pluginManager.getPlugin(ActionHandler.class).afterUploadToBuffer(resource, this, name2); - } - - @Override - public synchronized boolean remove(Resource resource) throws IOException { - resource = pluginManager.getPlugin(ActionHandler.class).beforeDeleteFromBuffer(resource, this); - - if (!isInBuffer(resource)) { - // TODO is this logic correct with new API? -// if (m_ResourceDAO.existsResource(LegacyMetadataHelper.getUri(resource))) { -// logger.warn( "Resource to be removed is not in buffer but it is in internal repository: {}, cleaning up", resource.getId()); -// m_ResourceDAO.deleteResource(LegacyMetadataHelper.getUri(resource)); -// } - return false; - } - - // if URI scheme is not 'file', it is detected in previous isInBuffer() check - File file = new File(metadataService.getUri(resource)); - if (!file.delete()) { - throw new IOException("Can not delete artifact file from buffer: " + metadataService.getUri(resource)); - } - -// ResourceDAO resourceDao = m_pluginManager.getPlugin(ResourceDAO.class); -// try { - resourceDAO.deleteResource(metadataService.getUri(resource)); -// } finally { - // once the artifact file was removed, the resource has to be removed - // from the repository even in case of exception on removing metadata - // to keep consistency of repository with stored artifact files -// if (m_repository == null) { -// loadRepository(); -// } -// if (!m_repository.removeResource(resource)) { -// logger.warn("Buffer's internal repository does not contain removing resource: {}", resource.getId()); -// } -// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); -// } - - pluginManager.getPlugin(ActionHandler.class).afterDeleteFromBuffer(resource, this); - - return true; - } - - @Override - public synchronized List commit(boolean move) throws IOException { - List resources = resourceDAO.loadResources(repository); - List resourcesToCommit = pluginManager.getPlugin(ActionHandler.class).beforeBufferCommit(resources, this, store); - - List commitedResources = new ArrayList<>(); - List resourcesToRemove = new ArrayList<>(); - - // put resources to store - if (move && store instanceof FilebasedStoreImpl) { - for (Resource resource : resourcesToCommit) { - Resource commitedResource; - try { - resourcesToRemove.add(metadataService.getUri(resource)); - commitedResource = ((FilebasedStoreImpl) store).move(resource); - } catch (RefusedArtifactException ex) { - logger.info( "Resource can not be commited, it was revoked by store: {}", resource.getId(), ex); - continue; - } - commitedResources.add(commitedResource); - } - } else { - for (Resource resource : resourcesToCommit) { - Resource putResource; - URI uri = metadataService.getUri(resource); - try { - putResource = store.put(resource); - } catch (RefusedArtifactException ex) { - logger.info( "Resource can not be commited, it was revoked by store: {}", resource.getId(), ex); - continue; - } - commitedResources.add(putResource); - if (move) { - resourcesToRemove.add(uri); - } - } - } - - // remove resources from buffer - if (move) { - for (URI resource : resourcesToRemove) { - File resourceFile = new File(resource); - if (resourceFile.exists() && !resourceFile.delete()) { - logger.error( "Can not delete artifact from buffer: {}", resource); - continue; - } - try { - resourceDAO.deleteResource(resource); - } catch (IOException e) { - // once the artifact file was removed, the resource has to be removed - // from the repository even in case of exception on removing metadata - // to keep consistency of repository with stored artifact files -// if (!m_repository.removeResource(resource)) { -// // cleanup (after renamed resource) -// Resource fake = m_metadataFactory.createResource(); -// fake.setSymbolicName(toRemoveNonrenamed.get(resource.getId())[0]); -// fake.setVersion(toRemoveNonrenamed.get(resource.getId())[1]); -// if (!m_repository.removeResource(fake)) { -// logger.warn( "Buffer's internal repository does not contain removing resource: {}", resource.getId()); -// } -// } -// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); - throw e; - } -// if (!m_repository.removeResource(resource)) { -// // cleanup (after renamed resource) -// Resource fake = m_metadataFactory.createResource(); -// fake.setSymbolicName(toRemoveNonrenamed.get(resource.getId())[0]); -// fake.setVersion(toRemoveNonrenamed.get(resource.getId())[1]); -// if (!m_repository.removeResource(fake)) { -// logger.warn("Buffer's internal repository does not contain removing resource: {}", resource.getId()); -// } -// } - } -// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); - } - - pluginManager.getPlugin(ActionHandler.class).afterBufferCommit(commitedResources, this, store); - - return commitedResources; - } - - @Override - public List commit(List resources, boolean move) throws IOException { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public synchronized void execute(List resources, final Executable executable, final Properties properties) { - final ActionHandler ah = pluginManager.getPlugin(ActionHandler.class); - final List res = ah.beforeExecuteInBuffer(resources, executable, properties, this); - final Buffer buffer = this; - - new Thread(new Runnable() { - - @Override - public void run() { - try { - executable.executeOnBuffer(res, store, buffer, properties); - } catch (Exception e) { - logger.error( "Executable plugin threw an exception while executed in buffer: {}", executable.getPluginDescription(), e); - } - ah.afterExecuteInBuffer(res, executable, properties, buffer); - } - }).start(); - } - - Dictionary getSessionProperties() { - return sessionProperties; - } - - @Override - public List getResources() { - try { - return resourceDAO.loadResources(repository); - } catch (IOException e) { - logger.error("Could not load resources of repository {}.", baseDir.toURI(), e); - } - return Collections.emptyList(); - } - - @Override - public List getResources(Requirement requirement) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Nonnull - @Override - public List getResources(Set requirement) { - throw new UnsupportedOperationException("Not supported yet."); - } - - private boolean isInBuffer(Resource resource) { - URI uri = metadataService.getUri(resource).normalize(); - if (!"file".equals(uri.getScheme())) { - return false; - } - return new File(uri).getPath().startsWith(baseDir.getAbsolutePath()); - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import javax.annotation.Nonnull; + +import org.osgi.framework.BundleContext; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventConstants; +import org.osgi.service.event.EventHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.repository.plugins.ActionHandler; +import cz.zcu.kiv.crce.repository.plugins.Executable; + +/** + * Filebased implementation of Buffer. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class BufferImpl implements Buffer, EventHandler { + + // injected by dependency manager + private volatile BundleContext context; + private volatile PluginManager pluginManager; + private volatile Store store; + private volatile MetadataFactory metadataFactory; + private volatile ResourceDAO resourceDAO; + private volatile RepositoryDAO repositoryDAO; + private volatile ResourceIndexerService resourceIndexerService; + private volatile MetadataService metadataService; + private volatile MetadataValidator metadataValidator; + private volatile IdentityIndexer identityIndexer; + // injected by dependency manager + + private final int BUFFER_SIZE = 8 * 1024; + private final Dictionary sessionProperties; + + private File baseDir; + private Repository repository; + + private static final Logger logger = LoggerFactory.getLogger(BufferImpl.class); + + @SuppressWarnings("UseOfObsoleteCollectionType") + public BufferImpl(String sessionId) { + sessionProperties = new Hashtable<>(); + sessionProperties.put(SessionRegister.SERVICE_SESSION_ID, sessionId); + } + + /* + * Called by dependency manager + */ + @SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"}) + void init() { + Dictionary props = new Hashtable<>(); + props.put(EventConstants.EVENT_TOPIC, PluginManager.class.getName().replace(".", "/") + "/*"); + props.put(EventConstants.EVENT_FILTER, "(" + PluginManager.PROPERTY_PLUGIN_TYPES + "=*" + ResourceDAO.class.getName() + "*)"); + context.registerService(EventHandler.class.getName(), this, props); + + baseDir = context.getDataFile(sessionProperties.get(SessionRegister.SERVICE_SESSION_ID)); + if (!baseDir.exists()) { + if (!baseDir.mkdirs()) { + logger.error("Could not create buffer directory {}, session: {}", + baseDir, sessionProperties.get(SessionRegister.SERVICE_SESSION_ID)); + } + } else if (!baseDir.isDirectory()) { + throw new IllegalStateException("Base directory is not a directory: " + baseDir); + } + if (!baseDir.exists()) { + throw new IllegalStateException("Base directory for Buffer was not created: " + baseDir, new IOException("Can not create directory")); + } + } + + /* + * Called by dependency manager + */ + void start() { + try { + repository = repositoryDAO.loadRepository(baseDir.toURI()); + } catch (IOException ex) { + logger.error("Could not load repository for {}", baseDir, ex); + } + + if (repository == null) { + repository = metadataFactory.createRepository(baseDir.toURI()); + try { + repositoryDAO.saveRepository(repository); + } catch (IOException ex) { + logger.error("Could not save repository for {}", baseDir, ex); + } + } + } + + /* + * Called by dependency manager + */ + synchronized void stop() { +// m_repository = null; + for (File file : baseDir.listFiles()) { + if (!file.delete()) { + file.deleteOnExit(); + logger.warn("Can not delete file from destroyed buffer, deleteOnExit was set: {}", file); + } + } + if (!baseDir.delete()) { + baseDir.deleteOnExit(); + logger.warn("Can not delete file from destroyed buffer's base dir, deleteOnExit was set: {}", baseDir); + } + } + + + @Override + public void handleEvent(final Event event) { +// final Object lock = this; +// new Thread(new Runnable() { +// +// @Override +// public void run() { +// synchronized (lock) { +// m_repository = null; +// } +// } +// }).start(); +// } + +// private synchronized void loadRepository() { +// RepositoryDAO rd = m_pluginManager.getPlugin(RepositoryDAO.class); +// +// try { +// m_repository = rd.getRepository(m_baseDir.toURI()); +// } catch (IOException ex) { +// logger.error("Could not get repository for URI: {}", m_baseDir.toURI(), ex); +// m_repository = m_pluginManager.getPlugin(MetadataFactory.class).createRepository(m_baseDir.toURI()); +// } + } + + @Override + public Resource put(Resource resource) throws IOException, RefusedArtifactException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public synchronized Resource put(String name, InputStream artifact) throws IOException, RefusedArtifactException { + String name2 = pluginManager.getPlugin(ActionHandler.class).beforeUploadToBuffer(name, this); + if (name2 == null || artifact == null || "".equals(name2)) { + throw new RefusedArtifactException("No file name was given on uploading to buffer"); + } + + File file = File.createTempFile("res", ".tmp", baseDir); + try (FileOutputStream output = new FileOutputStream(file)) { + byte[] buffer = new byte[BUFFER_SIZE]; + for (int count = artifact.read(buffer); count != -1; count = artifact.read(buffer)) { + output.write(buffer, 0, count); + } + } + +// Resource resource = resourceDAO.loadResource(file.toURI()); + Resource resource = null; + if (resource == null) { + resource = resourceIndexerService.indexResource(file); + } + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + + identityIndexer.preIndex(file, name2, resource); + + String presentationName = metadataService.getPresentationName(resource); + if (presentationName.trim().isEmpty() || presentationName.startsWith("unknown-name:")) { + metadataService.setPresentationName(resource, name2); + } + + Resource tmp; + try { + tmp = pluginManager.getPlugin(ActionHandler.class).onUploadToBuffer(resource, this, name2); + } catch (RefusedArtifactException e) { + if (!file.delete()) { + logger.error( "Can not delete file of revoked artifact: {}", file.getPath()); + } + throw e; + } + + identityIndexer.postIndex(file, resource); + + if (tmp == null) { + logger.error( "ActionHandler onUploadToBuffer returned null resource, using original"); + } else { + resource = tmp; + } + + ResourceValidationResult validationResult = metadataValidator.validate(resource); + if (!validationResult.isContextValid()) { + logger.error("Uploaded Resource {} is not valid:\r\n{}", resource.getId(), validationResult); + throw new RefusedArtifactException("Resource is not valid."); + } + + logger.info("Uploaded resource {} is valid.", resource.getId()); + + metadataService.getIdentity(resource).setAttribute("status", String.class, "buffered"); + + resourceDAO.saveResource(resource); + + return pluginManager.getPlugin(ActionHandler.class).afterUploadToBuffer(resource, this, name2); + } + + @Override + public synchronized boolean remove(Resource resource) throws IOException { + resource = pluginManager.getPlugin(ActionHandler.class).beforeDeleteFromBuffer(resource, this); + + if (!isInBuffer(resource)) { + // TODO is this logic correct with new API? +// if (m_ResourceDAO.existsResource(LegacyMetadataHelper.getUri(resource))) { +// logger.warn( "Resource to be removed is not in buffer but it is in internal repository: {}, cleaning up", resource.getId()); +// m_ResourceDAO.deleteResource(LegacyMetadataHelper.getUri(resource)); +// } + return false; + } + + // if URI scheme is not 'file', it is detected in previous isInBuffer() check + File file = new File(metadataService.getUri(resource)); + if (!file.delete()) { + throw new IOException("Can not delete artifact file from buffer: " + metadataService.getUri(resource)); + } + +// ResourceDAO resourceDao = m_pluginManager.getPlugin(ResourceDAO.class); +// try { + resourceDAO.deleteResource(metadataService.getUri(resource)); +// } finally { + // once the artifact file was removed, the resource has to be removed + // from the repository even in case of exception on removing metadata + // to keep consistency of repository with stored artifact files +// if (m_repository == null) { +// loadRepository(); +// } +// if (!m_repository.removeResource(resource)) { +// logger.warn("Buffer's internal repository does not contain removing resource: {}", resource.getId()); +// } +// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); +// } + + pluginManager.getPlugin(ActionHandler.class).afterDeleteFromBuffer(resource, this); + + return true; + } + + @Override + public synchronized List commit(boolean move) throws IOException { + List resources = resourceDAO.loadResources(repository); + List resourcesToCommit = pluginManager.getPlugin(ActionHandler.class).beforeBufferCommit(resources, this, store); + + List commitedResources = new ArrayList<>(); + List resourcesToRemove = new ArrayList<>(); + + // put resources to store + if (move && store instanceof FilebasedStoreImpl) { + for (Resource resource : resourcesToCommit) { + Resource commitedResource; + try { + resourcesToRemove.add(metadataService.getUri(resource)); + commitedResource = ((FilebasedStoreImpl) store).move(resource); + } catch (RefusedArtifactException ex) { + logger.info( "Resource can not be commited, it was revoked by store: {}", resource.getId(), ex); + continue; + } + commitedResources.add(commitedResource); + } + } else { + for (Resource resource : resourcesToCommit) { + Resource putResource; + URI uri = metadataService.getUri(resource); + try { + putResource = store.put(resource); + } catch (RefusedArtifactException ex) { + logger.info( "Resource can not be commited, it was revoked by store: {}", resource.getId(), ex); + continue; + } + commitedResources.add(putResource); + if (move) { + resourcesToRemove.add(uri); + } + } + } + + // remove resources from buffer + if (move) { + for (URI resource : resourcesToRemove) { + File resourceFile = new File(resource); + if (resourceFile.exists() && !resourceFile.delete()) { + logger.error( "Can not delete artifact from buffer: {}", resource); + continue; + } + try { + resourceDAO.deleteResource(resource); + } catch (IOException e) { + // once the artifact file was removed, the resource has to be removed + // from the repository even in case of exception on removing metadata + // to keep consistency of repository with stored artifact files +// if (!m_repository.removeResource(resource)) { +// // cleanup (after renamed resource) +// Resource fake = m_metadataFactory.createResource(); +// fake.setSymbolicName(toRemoveNonrenamed.get(resource.getId())[0]); +// fake.setVersion(toRemoveNonrenamed.get(resource.getId())[1]); +// if (!m_repository.removeResource(fake)) { +// logger.warn( "Buffer's internal repository does not contain removing resource: {}", resource.getId()); +// } +// } +// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); + throw e; + } +// if (!m_repository.removeResource(resource)) { +// // cleanup (after renamed resource) +// Resource fake = m_metadataFactory.createResource(); +// fake.setSymbolicName(toRemoveNonrenamed.get(resource.getId())[0]); +// fake.setVersion(toRemoveNonrenamed.get(resource.getId())[1]); +// if (!m_repository.removeResource(fake)) { +// logger.warn("Buffer's internal repository does not contain removing resource: {}", resource.getId()); +// } +// } + } +// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); + } + + pluginManager.getPlugin(ActionHandler.class).afterBufferCommit(commitedResources, this, store); + + return commitedResources; + } + + @Override + public List commit(List resources, boolean move) throws IOException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public synchronized void execute(List resources, final Executable executable, final Properties properties) { + final ActionHandler ah = pluginManager.getPlugin(ActionHandler.class); + final List res = ah.beforeExecuteInBuffer(resources, executable, properties, this); + final Buffer buffer = this; + + new Thread(new Runnable() { + + @Override + public void run() { + try { + executable.executeOnBuffer(res, store, buffer, properties); + } catch (Exception e) { + logger.error( "Executable plugin2 threw an exception while executed in buffer: {}", executable.getPluginDescription(), e); + } + ah.afterExecuteInBuffer(res, executable, properties, buffer); + } + }).start(); + } + + Dictionary getSessionProperties() { + return sessionProperties; + } + + @Override + public List getResources() { + try { + return resourceDAO.loadResources(repository); + } catch (IOException e) { + logger.error("Could not load resources of repository {}.", baseDir.toURI(), e); + } + return Collections.emptyList(); + } + + @Override + public List getResources(Requirement requirement) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Nonnull + @Override + public List getResources(Set requirement) { + throw new UnsupportedOperationException("Not supported yet."); + } + + private boolean isInBuffer(Resource resource) { + URI uri = metadataService.getUri(resource).normalize(); + if (!"file".equals(uri.getScheme())) { + return false; + } + return new File(uri).getPath().startsWith(baseDir.getAbsolutePath()); + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/FilebasedStoreImpl.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/FilebasedStoreImpl.java index 582cb364..3e6d46d2 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/FilebasedStoreImpl.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/FilebasedStoreImpl.java @@ -1,367 +1,367 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.Collections; -import java.util.Dictionary; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import javax.annotation.Nonnull; - -import org.apache.commons.io.FileUtils; -import org.osgi.framework.BundleContext; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventConstants; -import org.osgi.service.event.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.plugins.ActionHandler; -import cz.zcu.kiv.crce.repository.plugins.Executable; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * Filebased implementation of Store. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class FilebasedStoreImpl implements Store, EventHandler { - - private volatile BundleContext context; - private volatile PluginManager pluginManager; - private volatile ResourceDAO resourceDAO; - private volatile RepositoryDAO repositoryDAO; - private volatile ResourceIndexerService resourceIndexerService; - private volatile MetadataFactory metadataFactory; - private volatile MetadataService metadataService; // NOPMD - private volatile MetadataValidator metadataValidator; - private volatile ResourceLoader resourceLoader; - private volatile IdentityIndexer identityIndexer; - - private static final Logger logger = LoggerFactory.getLogger(FilebasedStoreImpl.class); - - private Repository repository; - private final File baseDir; - - - public FilebasedStoreImpl(File baseDir) { - this.baseDir = baseDir; - } - - /* - * Called by dependency manager. - */ - @SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"}) - void init() { - Dictionary props = new java.util.Hashtable<>(); - props.put(EventConstants.EVENT_TOPIC, PluginManager.class.getName().replace(".", "/") + "/*"); - props.put(EventConstants.EVENT_FILTER, "(" + PluginManager.PROPERTY_PLUGIN_TYPES + "=*" + ResourceDAO.class.getName() + "*)"); - context.registerService(EventHandler.class.getName(), this, props); - } - - /* - * Called by dependency manager. - */ - synchronized void start() { - try { - repository = repositoryDAO.loadRepository(baseDir.toURI()); - } catch (IOException ex) { - logger.error("Could not load repository for {}", baseDir, ex); - } - - if (repository == null) { - repository = metadataFactory.createRepository(baseDir.toURI()); - try { - repositoryDAO.saveRepository(repository); - } catch (IOException ex) { - logger.error("Could not save repository for {}", baseDir, ex); - } - } - - final Object lock = this; - new Thread(new Runnable() { - - @Override - public void run() { - synchronized (lock) { - indexResources(baseDir, repository); - } - } - }).start(); - - } - - void stop() { - logger.info("Stopping DM component {}", this); - } - - @Override - public void handleEvent(final Event event) { - // TODO why was that there? -// final Object lock = this; -// new Thread(new Runnable() { -// -// @Override -// public void run() { -// synchronized (lock) { -// m_repository = null; -// } -// } -// }).start(); - } - -// private synchronized void loadRepository() { -// RepositoryDAO rd = m_pluginManager.getPlugin(RepositoryDAO.class); -// -// try { -// m_repository = rd.getRepository(m_baseDir.toURI()); -// } catch (IOException ex) { -// logger.error("Could not get repository for URI: " + m_baseDir.toURI(), ex); -// m_repository = m_pluginManager.getPlugin(ResourceCreator.class).createRepository(m_baseDir.toURI()); -// } -// } - - public synchronized Resource move(Resource resource) throws IOException, RefusedArtifactException { - return putInternal(resource, true); - } - - @Override - public synchronized Resource put(Resource resource) throws IOException, RefusedArtifactException { - return putInternal(resource, false); - } - - private Resource putInternal(Resource resource, boolean move) throws IOException, RefusedArtifactException { - Resource tmp = pluginManager.getPlugin(ActionHandler.class).beforePutToStore(resource, this); - if (resource == null) { - return null; - } - if (tmp == null) { - logger.error( "ActionHandler onPutToStore returned null resource, using original"); - } else { - resource = tmp; - } - - if (resourceDAO.existsResource(metadataService.getUri(resource), repository)) { - throw new RefusedArtifactException("Resource with the same symbolic name and version already exists in Store: " + resource.getId()); - } - if ("file".equals(metadataService.getUri(resource).getScheme())) { - resource = putFileResource(resource, move); - } else { - resource = putNonFileResource(resource, move); - } - return pluginManager.getPlugin(ActionHandler.class).afterPutToStore(resource, this); - } - - private synchronized Resource putFileResource(Resource resource, boolean move) throws IOException, RefusedArtifactException { - File sourceFile = new File(metadataService.getUri(resource)); - if (!sourceFile.exists()) { - throw new RefusedArtifactException("File to be put tu store does not exist: " + sourceFile.getPath()); - } - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - - File targetFile = new File(baseDir, resource.getId()); - - if (move) { - FileUtils.moveFile(sourceFile, targetFile); - } else { - FileUtils.copyFile(sourceFile, targetFile); - } -// Resource out = resourceDAO.moveResource(resource, targetFile.toURI()); - metadataService.setUri(resource, targetFile.toURI().normalize()); -// if (!m_repository.addResource(out)) { -// logger.warn( "Resource with the same symbolic name and version already exists in Store, but it has not been expected: {}", targetFile.getPath()); -// if (!targetFile.delete()) { -// throw new IOException("Can not delete file of revoked artifact: " + targetFile.getPath()); -// } -// return null; -// } - - ResourceValidationResult validationResult = metadataValidator.validate(resource); - if (!validationResult.isContextValid()) { - logger.error("Saved Resource {} is not valid:\r\n{}", resource.getId(), validationResult); - throw new RefusedArtifactException("Resource is not valid."); - } - - logger.info("Saved resource {} is valid.", resource.getId()); - - metadataService.getIdentity(resource).setAttribute("status", String.class, "stored"); - - resourceDAO.saveResource(resource); // TODO is saving necessary after move? define exact contract - -// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); - - return resource; - } - - private Resource putNonFileResource(Resource resource, boolean move) { - throw new UnsupportedOperationException("Put resource from another URI than file not supported yet: " - + resource.getId() + ": " + metadataService.getUri(resource) + ", move: " + move); - } - - @Override - public synchronized boolean remove(Resource resource) throws IOException { - resource = pluginManager.getPlugin(ActionHandler.class).beforeDeleteFromStore(resource, this); - - if (!isInStore(resource)) { - if (resourceDAO.existsResource(metadataService.getUri(resource))) { - logger.warn( "Removing resource is not in store but it is in internal repository: {}", resource.getId()); - resourceDAO.deleteResource(metadataService.getUri(resource)); - } - pluginManager.getPlugin(ActionHandler.class).afterDeleteFromStore(resource, this); - return false; - } - - // if URI scheme is not 'file', it is detected in previous isInStore() check - File file = new File(metadataService.getUri(resource)); - if (!file.delete()) { - throw new IOException("Can not delete artifact file from store: " + metadataService.getUri(resource)); - } - -// ResourceDAO resourceDao = m_pluginManager.getPlugin(ResourceDAO.class); -// try { - resourceDAO.deleteResource(metadataService.getUri(resource)); -// } finally { - // once the artifact file was removed, the resource has to be removed - // from the repository even in case of exception on removing metadata - // to keep consistency of repository with stored artifact files -// if (m_repository == null) { -// loadRepository(); -// } -// if (!m_ResourceDAO.deleteResource(LegacyMetadataHelper.getUri(resource))) { -// logger.warn( "Store's internal repository does not contain removing resource: {}", resource.getId()); -// } -// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); -// } - pluginManager.getPlugin(ActionHandler.class).afterDeleteFromStore(resource, this); - return true; - } - - @Override - public synchronized void execute(List resources, final Executable executable, final Properties properties) { - final ActionHandler ah = pluginManager.getPlugin(ActionHandler.class); - final List res = ah.beforeExecuteInStore(resources, executable, properties, this); - final Store store = this; - - new Thread(new Runnable() { - - @Override - public void run() { - try { - executable.executeOnStore(res, store, properties); - } catch (Exception e) { - logger.error( "Executable plugin threw an exception while executed in buffer: {}", executable.getPluginDescription(), e); - } - ah.afterExecuteInStore(res, executable, properties, store); - } - }).start(); - } - - @Override - public synchronized List getResources() { - try { - return resourceDAO.loadResources(repository); - } catch (IOException e) { - logger.error("Could not load resources of repository {}.", baseDir.toURI(), e); - } - return Collections.emptyList(); - } - - @Override - public synchronized List getResources(Requirement requirement) { - return getResources(Collections.singleton(requirement)); - } - - @Nonnull - @Override - public synchronized List getResources(Set requirement) { - List resources = Collections.emptyList(); - try { - resources = resourceLoader.getResources(repository, requirement); - } catch (IOException e) { - logger.error("Could not load resources for requirement ({})", requirement.toString()); - logger.error(e.getMessage(), e); - } - - if (logger.isDebugEnabled()) { - logger.debug("getResources(requirement={}) returns {}", requirement.toString(), resources.size()); - } - return resources; - } - - private boolean isInStore(Resource resource) { - URI uri = metadataService.getUri(resource).normalize(); - if (!"file".equals(uri.getScheme())) { - return false; - } - return new File(uri).getPath().startsWith(baseDir.getAbsolutePath()); - } - - @Override - public String toString() { - return "FilebasedStoreImpl{" + "baseDir=" + baseDir + '}'; - } - - private void indexResources(File baseDir, Repository repository) { - indexDirectory(baseDir, repository); - if (logger.isDebugEnabled()) { - logger.debug("Indexing done for store directory: {}", baseDir.getAbsolutePath()); - } - } - - private void indexDirectory(File directory, Repository repository) { - for (File file : directory.listFiles()) { - if (file.isFile()) { - try { - if ("repository.xml".equals(file.getName())) { - continue; - } - if (resourceIndexerService != null && !resourceDAO.existsResource(file.toURI())) { - Resource resource; - try { - resource = resourceIndexerService.indexResource(file); - } catch (IOException e) { - logger.error("Could not index file {}", file, e); - continue; - } - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - - identityIndexer.preIndex(file, file.getName(), resource); - identityIndexer.postIndex(file, resource); - - ResourceValidationResult validationResult = metadataValidator.validate(resource); - if (!validationResult.isContextValid()) { - logger.error("Indexed Resource {} is not valid:\r\n{}", resource.getId(), validationResult); - continue; - } - logger.info("Indexed resource {} is valid.", resource.getId()); - - try { - resourceDAO.saveResource(resource); - } catch (IOException e) { - logger.error("Could not save indexed resource for file {}: {}", file, resource, e); - } - } - } catch (IOException e) { - logger.error("Could not check that resource exists: {}", file, e); - } - } else if (file.isDirectory()) { - indexDirectory(file, repository); - } - } - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.Collections; +import java.util.Dictionary; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import javax.annotation.Nonnull; + +import org.apache.commons.io.FileUtils; +import org.osgi.framework.BundleContext; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventConstants; +import org.osgi.service.event.EventHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.repository.plugins.ActionHandler; +import cz.zcu.kiv.crce.repository.plugins.Executable; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * Filebased implementation of Store. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class FilebasedStoreImpl implements Store, EventHandler { + + private volatile BundleContext context; + private volatile PluginManager pluginManager; + private volatile ResourceDAO resourceDAO; + private volatile RepositoryDAO repositoryDAO; + private volatile ResourceIndexerService resourceIndexerService; + private volatile MetadataFactory metadataFactory; + private volatile MetadataService metadataService; // NOPMD + private volatile MetadataValidator metadataValidator; + private volatile ResourceLoader resourceLoader; + private volatile IdentityIndexer identityIndexer; + + private static final Logger logger = LoggerFactory.getLogger(FilebasedStoreImpl.class); + + private Repository repository; + private final File baseDir; + + + public FilebasedStoreImpl(File baseDir) { + this.baseDir = baseDir; + } + + /* + * Called by dependency manager. + */ + @SuppressWarnings({"UseOfObsoleteCollectionType", "unchecked"}) + void init() { + Dictionary props = new java.util.Hashtable<>(); + props.put(EventConstants.EVENT_TOPIC, PluginManager.class.getName().replace(".", "/") + "/*"); + props.put(EventConstants.EVENT_FILTER, "(" + PluginManager.PROPERTY_PLUGIN_TYPES + "=*" + ResourceDAO.class.getName() + "*)"); + context.registerService(EventHandler.class.getName(), this, props); + } + + /* + * Called by dependency manager. + */ + synchronized void start() { + try { + repository = repositoryDAO.loadRepository(baseDir.toURI()); + } catch (IOException ex) { + logger.error("Could not load repository for {}", baseDir, ex); + } + + if (repository == null) { + repository = metadataFactory.createRepository(baseDir.toURI()); + try { + repositoryDAO.saveRepository(repository); + } catch (IOException ex) { + logger.error("Could not save repository for {}", baseDir, ex); + } + } + + final Object lock = this; + new Thread(new Runnable() { + + @Override + public void run() { + synchronized (lock) { + indexResources(baseDir, repository); + } + } + }).start(); + + } + + void stop() { + logger.info("Stopping DM component {}", this); + } + + @Override + public void handleEvent(final Event event) { + // TODO why was that there? +// final Object lock = this; +// new Thread(new Runnable() { +// +// @Override +// public void run() { +// synchronized (lock) { +// m_repository = null; +// } +// } +// }).start(); + } + +// private synchronized void loadRepository() { +// RepositoryDAO rd = m_pluginManager.getPlugin(RepositoryDAO.class); +// +// try { +// m_repository = rd.getRepository(m_baseDir.toURI()); +// } catch (IOException ex) { +// logger.error("Could not get repository for URI: " + m_baseDir.toURI(), ex); +// m_repository = m_pluginManager.getPlugin(ResourceCreator.class).createRepository(m_baseDir.toURI()); +// } +// } + + public synchronized Resource move(Resource resource) throws IOException, RefusedArtifactException { + return putInternal(resource, true); + } + + @Override + public synchronized Resource put(Resource resource) throws IOException, RefusedArtifactException { + return putInternal(resource, false); + } + + private Resource putInternal(Resource resource, boolean move) throws IOException, RefusedArtifactException { + Resource tmp = pluginManager.getPlugin(ActionHandler.class).beforePutToStore(resource, this); + if (resource == null) { + return null; + } + if (tmp == null) { + logger.error( "ActionHandler onPutToStore returned null resource, using original"); + } else { + resource = tmp; + } + + if (resourceDAO.existsResource(metadataService.getUri(resource), repository)) { + throw new RefusedArtifactException("Resource with the same symbolic name and version already exists in Store: " + resource.getId()); + } + if ("file".equals(metadataService.getUri(resource).getScheme())) { + resource = putFileResource(resource, move); + } else { + resource = putNonFileResource(resource, move); + } + return pluginManager.getPlugin(ActionHandler.class).afterPutToStore(resource, this); + } + + private synchronized Resource putFileResource(Resource resource, boolean move) throws IOException, RefusedArtifactException { + File sourceFile = new File(metadataService.getUri(resource)); + if (!sourceFile.exists()) { + throw new RefusedArtifactException("File to be put tu store does not exist: " + sourceFile.getPath()); + } + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + + File targetFile = new File(baseDir, resource.getId()); + + if (move) { + FileUtils.moveFile(sourceFile, targetFile); + } else { + FileUtils.copyFile(sourceFile, targetFile); + } +// Resource out = resourceDAO.moveResource(resource, targetFile.toURI()); + metadataService.setUri(resource, targetFile.toURI().normalize()); +// if (!m_repository.addResource(out)) { +// logger.warn( "Resource with the same symbolic name and version already exists in Store, but it has not been expected: {}", targetFile.getPath()); +// if (!targetFile.delete()) { +// throw new IOException("Can not delete file of revoked artifact: " + targetFile.getPath()); +// } +// return null; +// } + + ResourceValidationResult validationResult = metadataValidator.validate(resource); + if (!validationResult.isContextValid()) { + logger.error("Saved Resource {} is not valid:\r\n{}", resource.getId(), validationResult); + throw new RefusedArtifactException("Resource is not valid."); + } + + logger.info("Saved resource {} is valid.", resource.getId()); + + metadataService.getIdentity(resource).setAttribute("status", String.class, "stored"); + + resourceDAO.saveResource(resource); // TODO is saving necessary after move? define exact contract + +// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); + + return resource; + } + + private Resource putNonFileResource(Resource resource, boolean move) { + throw new UnsupportedOperationException("Put resource from another URI than file not supported yet: " + + resource.getId() + ": " + metadataService.getUri(resource) + ", move: " + move); + } + + @Override + public synchronized boolean remove(Resource resource) throws IOException { + resource = pluginManager.getPlugin(ActionHandler.class).beforeDeleteFromStore(resource, this); + + if (!isInStore(resource)) { + if (resourceDAO.existsResource(metadataService.getUri(resource))) { + logger.warn( "Removing resource is not in store but it is in internal repository: {}", resource.getId()); + resourceDAO.deleteResource(metadataService.getUri(resource)); + } + pluginManager.getPlugin(ActionHandler.class).afterDeleteFromStore(resource, this); + return false; + } + + // if URI scheme is not 'file', it is detected in previous isInStore() check + File file = new File(metadataService.getUri(resource)); + if (!file.delete()) { + throw new IOException("Can not delete artifact file from store: " + metadataService.getUri(resource)); + } + +// ResourceDAO resourceDao = m_pluginManager.getPlugin(ResourceDAO.class); +// try { + resourceDAO.deleteResource(metadataService.getUri(resource)); +// } finally { + // once the artifact file was removed, the resource has to be removed + // from the repository even in case of exception on removing metadata + // to keep consistency of repository with stored artifact files +// if (m_repository == null) { +// loadRepository(); +// } +// if (!m_ResourceDAO.deleteResource(LegacyMetadataHelper.getUri(resource))) { +// logger.warn( "Store's internal repository does not contain removing resource: {}", resource.getId()); +// } +// m_pluginManager.getPlugin(RepositoryDAO.class).saveRepository(m_repository); +// } + pluginManager.getPlugin(ActionHandler.class).afterDeleteFromStore(resource, this); + return true; + } + + @Override + public synchronized void execute(List resources, final Executable executable, final Properties properties) { + final ActionHandler ah = pluginManager.getPlugin(ActionHandler.class); + final List res = ah.beforeExecuteInStore(resources, executable, properties, this); + final Store store = this; + + new Thread(new Runnable() { + + @Override + public void run() { + try { + executable.executeOnStore(res, store, properties); + } catch (Exception e) { + logger.error( "Executable plugin2 threw an exception while executed in buffer: {}", executable.getPluginDescription(), e); + } + ah.afterExecuteInStore(res, executable, properties, store); + } + }).start(); + } + + @Override + public synchronized List getResources() { + try { + return resourceDAO.loadResources(repository); + } catch (IOException e) { + logger.error("Could not load resources of repository {}.", baseDir.toURI(), e); + } + return Collections.emptyList(); + } + + @Override + public synchronized List getResources(Requirement requirement) { + return getResources(Collections.singleton(requirement)); + } + + @Nonnull + @Override + public synchronized List getResources(Set requirement) { + List resources = Collections.emptyList(); + try { + resources = resourceLoader.getResources(repository, requirement); + } catch (IOException e) { + logger.error("Could not load resources for requirement ({})", requirement.toString()); + logger.error(e.getMessage(), e); + } + + if (logger.isDebugEnabled()) { + logger.debug("getResources(requirement={}) returns {}", requirement.toString(), resources.size()); + } + return resources; + } + + private boolean isInStore(Resource resource) { + URI uri = metadataService.getUri(resource).normalize(); + if (!"file".equals(uri.getScheme())) { + return false; + } + return new File(uri).getPath().startsWith(baseDir.getAbsolutePath()); + } + + @Override + public String toString() { + return "FilebasedStoreImpl{" + "baseDir=" + baseDir + '}'; + } + + private void indexResources(File baseDir, Repository repository) { + indexDirectory(baseDir, repository); + if (logger.isDebugEnabled()) { + logger.debug("Indexing done for store directory: {}", baseDir.getAbsolutePath()); + } + } + + private void indexDirectory(File directory, Repository repository) { + for (File file : directory.listFiles()) { + if (file.isFile()) { + try { + if ("repository.xml".equals(file.getName())) { + continue; + } + if (resourceIndexerService != null && !resourceDAO.existsResource(file.toURI())) { + Resource resource; + try { + resource = resourceIndexerService.indexResource(file); + } catch (IOException e) { + logger.error("Could not index file {}", file, e); + continue; + } + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + + identityIndexer.preIndex(file, file.getName(), resource); + identityIndexer.postIndex(file, resource); + + ResourceValidationResult validationResult = metadataValidator.validate(resource); + if (!validationResult.isContextValid()) { + logger.error("Indexed Resource {} is not valid:\r\n{}", resource.getId(), validationResult); + continue; + } + logger.info("Indexed resource {} is valid.", resource.getId()); + + try { + resourceDAO.saveResource(resource); + } catch (IOException e) { + logger.error("Could not save indexed resource for file {}: {}", file, resource, e); + } + } + } catch (IOException e) { + logger.error("Could not check that resource exists: {}", file, e); + } + } else if (file.isDirectory()) { + indexDirectory(file, repository); + } + } + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/IdentityIndexer.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/IdentityIndexer.java index 5b8881cd..038e25cf 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/IdentityIndexer.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/IdentityIndexer.java @@ -1,89 +1,89 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = IdentityIndexer.class) -public class IdentityIndexer { - - private static final Logger logger = LoggerFactory.getLogger(IdentityIndexer.class); - - private static final String MIME__APPLICATION_OCTET_STREAM = "application/octet-stream"; - - - @ServiceDependency private volatile MetadataService metadataService; - - public void preIndex(File file, String name, Resource resource) { - Capability identity = metadataService.getIdentity(resource); - - metadataService.setUri(resource, file.toURI().normalize()); - metadataService.setFileName(resource, name); - - identity.setAttribute("original-file-name", String.class, name); // TODO hardcoded - } - - public void postIndex(File file, Resource resource) { - Capability identity = metadataService.getIdentity(resource); - - metadataService.setSize(resource, file.length()); - String hash = getSHA(file); - if (hash != null) { - identity.setAttribute("hash", String.class, hash); // TODO hardcoded - } - - SimpleAttributeType mime = new SimpleAttributeType<>("mime", String.class); // TODO hardcoded - Attribute attribute = identity.getAttribute(mime); - if (attribute == null) { - identity.setAttribute(mime, MIME__APPLICATION_OCTET_STREAM); - } - } - - /** - * Get hexadecimal SHA-256 of file with resource or null, if error occurred during counting digest. - * - * @param file - * @return hexadecimal SHA-256 of file with resource or null - */ - private String getSHA(File file) { - try (FileInputStream fis = new FileInputStream(file)) { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - - byte[] buffer = new byte[10 * 1024]; - - int nread; - while ((nread = fis.read(buffer)) != -1) { - md.update(buffer, 0, nread); - } - byte[] mdbytes = md.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mdbytes.length; i++) { - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); // NOPMD better clarity - } - - return sb.toString(); - - } catch (NoSuchAlgorithmException | IOException e) { - logger.warn("Hash generation failed.", e); - return null; - } - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = IdentityIndexer.class) +public class IdentityIndexer { + + private static final Logger logger = LoggerFactory.getLogger(IdentityIndexer.class); + + private static final String MIME__APPLICATION_OCTET_STREAM = "application/octet-stream"; + + + @ServiceDependency private volatile MetadataService metadataService; + + public void preIndex(File file, String name, Resource resource) { + Capability identity = metadataService.getIdentity(resource); + + metadataService.setUri(resource, file.toURI().normalize()); + metadataService.setFileName(resource, name); + + identity.setAttribute("original-file-name", String.class, name); // TODO hardcoded + } + + public void postIndex(File file, Resource resource) { + Capability identity = metadataService.getIdentity(resource); + + metadataService.setSize(resource, file.length()); + String hash = getSHA(file); + if (hash != null) { + identity.setAttribute("hash", String.class, hash); // TODO hardcoded + } + + SimpleAttributeType mime = new SimpleAttributeType<>("mime", String.class); // TODO hardcoded + Attribute attribute = identity.getAttribute(mime); + if (attribute == null) { + identity.setAttribute(mime, MIME__APPLICATION_OCTET_STREAM); + } + } + + /** + * Get hexadecimal SHA-256 of file with resource or null, if error occurred during counting digest. + * + * @param file + * @return hexadecimal SHA-256 of file with resource or null + */ + private String getSHA(File file) { + try (FileInputStream fis = new FileInputStream(file)) { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + + byte[] buffer = new byte[10 * 1024]; + + int nread; + while ((nread = fis.read(buffer)) != -1) { + md.update(buffer, 0, nread); + } + byte[] mdbytes = md.digest(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mdbytes.length; i++) { + sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); // NOPMD better clarity + } + + return sb.toString(); + + } catch (NoSuchAlgorithmException | IOException e) { + logger.warn("Hash generation failed.", e); + return null; + } + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/PriorityActionHandler.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/PriorityActionHandler.java index 7ba4285b..cbff0360 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/PriorityActionHandler.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/PriorityActionHandler.java @@ -1,280 +1,280 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.plugin.AbstractPlugin; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.repository.plugins.ActionHandler; -import cz.zcu.kiv.crce.repository.plugins.Executable; - -/** - * Root implementation of ActionHandler which calls other - * implementations and call them in order given by their priority. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@SuppressWarnings("UseSpecificCatch") -public class PriorityActionHandler extends AbstractPlugin implements ActionHandler { - - private volatile PluginManager m_pluginManager; /* injected by dependency manager */ - - private static final Logger logger = LoggerFactory.getLogger(PriorityActionHandler.class); - - - private static final Method BEFORE_BUFFER_UPLOAD; - private static final Method ON_BUFFER_UPLOAD; - private static final Method AFTER_BUFFER_UPLOAD; - - private static final Method BEFORE_BUFFER_DOWNLOAD; - private static final Method AFTER_BUFFER_DOWNLOAD; - - private static final Method BEFORE_BUFFER_EXECUTE; - private static final Method AFTER_BUFFER_EXECUTE; - - private static final Method BEFORE_BUFFER_DELETE; - private static final Method AFTER_BUFFER_DELETE; - - private static final Method BEFORE_BUFFER_COMMIT; - private static final Method AFTER_BUFFER_COMMIT; - - - private static final Method BEFORE_STORE_PUT; - private static final Method AFTER_STORE_PUT; - - private static final Method BEFORE_STORE_DELETE; - private static final Method AFTER_STORE_DELETE; - - private static final Method BEFORE_STORE_DOWNLOAD; - private static final Method AFTER_STORE_DOWNLOAD; - - private static final Method BEFORE_STORE_EXECUTE; - private static final Method AFTER_STORE_EXECUTE; - - static { - try { - BEFORE_BUFFER_UPLOAD = ActionHandler.class.getMethod("beforeUploadToBuffer", String.class, Buffer.class); - ON_BUFFER_UPLOAD = ActionHandler.class.getMethod("onUploadToBuffer", Resource.class, Buffer.class, String.class); - AFTER_BUFFER_UPLOAD = ActionHandler.class.getMethod("afterUploadToBuffer", Resource.class, Buffer.class, String.class); - - BEFORE_BUFFER_DOWNLOAD = ActionHandler.class.getMethod("beforeDownloadFromBuffer", Resource.class, Buffer.class); - AFTER_BUFFER_DOWNLOAD = ActionHandler.class.getMethod("afterDownloadFromBuffer", Resource.class, Buffer.class); - - BEFORE_BUFFER_EXECUTE = ActionHandler.class.getMethod("beforeExecuteInBuffer", List.class, Executable.class, Properties.class, Buffer.class); - AFTER_BUFFER_EXECUTE = ActionHandler.class.getMethod("afterExecuteInBuffer", List.class, Executable.class, Properties.class, Buffer.class); - - BEFORE_BUFFER_DELETE = ActionHandler.class.getMethod("beforeDeleteFromBuffer", Resource.class, Buffer.class); - AFTER_BUFFER_DELETE = ActionHandler.class.getMethod("afterDeleteFromBuffer", Resource.class, Buffer.class); - - BEFORE_BUFFER_COMMIT = ActionHandler.class.getMethod("beforeBufferCommit", List.class, Buffer.class, Store.class); - AFTER_BUFFER_COMMIT = ActionHandler.class.getMethod("afterBufferCommit", List.class, Buffer.class, Store.class); - - BEFORE_STORE_PUT = ActionHandler.class.getMethod("beforePutToStore", Resource.class, Store.class); - AFTER_STORE_PUT = ActionHandler.class.getMethod("afterPutToStore", Resource.class, Store.class); - - BEFORE_STORE_DELETE = ActionHandler.class.getMethod("beforeDeleteFromStore", Resource.class, Store.class); - AFTER_STORE_DELETE = ActionHandler.class.getMethod("afterDeleteFromStore", Resource.class, Store.class); - - BEFORE_STORE_DOWNLOAD = ActionHandler.class.getMethod("beforeDownloadFromStore", Resource.class, Store.class); - AFTER_STORE_DOWNLOAD = ActionHandler.class.getMethod("afterDownloadFromStore", Resource.class, Store.class); - - BEFORE_STORE_EXECUTE = ActionHandler.class.getMethod("beforeExecuteInStore", List.class, Executable.class, Properties.class, Store.class); - AFTER_STORE_EXECUTE = ActionHandler.class.getMethod("afterExecuteInStore", List.class, Executable.class, Properties.class, Store.class); - } catch (NoSuchMethodException ex) { - throw new IllegalStateException("Can not create method: " + ex.getMessage(), ex); - } - } - - @Override - public String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException { - Object[] out = execute(BEFORE_BUFFER_UPLOAD, new Object[]{name, buffer}); - if (out[1] != null) { - if (out[1] instanceof RefusedArtifactException) { - throw (RefusedArtifactException) out[1]; - } else { - throw new IllegalStateException("beforeUploadToBuffer threw unexpected exception", (Throwable) out[1]); - } - } - return (String) out[0]; - } - - @Override - public Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { - Object[] out = execute(ON_BUFFER_UPLOAD, new Object[]{resource, buffer, name}); - if (out[1] != null) { - if (out[1] instanceof RefusedArtifactException) { - throw (RefusedArtifactException) out[1]; - } else { - throw new IllegalStateException("onUploadToBuffer threw unexpected exception", (Throwable) out[1]); - } - } - return (Resource) out[0]; - } - - @Override - public Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { - Object[] out = execute(AFTER_BUFFER_UPLOAD, new Object[]{resource, buffer, name}); - if (out[1] != null) { - if (out[1] instanceof RefusedArtifactException) { - throw (RefusedArtifactException) out[1]; - } else { - throw new IllegalStateException("afterUploadToBuffer threw unexpected exception", (Throwable) out[1]); - } - } - return (Resource) out[0]; - } - - @Override - public Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer) { - return (Resource) execute(BEFORE_BUFFER_DOWNLOAD, new Object[]{resource, buffer})[0]; - } - - @Override - public Resource afterDownloadFromBuffer(Resource resource, Buffer buffer) { - return (Resource) execute(AFTER_BUFFER_DOWNLOAD, new Object[]{resource, buffer})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { - return (List) execute(BEFORE_BUFFER_EXECUTE, new Object[]{resources, executable, properties, buffer})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { - return (List) execute(AFTER_BUFFER_EXECUTE, new Object[]{resources, executable, properties, buffer})[0]; - } - - @Override - public Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer) { - return (Resource) execute(BEFORE_BUFFER_DELETE, new Object[]{resource, buffer})[0]; - } - - @Override - public Resource afterDeleteFromBuffer(Resource resource, Buffer buffer) { - return (Resource) execute(AFTER_BUFFER_DELETE, new Object[]{resource, buffer})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List beforeBufferCommit(List resources, Buffer buffer, Store store) { - return (List) execute(BEFORE_BUFFER_COMMIT, new Object[]{resources, buffer, store})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List afterBufferCommit(List resources, Buffer buffer, Store store) { - return (List) execute(AFTER_BUFFER_COMMIT, new Object[]{resources, buffer, store})[0]; - } - - @Override - public Resource beforePutToStore(Resource resource, Store repository) throws RefusedArtifactException { - Object[] out = execute(BEFORE_STORE_PUT, new Object[]{resource, repository}); - if (out[1] != null) { - if (out[1] instanceof RefusedArtifactException) { - throw (RefusedArtifactException) out[1]; - } else { - throw new IllegalStateException("beforePutToStore threw unexpected exception", (Throwable) out[1]); - } - } - return (Resource) out[0]; - } - - @Override - public Resource afterPutToStore(Resource resource, Store repository) throws RefusedArtifactException { - Object[] out = execute(AFTER_STORE_PUT, new Object[]{resource, repository}); - if (out[1] != null) { - if (out[1] instanceof RefusedArtifactException) { - throw (RefusedArtifactException) out[1]; - } else { - throw new IllegalStateException("afterPutToStore threw unexpected exception", (Throwable) out[1]); - } - } - return (Resource) out[0]; - } - - @Override - public Resource beforeDeleteFromStore(Resource resource, Store store) { - return (Resource) execute(BEFORE_STORE_DELETE, new Object[]{resource, store})[0]; - } - - @Override - public Resource afterDeleteFromStore(Resource resource, Store store) { - return (Resource) execute(AFTER_STORE_DELETE, new Object[]{resource, store})[0]; - } - - @Override - public Resource beforeDownloadFromStore(Resource resource, Store store) { - return (Resource) execute(BEFORE_STORE_DOWNLOAD, new Object[]{resource, store})[0]; - } - - @Override - public Resource afterDownloadFromStore(Resource resource, Store store) { - return (Resource) execute(AFTER_STORE_DOWNLOAD, new Object[]{resource, store})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store) { - return (List) execute(BEFORE_STORE_EXECUTE, new Object[]{resources, executable, properties, store})[0]; - } - - @Override - @SuppressWarnings("unchecked") - public List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store) { - return (List) execute(AFTER_STORE_EXECUTE, new Object[]{resources, executable, properties, store})[0]; - } - - /** - * Works for all ActionHandler methods whose the first parameter is equivalent - * to returned object (e.g. the first parameter is Resource, returned parameter - * is Resource too.) - * - * @return An array of returned object and thrown exception. - */ - private Object[] execute(Method method, Object[] args) { - List handlers = m_pluginManager.getPlugins(ActionHandler.class); - - Object out = args[0]; - - boolean modifying = true; - Throwable exception = null; - do { - for (ActionHandler handler : handlers) { - if (handler.isExclusive() == modifying && !handler.equals(this)) { - args[0] = out; - try { - out = method.invoke(handler, args); - } catch (IllegalAccessException ex) { - logger.error("Unexpected IllegalAccessException", ex); - } catch (InvocationTargetException ex) { - exception = ex.getTargetException(); - } catch (Exception e) { - logger.error("Unexpected exception on calling handler", e); - } - } - } - } while (!(modifying = !modifying)); // runs twice, the first for modifying true - - return new Object[] {out, exception}; - } - - @Override - public int getPluginPriority() { - return Integer.MAX_VALUE / 2; - } - - @Override - public boolean isExclusive() { - return true; - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.plugin.AbstractPlugin; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.plugins.ActionHandler; +import cz.zcu.kiv.crce.repository.plugins.Executable; + +/** + * Root implementation of ActionHandler which calls other + * implementations and call them in order given by their priority. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@SuppressWarnings("UseSpecificCatch") +public class PriorityActionHandler extends AbstractPlugin implements ActionHandler { + + private volatile PluginManager m_pluginManager; /* injected by dependency manager */ + + private static final Logger logger = LoggerFactory.getLogger(PriorityActionHandler.class); + + + private static final Method BEFORE_BUFFER_UPLOAD; + private static final Method ON_BUFFER_UPLOAD; + private static final Method AFTER_BUFFER_UPLOAD; + + private static final Method BEFORE_BUFFER_DOWNLOAD; + private static final Method AFTER_BUFFER_DOWNLOAD; + + private static final Method BEFORE_BUFFER_EXECUTE; + private static final Method AFTER_BUFFER_EXECUTE; + + private static final Method BEFORE_BUFFER_DELETE; + private static final Method AFTER_BUFFER_DELETE; + + private static final Method BEFORE_BUFFER_COMMIT; + private static final Method AFTER_BUFFER_COMMIT; + + + private static final Method BEFORE_STORE_PUT; + private static final Method AFTER_STORE_PUT; + + private static final Method BEFORE_STORE_DELETE; + private static final Method AFTER_STORE_DELETE; + + private static final Method BEFORE_STORE_DOWNLOAD; + private static final Method AFTER_STORE_DOWNLOAD; + + private static final Method BEFORE_STORE_EXECUTE; + private static final Method AFTER_STORE_EXECUTE; + + static { + try { + BEFORE_BUFFER_UPLOAD = ActionHandler.class.getMethod("beforeUploadToBuffer", String.class, Buffer.class); + ON_BUFFER_UPLOAD = ActionHandler.class.getMethod("onUploadToBuffer", Resource.class, Buffer.class, String.class); + AFTER_BUFFER_UPLOAD = ActionHandler.class.getMethod("afterUploadToBuffer", Resource.class, Buffer.class, String.class); + + BEFORE_BUFFER_DOWNLOAD = ActionHandler.class.getMethod("beforeDownloadFromBuffer", Resource.class, Buffer.class); + AFTER_BUFFER_DOWNLOAD = ActionHandler.class.getMethod("afterDownloadFromBuffer", Resource.class, Buffer.class); + + BEFORE_BUFFER_EXECUTE = ActionHandler.class.getMethod("beforeExecuteInBuffer", List.class, Executable.class, Properties.class, Buffer.class); + AFTER_BUFFER_EXECUTE = ActionHandler.class.getMethod("afterExecuteInBuffer", List.class, Executable.class, Properties.class, Buffer.class); + + BEFORE_BUFFER_DELETE = ActionHandler.class.getMethod("beforeDeleteFromBuffer", Resource.class, Buffer.class); + AFTER_BUFFER_DELETE = ActionHandler.class.getMethod("afterDeleteFromBuffer", Resource.class, Buffer.class); + + BEFORE_BUFFER_COMMIT = ActionHandler.class.getMethod("beforeBufferCommit", List.class, Buffer.class, Store.class); + AFTER_BUFFER_COMMIT = ActionHandler.class.getMethod("afterBufferCommit", List.class, Buffer.class, Store.class); + + BEFORE_STORE_PUT = ActionHandler.class.getMethod("beforePutToStore", Resource.class, Store.class); + AFTER_STORE_PUT = ActionHandler.class.getMethod("afterPutToStore", Resource.class, Store.class); + + BEFORE_STORE_DELETE = ActionHandler.class.getMethod("beforeDeleteFromStore", Resource.class, Store.class); + AFTER_STORE_DELETE = ActionHandler.class.getMethod("afterDeleteFromStore", Resource.class, Store.class); + + BEFORE_STORE_DOWNLOAD = ActionHandler.class.getMethod("beforeDownloadFromStore", Resource.class, Store.class); + AFTER_STORE_DOWNLOAD = ActionHandler.class.getMethod("afterDownloadFromStore", Resource.class, Store.class); + + BEFORE_STORE_EXECUTE = ActionHandler.class.getMethod("beforeExecuteInStore", List.class, Executable.class, Properties.class, Store.class); + AFTER_STORE_EXECUTE = ActionHandler.class.getMethod("afterExecuteInStore", List.class, Executable.class, Properties.class, Store.class); + } catch (NoSuchMethodException ex) { + throw new IllegalStateException("Can not create method: " + ex.getMessage(), ex); + } + } + + @Override + public String beforeUploadToBuffer(String name, Buffer buffer) throws RefusedArtifactException { + Object[] out = execute(BEFORE_BUFFER_UPLOAD, new Object[]{name, buffer}); + if (out[1] != null) { + if (out[1] instanceof RefusedArtifactException) { + throw (RefusedArtifactException) out[1]; + } else { + throw new IllegalStateException("beforeUploadToBuffer threw unexpected exception", (Throwable) out[1]); + } + } + return (String) out[0]; + } + + @Override + public Resource onUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { + Object[] out = execute(ON_BUFFER_UPLOAD, new Object[]{resource, buffer, name}); + if (out[1] != null) { + if (out[1] instanceof RefusedArtifactException) { + throw (RefusedArtifactException) out[1]; + } else { + throw new IllegalStateException("onUploadToBuffer threw unexpected exception", (Throwable) out[1]); + } + } + return (Resource) out[0]; + } + + @Override + public Resource afterUploadToBuffer(Resource resource, Buffer buffer, String name) throws RefusedArtifactException { + Object[] out = execute(AFTER_BUFFER_UPLOAD, new Object[]{resource, buffer, name}); + if (out[1] != null) { + if (out[1] instanceof RefusedArtifactException) { + throw (RefusedArtifactException) out[1]; + } else { + throw new IllegalStateException("afterUploadToBuffer threw unexpected exception", (Throwable) out[1]); + } + } + return (Resource) out[0]; + } + + @Override + public Resource beforeDownloadFromBuffer(Resource resource, Buffer buffer) { + return (Resource) execute(BEFORE_BUFFER_DOWNLOAD, new Object[]{resource, buffer})[0]; + } + + @Override + public Resource afterDownloadFromBuffer(Resource resource, Buffer buffer) { + return (Resource) execute(AFTER_BUFFER_DOWNLOAD, new Object[]{resource, buffer})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List beforeExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { + return (List) execute(BEFORE_BUFFER_EXECUTE, new Object[]{resources, executable, properties, buffer})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List afterExecuteInBuffer(List resources, Executable executable, Properties properties, Buffer buffer) { + return (List) execute(AFTER_BUFFER_EXECUTE, new Object[]{resources, executable, properties, buffer})[0]; + } + + @Override + public Resource beforeDeleteFromBuffer(Resource resource, Buffer buffer) { + return (Resource) execute(BEFORE_BUFFER_DELETE, new Object[]{resource, buffer})[0]; + } + + @Override + public Resource afterDeleteFromBuffer(Resource resource, Buffer buffer) { + return (Resource) execute(AFTER_BUFFER_DELETE, new Object[]{resource, buffer})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List beforeBufferCommit(List resources, Buffer buffer, Store store) { + return (List) execute(BEFORE_BUFFER_COMMIT, new Object[]{resources, buffer, store})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List afterBufferCommit(List resources, Buffer buffer, Store store) { + return (List) execute(AFTER_BUFFER_COMMIT, new Object[]{resources, buffer, store})[0]; + } + + @Override + public Resource beforePutToStore(Resource resource, Store repository) throws RefusedArtifactException { + Object[] out = execute(BEFORE_STORE_PUT, new Object[]{resource, repository}); + if (out[1] != null) { + if (out[1] instanceof RefusedArtifactException) { + throw (RefusedArtifactException) out[1]; + } else { + throw new IllegalStateException("beforePutToStore threw unexpected exception", (Throwable) out[1]); + } + } + return (Resource) out[0]; + } + + @Override + public Resource afterPutToStore(Resource resource, Store repository) throws RefusedArtifactException { + Object[] out = execute(AFTER_STORE_PUT, new Object[]{resource, repository}); + if (out[1] != null) { + if (out[1] instanceof RefusedArtifactException) { + throw (RefusedArtifactException) out[1]; + } else { + throw new IllegalStateException("afterPutToStore threw unexpected exception", (Throwable) out[1]); + } + } + return (Resource) out[0]; + } + + @Override + public Resource beforeDeleteFromStore(Resource resource, Store store) { + return (Resource) execute(BEFORE_STORE_DELETE, new Object[]{resource, store})[0]; + } + + @Override + public Resource afterDeleteFromStore(Resource resource, Store store) { + return (Resource) execute(AFTER_STORE_DELETE, new Object[]{resource, store})[0]; + } + + @Override + public Resource beforeDownloadFromStore(Resource resource, Store store) { + return (Resource) execute(BEFORE_STORE_DOWNLOAD, new Object[]{resource, store})[0]; + } + + @Override + public Resource afterDownloadFromStore(Resource resource, Store store) { + return (Resource) execute(AFTER_STORE_DOWNLOAD, new Object[]{resource, store})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List beforeExecuteInStore(List resources, Executable executable, Properties properties, Store store) { + return (List) execute(BEFORE_STORE_EXECUTE, new Object[]{resources, executable, properties, store})[0]; + } + + @Override + @SuppressWarnings("unchecked") + public List afterExecuteInStore(List resources, Executable executable, Properties properties, Store store) { + return (List) execute(AFTER_STORE_EXECUTE, new Object[]{resources, executable, properties, store})[0]; + } + + /** + * Works for all ActionHandler methods whose the first parameter is equivalent + * to returned object (e.g. the first parameter is Resource, returned parameter + * is Resource too.) + * + * @return An array of returned object and thrown exception. + */ + private Object[] execute(Method method, Object[] args) { + List handlers = m_pluginManager.getPlugins(ActionHandler.class); + + Object out = args[0]; + + boolean modifying = true; + Throwable exception = null; + do { + for (ActionHandler handler : handlers) { + if (handler.isExclusive() == modifying && !handler.equals(this)) { + args[0] = out; + try { + out = method.invoke(handler, args); + } catch (IllegalAccessException ex) { + logger.error("Unexpected IllegalAccessException", ex); + } catch (InvocationTargetException ex) { + exception = ex.getTargetException(); + } catch (Exception e) { + logger.error("Unexpected exception on calling handler", e); + } + } + } + } while (!(modifying = !modifying)); // runs twice, the first for modifying true + + return new Object[] {out, exception}; + } + + @Override + public int getPluginPriority() { + return Integer.MAX_VALUE / 2; + } + + @Override + public boolean isExclusive() { + return true; + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionDataImpl.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionDataImpl.java index 34a7a367..2e41835e 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionDataImpl.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionDataImpl.java @@ -1,20 +1,20 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.SessionData; -import org.apache.felix.dm.Component; - -/** - * Implementation of SessionData - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class SessionDataImpl implements SessionData { - - Component bufferComponent; - Buffer buffer; - - @Override - public Buffer getBuffer() { - return buffer; - } -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.SessionData; +import org.apache.felix.dm.Component; + +/** + * Implementation of SessionData + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class SessionDataImpl implements SessionData { + + Component bufferComponent; + Buffer buffer; + + @Override + public Buffer getBuffer() { + return buffer; + } +} diff --git a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionRegisterImpl.java b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionRegisterImpl.java index 7dc26956..ccd54bbe 100644 --- a/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionRegisterImpl.java +++ b/core/crce-repository-impl/src/main/java/cz/zcu/kiv/crce/repository/filebased/internal/SessionRegisterImpl.java @@ -1,80 +1,80 @@ -package cz.zcu.kiv.crce.repository.filebased.internal; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.felix.dm.DependencyManager; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.SessionData; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; - -/** - * Implementation of SessionFactory. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class SessionRegisterImpl implements SessionRegister { - - private volatile DependencyManager dependencyManager; /* injected by dependency manager */ - - private final Map sessions = new HashMap<>(); - - @Override - public void registerSession(String sessionId) { - synchronized (sessions) { - if (!sessions.containsKey(sessionId)) { - SessionDataImpl sd = new SessionDataImpl(); - BufferImpl buffer = new BufferImpl(sessionId); - - sd.buffer = buffer; - - sd.bufferComponent = dependencyManager.createComponent() - .setInterface(Buffer.class.getName(), buffer.getSessionProperties()) - .setImplementation(buffer) - .add(dependencyManager.createServiceDependency().setService(PluginManager.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(Store.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(ResourceDAO.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(MetadataValidator.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(IdentityIndexer.class).setRequired(true)) - .add(dependencyManager.createServiceDependency().setService(ResourceIndexerService.class).setRequired(true)); - - dependencyManager.add(sd.bufferComponent); - sessions.put(sessionId, sd); - } - } - } - - @Override - public void unregisterSession(String sessionId) { - synchronized (sessions) { - SessionDataImpl sd = sessions.remove(sessionId); - if (sd != null) { - dependencyManager.remove(sd.bufferComponent); - } - } - } - - @Override - public SessionData getSessionData(String sessionId) { - synchronized (sessions) { - SessionData session = sessions.get(sessionId); - if (session == null) { - registerSession(sessionId); - return sessions.get(sessionId); - } - return session; - } - } - -} +package cz.zcu.kiv.crce.repository.filebased.internal; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.felix.dm.DependencyManager; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.SessionData; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; + +/** + * Implementation of SessionFactory. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class SessionRegisterImpl implements SessionRegister { + + private volatile DependencyManager dependencyManager; /* injected by dependency manager */ + + private final Map sessions = new HashMap<>(); + + @Override + public void registerSession(String sessionId) { + synchronized (sessions) { + if (!sessions.containsKey(sessionId)) { + SessionDataImpl sd = new SessionDataImpl(); + BufferImpl buffer = new BufferImpl(sessionId); + + sd.buffer = buffer; + + sd.bufferComponent = dependencyManager.createComponent() + .setInterface(Buffer.class.getName(), buffer.getSessionProperties()) + .setImplementation(buffer) + .add(dependencyManager.createServiceDependency().setService(PluginManager.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(Store.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(ResourceDAO.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(MetadataValidator.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(IdentityIndexer.class).setRequired(true)) + .add(dependencyManager.createServiceDependency().setService(ResourceIndexerService.class).setRequired(true)); + + dependencyManager.add(sd.bufferComponent); + sessions.put(sessionId, sd); + } + } + } + + @Override + public void unregisterSession(String sessionId) { + synchronized (sessions) { + SessionDataImpl sd = sessions.remove(sessionId); + if (sd != null) { + dependencyManager.remove(sd.bufferComponent); + } + } + } + + @Override + public SessionData getSessionData(String sessionId) { + synchronized (sessions) { + SessionData session = sessions.get(sessionId); + if (session == null) { + registerSession(sessionId); + return sessions.get(sessionId); + } + return session; + } + } + +} diff --git a/core/crce-repository-impl/src/test/java/cz/zcu/kiv/crce/repository/internal/PriorityActionHandlerTest.java b/core/crce-repository-impl/src/test/java/cz/zcu/kiv/crce/repository/internal/PriorityActionHandlerTest.java index a0c1a412..3a0bc02a 100644 --- a/core/crce-repository-impl/src/test/java/cz/zcu/kiv/crce/repository/internal/PriorityActionHandlerTest.java +++ b/core/crce-repository-impl/src/test/java/cz/zcu/kiv/crce/repository/internal/PriorityActionHandlerTest.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.repository.internal; - -import cz.zcu.kiv.crce.repository.filebased.internal.PriorityActionHandler; -import cz.zcu.kiv.crce.repository.plugins.ActionHandler; - -import org.junit.*; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class PriorityActionHandlerTest { - - /* - * This test can detect mismatch declaration of reflective methods in PriorityActionHandler. - * @throws Exception - */ - @Test - public void testInstantiation() throws Exception { - try { - ActionHandler handler = new PriorityActionHandler(); - } catch (Throwable e) { - assert false : e.getCause().getMessage(); - } - } -} +package cz.zcu.kiv.crce.repository.internal; + +import cz.zcu.kiv.crce.repository.filebased.internal.PriorityActionHandler; +import cz.zcu.kiv.crce.repository.plugins.ActionHandler; + +import org.junit.*; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class PriorityActionHandlerTest { + + /* + * This test can detect mismatch declaration of reflective methods in PriorityActionHandler. + * @throws Exception + */ + @Test + public void testInstantiation() throws Exception { + try { + ActionHandler handler = new PriorityActionHandler(); + } catch (Throwable e) { + assert false : e.getCause().getMessage(); + } + } +} diff --git a/core/crce-resolver-api/osgi.bnd b/core/crce-resolver-api/osgi.bnd index cf6ca00e..fb96e5f2 100644 --- a/core/crce-resolver-api/osgi.bnd +++ b/core/crce-resolver-api/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Private-Package: +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Private-Package: diff --git a/core/crce-resolver-api/pom.xml b/core/crce-resolver-api/pom.xml index 7d576fee..22377507 100644 --- a/core/crce-resolver-api/pom.xml +++ b/core/crce-resolver-api/pom.xml @@ -1,56 +1,56 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-resolver-api - 2.2.0-SNAPSHOT - bundle - - CRCE - Core - Resolver API - - - https://github.com/ReliSA/crce/tree/master/core/crce-resolver-api - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.resolver.api - ${namespace}.resolver - - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-resolver-api + 2.2.0-SNAPSHOT + bundle + + CRCE - Core - Resolver API + + + https://github.com/ReliSA/crce/tree/master/core/crce-resolver-api + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.resolver.api + ${namespace}.resolver + + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-resolver-api/src/main/java/cz/zcu/kiv/crce/resolver/ResourceLoader.java b/core/crce-resolver-api/src/main/java/cz/zcu/kiv/crce/resolver/ResourceLoader.java index 7c7a8068..0c9ec293 100644 --- a/core/crce-resolver-api/src/main/java/cz/zcu/kiv/crce/resolver/ResourceLoader.java +++ b/core/crce-resolver-api/src/main/java/cz/zcu/kiv/crce/resolver/ResourceLoader.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.resolver; - -import java.io.IOException; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@ParametersAreNonnullByDefault -public interface ResourceLoader { - - @Nonnull - List getResources(Repository repository, Requirement requirement) throws IOException; - - @Nonnull - List getResources(Repository repository, Set requirement) throws IOException; -} +package cz.zcu.kiv.crce.resolver; + +import java.io.IOException; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@ParametersAreNonnullByDefault +public interface ResourceLoader { + + @Nonnull + List getResources(Repository repository, Requirement requirement) throws IOException; + + @Nonnull + List getResources(Repository repository, Set requirement) throws IOException; +} diff --git a/core/crce-resolver-impl/osgi.bnd b/core/crce-resolver-impl/osgi.bnd index 8247c5ee..df4ea477 100644 --- a/core/crce-resolver-impl/osgi.bnd +++ b/core/crce-resolver-impl/osgi.bnd @@ -1,4 +1,4 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + diff --git a/core/crce-resolver-impl/pom.xml b/core/crce-resolver-impl/pom.xml index 8b42e00d..6d17febb 100644 --- a/core/crce-resolver-impl/pom.xml +++ b/core/crce-resolver-impl/pom.xml @@ -1,82 +1,82 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - crce-resolver-impl - 2.2.0-SNAPSHOT - bundle - - CRCE - Core - Resolver Implementation - - - https://github.com/ReliSA/crce/tree/master/core/crce-resolver-impl - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - ${namespace}.resolver.impl - ${namespace}.resolver - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - - - ${project.groupId} - crce-metadata-dao-api - 3.0.0-SNAPSHOT - - - ${project.groupId} - crce-resolver-api - 2.2.0-SNAPSHOT - - - - - - junit - junit - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + crce-resolver-impl + 2.2.0-SNAPSHOT + bundle + + CRCE - Core - Resolver Implementation + + + https://github.com/ReliSA/crce/tree/master/core/crce-resolver-impl + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + ${namespace}.resolver.impl + ${namespace}.resolver + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + + + ${project.groupId} + crce-metadata-dao-api + 3.0.0-SNAPSHOT + + + ${project.groupId} + crce-resolver-api + 2.2.0-SNAPSHOT + + + + + + junit + junit + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/core/crce-resolver-impl/src/main/java/cz/zcu/kiv/crce/resolver/internal/ResourceLoaderImpl.java b/core/crce-resolver-impl/src/main/java/cz/zcu/kiv/crce/resolver/internal/ResourceLoaderImpl.java index cfbc0936..cc4cfe2f 100644 --- a/core/crce-resolver-impl/src/main/java/cz/zcu/kiv/crce/resolver/internal/ResourceLoaderImpl.java +++ b/core/crce-resolver-impl/src/main/java/cz/zcu/kiv/crce/resolver/internal/ResourceLoaderImpl.java @@ -1,82 +1,82 @@ -package cz.zcu.kiv.crce.resolver.internal; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; -import cz.zcu.kiv.crce.metadata.dao.filter.Operator; -import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = ResourceLoader.class) -@ParametersAreNonnullByDefault -public class ResourceLoaderImpl implements ResourceLoader { - - private static final Logger logger = LoggerFactory.getLogger(ResourceLoaderImpl.class); - - @ServiceDependency private volatile ResourceDAO resourceDAO; - @ServiceDependency private volatile MetadataFactory metadataFactory; // NOPMD will be used - - @Override - @Nonnull - public List getResources(Repository repository, Requirement requirement) throws IOException { - return getResources(repository, Collections.singleton(requirement)); - } - - @Nonnull - @Override - public List getResources(Repository repository, Set requirements) throws IOException { - List resources = Collections.emptyList(); - try { - ResourceDAOFilter filter = buildFilter(requirements); - resources = resourceDAO.loadResources(repository, filter); - } catch (IOException e) { - logger.error("Could not load resources for requirements ({})", requirements.toString()); - logger.error("Stacktrace: ", e); - } - - if (logger.isDebugEnabled()) { - logger.debug("getResources(requirement={}) returns {}", requirements.toString(), resources.size()); - } - return resources; - } - - private ResourceDAOFilter buildFilter(Set requirements) { - ResourceDAOFilter filter = new ResourceDAOFilter(); - - for (Requirement req : requirements) { - CapabilityFilter cap = new CapabilityFilter(req.getNamespace()); - - String operator = req.getDirective("operator"); - if (operator == null || operator.equals("and")) { - cap.setOperator(Operator.AND); - } else if (operator.equals("or")) { - cap.setOperator(Operator.OR); - } - - cap.addAttributes(req.getAttributes()); - filter.addCapabilityFilter(cap); - } - - return filter; - } -} +package cz.zcu.kiv.crce.resolver.internal; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.dao.filter.CapabilityFilter; +import cz.zcu.kiv.crce.metadata.dao.filter.Operator; +import cz.zcu.kiv.crce.metadata.dao.filter.ResourceDAOFilter; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = ResourceLoader.class) +@ParametersAreNonnullByDefault +public class ResourceLoaderImpl implements ResourceLoader { + + private static final Logger logger = LoggerFactory.getLogger(ResourceLoaderImpl.class); + + @ServiceDependency private volatile ResourceDAO resourceDAO; + @ServiceDependency private volatile MetadataFactory metadataFactory; // NOPMD will be used + + @Override + @Nonnull + public List getResources(Repository repository, Requirement requirement) throws IOException { + return getResources(repository, Collections.singleton(requirement)); + } + + @Nonnull + @Override + public List getResources(Repository repository, Set requirements) throws IOException { + List resources = Collections.emptyList(); + try { + ResourceDAOFilter filter = buildFilter(requirements); + resources = resourceDAO.loadResources(repository, filter); + } catch (IOException e) { + logger.error("Could not load resources for requirements ({})", requirements.toString()); + logger.error("Stacktrace: ", e); + } + + if (logger.isDebugEnabled()) { + logger.debug("getResources(requirement={}) returns {}", requirements.toString(), resources.size()); + } + return resources; + } + + private ResourceDAOFilter buildFilter(Set requirements) { + ResourceDAOFilter filter = new ResourceDAOFilter(); + + for (Requirement req : requirements) { + CapabilityFilter cap = new CapabilityFilter(req.getNamespace()); + + String operator = req.getDirective("operator"); + if (operator == null || operator.equals("and")) { + cap.setOperator(Operator.AND); + } else if (operator.equals("or")) { + cap.setOperator(Operator.OR); + } + + cap.addAttributes(req.getAttributes()); + filter.addCapabilityFilter(cap); + } + + return filter; + } +} diff --git a/core/pom.xml b/core/pom.xml index ff7773e2..6f6c6d25 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -1,49 +1,49 @@ - - - - 4.0.0 - - cz.zcu.kiv.crce - crce-core-reactor - 2.1.0-SNAPSHOT - pom - - CRCE - Core - Reactor - - - crce-plugin-api - crce-metadata-api - crce-metadata-dao-api - crce-metadata-indexer-api - crce-metadata-json-api - crce-metadata-service-api - crce-repository-api - crce-resolver-api - - crce-metadata-json-impl - crce-metadata-impl - crce-metadata-dao-impl - crce-metadata-indexer-impl - crce-metadata-service-impl - crce-repository-impl - crce-resolver-impl - - crce-core - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + cz.zcu.kiv.crce + crce-core-reactor + 2.1.0-SNAPSHOT + pom + + CRCE - Core - Reactor + + + crce-plugin-api + crce-metadata-api + crce-metadata-dao-api + crce-metadata-indexer-api + crce-metadata-json-api + crce-metadata-service-api + crce-repository-api + crce-resolver-api + + crce-metadata-json-impl + crce-metadata-impl + crce-metadata-dao-impl + crce-metadata-indexer-impl + crce-metadata-service-impl + crce-repository-impl + crce-resolver-impl + + crce-core + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/modules/conf.default/cz.zcu.kiv.crce.repository.maven-local.cfg b/modules/conf.default/cz.zcu.kiv.crce.repository.maven-local.cfg index 8337d587..8923519d 100644 --- a/modules/conf.default/cz.zcu.kiv.crce.repository.maven-local.cfg +++ b/modules/conf.default/cz.zcu.kiv.crce.repository.maven-local.cfg @@ -1,8 +1,8 @@ -# URI of repository's central store or absolute/relative file path -# -# Examples: -# store.uri=file:/C:/store -# store.uri=C:\\store -# store.uri=store - -store.uri=maven +# URI of repository's central store or absolute/relative file path +# +# Examples: +# store.uri=file:/C:/store +# store.uri=C:\\store +# store.uri=store + +store.uri=maven diff --git a/modules/crce-compatibility-api/pom.xml b/modules/crce-compatibility-api/pom.xml index 58b92917..b62e1124 100644 --- a/modules/crce-compatibility-api/pom.xml +++ b/modules/crce-compatibility-api/pom.xml @@ -1,34 +1,34 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-compatibility-api - bundle - - CRCE - Compatibility API - - - ${namespace}.compatibility.api - ${namespace}.compatibility - - - - - - - ${project.groupId} - crce-core - pom - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-compatibility-api + bundle + + CRCE - Compatibility API + + + ${namespace}.compatibility.api + ${namespace}.compatibility + + + + + + + ${project.groupId} + crce-core + pom + + + + \ No newline at end of file diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Compatibility.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Compatibility.java index 3ed304db..ab5f137c 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Compatibility.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Compatibility.java @@ -1,85 +1,85 @@ -package cz.zcu.kiv.crce.compatibility; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Interface representing Compability metadata for a pair of bundles. - *

- * Date: 16.11.13 - * - * @author Jakub Danek - */ -public interface Compatibility { - - /** - * Id implementation depends on underlying persistence layer. - * - * @return unique ID - */ - String getId(); - - /** - * Name of the resource (crce.identity namespace) which has been compared to the Base resource - * - * @return unique name - */ - @Nonnull - String getResourceName(); - - /** - * Version of the resource which was compared to the Base resource. - *

- * Implemented according to the OSGi versioning scheme: - * major.minor.micor-qualifier - * - * @return version object - */ - @Nonnull - Version getResourceVersion(); - - /** - * Name of the resource (crce.identity namespace) which was the reference Resource - * - * @return unique name - */ - @Nullable - String getBaseResourceName(); - - /** - * Version of the resource which the resource has been compared to. - *

- * Implemented according to the OSGi versioning scheme: - * major.minor.micor-qualifier - * - * @return version object - */ - @Nonnull - Version getBaseResourceVersion(); - - /** - * Difference value for the two resources aggregated from the DiffDetails. - * - * @return {@link Difference} value - */ - @Nonnull - Difference getDiffValue(); - - /** - * @return Complete diff of the two resources. - */ - @Nullable - List getDiffDetails(); - - /** - * - * @return contract the compatibility instance is related to - */ - @Nonnull - Contract getContract(); - -} +package cz.zcu.kiv.crce.compatibility; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Interface representing Compability metadata for a pair of bundles. + *

+ * Date: 16.11.13 + * + * @author Jakub Danek + */ +public interface Compatibility { + + /** + * Id implementation depends on underlying persistence layer. + * + * @return unique ID + */ + String getId(); + + /** + * Name of the resource (crce.identity namespace) which has been compared to the Base resource + * + * @return unique name + */ + @Nonnull + String getResourceName(); + + /** + * Version of the resource which was compared to the Base resource. + *

+ * Implemented according to the OSGi versioning scheme: + * major.minor.micor-qualifier + * + * @return version object + */ + @Nonnull + Version getResourceVersion(); + + /** + * Name of the resource (crce.identity namespace) which was the reference Resource + * + * @return unique name + */ + @Nullable + String getBaseResourceName(); + + /** + * Version of the resource which the resource has been compared to. + *

+ * Implemented according to the OSGi versioning scheme: + * major.minor.micor-qualifier + * + * @return version object + */ + @Nonnull + Version getBaseResourceVersion(); + + /** + * Difference value for the two resources aggregated from the DiffDetails. + * + * @return {@link Difference} value + */ + @Nonnull + Difference getDiffValue(); + + /** + * @return Complete diff of the two resources. + */ + @Nullable + List getDiffDetails(); + + /** + * + * @return contract the compatibility instance is related to + */ + @Nonnull + Contract getContract(); + +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityFactory.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityFactory.java index a8070374..3fdc75ba 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityFactory.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityFactory.java @@ -1,56 +1,56 @@ -package cz.zcu.kiv.crce.compatibility; - -import java.util.List; - -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Factory interface for Compatibility. - * - * Date: 17.11.13 - * - * @author Jakub Danek - */ -public interface CompatibilityFactory { - - /** - * - * Factory method for complete initialization of Compability implementation. - * - * @param id unique id - * @param resourceName compared resource name (crce.identity) - * @param resourceVersion compared resource version in OSGi representation - * @param baseName name of the resource used as base - * @param baseVersion OSGi representation of the version of the resource used as base - * @param diffValue aggregated difference value of the two resources - * @param diffValues complete diff of the two resources - * @param contract contract the instance is related to - * @return new Compatibility instance - */ - Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, String baseName, - Version baseVersion, Difference diffValue, List diffValues, Contract contract); - - /** - * - * Factory method for complete initialization of Compability implementation. Base name is set to the same - * value as resource name. - * - * @param id unique id - * @param resourceName compared resource name (crce.identity) - * @param resourceVersion compared resource version in OSGi representation - * @param baseVersion OSGi representation of the version of the resource used as base - * @param diffValue aggregated difference value of the two resources - * @param diffValues complete diff of the two resources - * @param contract contract the instance is related to - * @return new Compatibility instance - */ - Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, - Version baseVersion, Difference diffValue, List diffValues, Contract contract); - - /** - * Create blank diff instance. - * - * @return empty instance of Diff - */ - Diff createEmptyDiff(); -} +package cz.zcu.kiv.crce.compatibility; + +import java.util.List; + +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Factory interface for Compatibility. + * + * Date: 17.11.13 + * + * @author Jakub Danek + */ +public interface CompatibilityFactory { + + /** + * + * Factory method for complete initialization of Compability implementation. + * + * @param id unique id + * @param resourceName compared resource name (crce.identity) + * @param resourceVersion compared resource version in OSGi representation + * @param baseName name of the resource used as base + * @param baseVersion OSGi representation of the version of the resource used as base + * @param diffValue aggregated difference value of the two resources + * @param diffValues complete diff of the two resources + * @param contract contract the instance is related to + * @return new Compatibility instance + */ + Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, String baseName, + Version baseVersion, Difference diffValue, List diffValues, Contract contract); + + /** + * + * Factory method for complete initialization of Compability implementation. Base name is set to the same + * value as resource name. + * + * @param id unique id + * @param resourceName compared resource name (crce.identity) + * @param resourceVersion compared resource version in OSGi representation + * @param baseVersion OSGi representation of the version of the resource used as base + * @param diffValue aggregated difference value of the two resources + * @param diffValues complete diff of the two resources + * @param contract contract the instance is related to + * @return new Compatibility instance + */ + Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, + Version baseVersion, Difference diffValue, List diffValues, Contract contract); + + /** + * Create blank diff instance. + * + * @return empty instance of Diff + */ + Diff createEmptyDiff(); +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityVersionComparator.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityVersionComparator.java index 51c79582..0a571ab3 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityVersionComparator.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/CompatibilityVersionComparator.java @@ -1,67 +1,67 @@ -package cz.zcu.kiv.crce.compatibility; - -import java.util.Comparator; - -import cz.zcu.kiv.crce.metadata.type.Version; - - -/** - * Compares two pieces of Compatibility data by their version. - *

- * Date: 29.11.13 - * - * @author Jakub Danek - */ -public class CompatibilityVersionComparator implements Comparator { - - private static final CompatibilityVersionComparator upperInstance = new CompatibilityVersionComparator(VERSION_SELECTOR.UPPER); - private static final CompatibilityVersionComparator baseInstance = new CompatibilityVersionComparator(VERSION_SELECTOR.BASE); - - /** - * This instance uses "upper" version for comparison. - * - * @return - */ - public static CompatibilityVersionComparator getUpperComparator() { - return upperInstance; - } - - /** - * This instance uses base version for comparison. - * - * @return - */ - public static CompatibilityVersionComparator getBaseComparator() { - return baseInstance; - } - - private enum VERSION_SELECTOR { - BASE, - UPPER - } - - private VERSION_SELECTOR selector; - - private CompatibilityVersionComparator(VERSION_SELECTOR selector) { - this.selector = selector; - } - - - @Override - public int compare(Compatibility o1, Compatibility o2) { - Version v1, v2; - switch (selector) { - default: - case UPPER: - v1 = o1.getResourceVersion(); - v2 = o2.getResourceVersion(); - break; - case BASE: - v1 = o1.getBaseResourceVersion(); - v2 = o2.getBaseResourceVersion(); - break; - } - - return v1.compareTo(v2); - } -} +package cz.zcu.kiv.crce.compatibility; + +import java.util.Comparator; + +import cz.zcu.kiv.crce.metadata.type.Version; + + +/** + * Compares two pieces of Compatibility data by their version. + *

+ * Date: 29.11.13 + * + * @author Jakub Danek + */ +public class CompatibilityVersionComparator implements Comparator { + + private static final CompatibilityVersionComparator upperInstance = new CompatibilityVersionComparator(VERSION_SELECTOR.UPPER); + private static final CompatibilityVersionComparator baseInstance = new CompatibilityVersionComparator(VERSION_SELECTOR.BASE); + + /** + * This instance uses "upper" version for comparison. + * + * @return + */ + public static CompatibilityVersionComparator getUpperComparator() { + return upperInstance; + } + + /** + * This instance uses base version for comparison. + * + * @return + */ + public static CompatibilityVersionComparator getBaseComparator() { + return baseInstance; + } + + private enum VERSION_SELECTOR { + BASE, + UPPER + } + + private VERSION_SELECTOR selector; + + private CompatibilityVersionComparator(VERSION_SELECTOR selector) { + this.selector = selector; + } + + + @Override + public int compare(Compatibility o1, Compatibility o2) { + Version v1, v2; + switch (selector) { + default: + case UPPER: + v1 = o1.getResourceVersion(); + v2 = o2.getResourceVersion(); + break; + case BASE: + v1 = o1.getBaseResourceVersion(); + v2 = o2.getBaseResourceVersion(); + break; + } + + return v1.compareTo(v2); + } +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Contract.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Contract.java index 16f9e25c..3359bdce 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Contract.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Contract.java @@ -1,24 +1,24 @@ -package cz.zcu.kiv.crce.compatibility; - -/** - * Date: 8.4.14 - * - * @author Jakub Danek - */ -public enum Contract { - - SYNTAX("syntax"), - SEMANTICS("semantics"), - INTERACTION("interaction"), - EXTRA_FUNCTIONAL("extra-functional"); - - private final String value; - - private Contract(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} +package cz.zcu.kiv.crce.compatibility; + +/** + * Date: 8.4.14 + * + * @author Jakub Danek + */ +public enum Contract { + + SYNTAX("syntax"), + SEMANTICS("semantics"), + INTERACTION("interaction"), + EXTRA_FUNCTIONAL("extra-functional"); + + private final String value; + + private Contract(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Diff.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Diff.java index aa06f41b..3c782738 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Diff.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Diff.java @@ -1,92 +1,92 @@ -package cz.zcu.kiv.crce.compatibility; - - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Detailed description of differences between two bundles. - * - * Date: 16.11.13 - * - * @author Jakub Danek - */ -public interface Diff { - - /** - * DifferenceLevel represents particular part of bundle this - * diff is related to. E.g. whole package, class or just a method or a field. - * - * @return - */ - @Nonnull - DifferenceLevel getLevel(); - - void setLevel(@Nonnull DifferenceLevel level); - - /** - * Name of the element this diff is related to. E.g. a class name. - * - * @return - */ - @Nonnull - String getName(); - - void setName(@Nonnull String name); - - /** - * Difference value represent the type of change made. - * - * @return - */ - @Nonnull - Difference getValue(); - - void setValue(@Nonnull Difference value); - - /** - * Children represent more detailed difference data. - *

- * E.g. for a package, children would list modified classes. - * - * @return - */ - @Nonnull - List getChildren(); - - void addChild(@Nonnull Diff child); - - void addChildren(@Nonnull List children); - - /** - * Role represents meaning of the item this diff is about. - *

- * Capability (e.g. exported packages) or requirement. - * - * @return - */ - @Nullable - DifferenceRole getRole(); - - void setRole(@Nullable DifferenceRole role); - - /** - * Namespace value. - *

- * E.g. osgi.wiring.package for exported/imported packages of OSGi bundle - * - * @return - */ - @Nullable - String getNamespace(); - - void setNamespace(@Nullable String namespace); - - @Nullable - String getSyntax(); - - void setSyntax(@Nullable String syntax); - -} +package cz.zcu.kiv.crce.compatibility; + + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * Detailed description of differences between two bundles. + * + * Date: 16.11.13 + * + * @author Jakub Danek + */ +public interface Diff { + + /** + * DifferenceLevel represents particular part of bundle this + * diff is related to. E.g. whole package, class or just a method or a field. + * + * @return + */ + @Nonnull + DifferenceLevel getLevel(); + + void setLevel(@Nonnull DifferenceLevel level); + + /** + * Name of the element this diff is related to. E.g. a class name. + * + * @return + */ + @Nonnull + String getName(); + + void setName(@Nonnull String name); + + /** + * Difference value represent the type of change made. + * + * @return + */ + @Nonnull + Difference getValue(); + + void setValue(@Nonnull Difference value); + + /** + * Children represent more detailed difference data. + *

+ * E.g. for a package, children would list modified classes. + * + * @return + */ + @Nonnull + List getChildren(); + + void addChild(@Nonnull Diff child); + + void addChildren(@Nonnull List children); + + /** + * Role represents meaning of the item this diff is about. + *

+ * Capability (e.g. exported packages) or requirement. + * + * @return + */ + @Nullable + DifferenceRole getRole(); + + void setRole(@Nullable DifferenceRole role); + + /** + * Namespace value. + *

+ * E.g. osgi.wiring.package for exported/imported packages of OSGi bundle + * + * @return + */ + @Nullable + String getNamespace(); + + void setNamespace(@Nullable String namespace); + + @Nullable + String getSyntax(); + + void setSyntax(@Nullable String syntax); + +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Difference.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Difference.java index 933e95de..32c38c79 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Difference.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/Difference.java @@ -1,93 +1,93 @@ -package cz.zcu.kiv.crce.compatibility; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - -/** - * List of possible difference classes between two resource elements. - * - * Date: 25.3.15 - * - * @author Jakub Danek - */ -@XmlType -@XmlEnum -public enum Difference { - @XmlEnumValue("NON") - NON("None"), - @XmlEnumValue("INS") - INS("Insertion"), - @XmlEnumValue("DEL") - DEL("Deletetion"), - @XmlEnumValue("GEN") - GEN("Generalization"), - @XmlEnumValue("SPE") - SPE("Specialization"), - @XmlEnumValue("MUT") - MUT("Mutation"), - @XmlEnumValue("UNK") - UNK("Unknown"); - - private String name; - - private Difference(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - /** - * Returns direct opposite of the value. - * - * INS to DEL - * SPE to GEN - * and vice versa. - * - * Returns the value itself if there is no opposite (NON, MUT, UNK) - * - * @return - */ - public Difference flip() { - switch (this) { - case DEL: - return INS; - case INS: - return DEL; - case GEN: - return SPE; - case SPE: - return GEN; - default: - return this; - } - } - - /** - * Returns superset value if possible: - * - * DEL -> GEN - * INS -> SPE - * - * or returns the value itself. - * @return - */ - public Difference formalize() { - switch (this) { - case DEL: - return GEN; - case INS: - return SPE; - default: - return this; - } - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.name); - return sb.toString(); - } +package cz.zcu.kiv.crce.compatibility; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +/** + * List of possible difference classes between two resource elements. + * + * Date: 25.3.15 + * + * @author Jakub Danek + */ +@XmlType +@XmlEnum +public enum Difference { + @XmlEnumValue("NON") + NON("None"), + @XmlEnumValue("INS") + INS("Insertion"), + @XmlEnumValue("DEL") + DEL("Deletetion"), + @XmlEnumValue("GEN") + GEN("Generalization"), + @XmlEnumValue("SPE") + SPE("Specialization"), + @XmlEnumValue("MUT") + MUT("Mutation"), + @XmlEnumValue("UNK") + UNK("Unknown"); + + private String name; + + private Difference(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + /** + * Returns direct opposite of the value. + * + * INS to DEL + * SPE to GEN + * and vice versa. + * + * Returns the value itself if there is no opposite (NON, MUT, UNK) + * + * @return + */ + public Difference flip() { + switch (this) { + case DEL: + return INS; + case INS: + return DEL; + case GEN: + return SPE; + case SPE: + return GEN; + default: + return this; + } + } + + /** + * Returns superset value if possible: + * + * DEL -> GEN + * INS -> SPE + * + * or returns the value itself. + * @return + */ + public Difference formalize() { + switch (this) { + case DEL: + return GEN; + case INS: + return SPE; + default: + return this; + } + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(this.name); + return sb.toString(); + } } \ No newline at end of file diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceLevel.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceLevel.java index ddacf7a1..a7154d98 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceLevel.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceLevel.java @@ -1,41 +1,41 @@ -package cz.zcu.kiv.crce.compatibility; - - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - -/** - * Enumeration for specification of level which a difference value is related to. - *

- * Package, class, operation (method or constructor) or field are meant by the level. - *

- * Date: 13.3.14 - * - * @author Jakub Danek - */ -@XmlType -@XmlEnum -public enum DifferenceLevel { - - @XmlEnumValue("package") - PACKAGE("package"), - @XmlEnumValue("type") - TYPE("type"), - @XmlEnumValue("operation") - OPERATION("operation"), //both methods and constructors - @XmlEnumValue("field") - FIELD("field"), - @XmlEnumValue("unknown") - UNKNOWN("unknown"); - - private final String value; - - private DifferenceLevel(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} +package cz.zcu.kiv.crce.compatibility; + + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +/** + * Enumeration for specification of level which a difference value is related to. + *

+ * Package, class, operation (method or constructor) or field are meant by the level. + *

+ * Date: 13.3.14 + * + * @author Jakub Danek + */ +@XmlType +@XmlEnum +public enum DifferenceLevel { + + @XmlEnumValue("package") + PACKAGE("package"), + @XmlEnumValue("type") + TYPE("type"), + @XmlEnumValue("operation") + OPERATION("operation"), //both methods and constructors + @XmlEnumValue("field") + FIELD("field"), + @XmlEnumValue("unknown") + UNKNOWN("unknown"); + + private final String value; + + private DifferenceLevel(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceRole.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceRole.java index 3fd10d45..07b7f4e8 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceRole.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/DifferenceRole.java @@ -1,31 +1,31 @@ -package cz.zcu.kiv.crce.compatibility; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - -/** - * Enumeration of possible roles of compared bundle parts. - *

- * Date: 13.3.14 - * - * @author Jakub Danek - */ -@XmlType -@XmlEnum -public enum DifferenceRole { - @XmlEnumValue("CAP") - CAPABILITY("capability"), - @XmlEnumValue("REQ") - REQUIREMENT("requirement"); - - private final String value; - - private DifferenceRole(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} +package cz.zcu.kiv.crce.compatibility; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +/** + * Enumeration of possible roles of compared bundle parts. + *

+ * Date: 13.3.14 + * + * @author Jakub Danek + */ +@XmlType +@XmlEnum +public enum DifferenceRole { + @XmlEnumValue("CAP") + CAPABILITY("capability"), + @XmlEnumValue("REQ") + REQUIREMENT("requirement"); + + private final String value; + + private DifferenceRole(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/namespace/NsCrceCompatibility.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/namespace/NsCrceCompatibility.java index e2568441..6bebae13 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/namespace/NsCrceCompatibility.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/namespace/NsCrceCompatibility.java @@ -1,18 +1,18 @@ -package cz.zcu.kiv.crce.compatibility.namespace; - -/** - * Class with identifier strings for CRCE Compatibility module. - *

- * Date: 18.3.14 - * - * @author Jakub Danek - */ -public class NsCrceCompatibility { - - /** - * CRCE Compatibility namespace identifier - */ - public static final String NAMESPACE__CRCE_COMPATIBILITY = "crce.compatibility"; - - public static final String DIFF_SYNTAX_JAVA = "java"; -} +package cz.zcu.kiv.crce.compatibility.namespace; + +/** + * Class with identifier strings for CRCE Compatibility module. + *

+ * Date: 18.3.14 + * + * @author Jakub Danek + */ +public class NsCrceCompatibility { + + /** + * CRCE Compatibility namespace identifier + */ + public static final String NAMESPACE__CRCE_COMPATIBILITY = "crce.compatibility"; + + public static final String DIFF_SYNTAX_JAVA = "java"; +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilitySearchService.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilitySearchService.java index e9748071..15721f96 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilitySearchService.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilitySearchService.java @@ -1,70 +1,70 @@ -package cz.zcu.kiv.crce.compatibility.service; - -import java.util.List; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * Service for searching compatibilities or resources by compatibility criteria. - *

- * Doesnt contain services for modification of compatibility data. - *

- * Date: 20.11.13 - * - * @author Jakub Danek - */ -public interface CompatibilitySearchService { - - /** - * List all compatibility data of the given resource with upper version. - * - * @param resource resource present in crce - * @return list - */ - List listUpperCompatibilities(Resource resource); - - /** - * List all compatibility data of the given resource with lower versions. - * - * @param resource resource present in crce - * @return list - */ - List listLowerCompatibilities(Resource resource); - - /** - * Find the nearest version of the same resource name which is available for upgrade (has higher - * version and is strictly compatible). - * - * @param resource resource to upgrade - * @return strictly compatible resource or null if none found - */ - Resource findNearestUpgrade(Resource resource); - - /** - * Find the highest version of the same resource name which is available for upgrade (has higher - * version and is strictly compatible). - * - * @param resource resource to upgrade - * @return strictly compatible resource or null if none found - */ - Resource findHighestUpgrade(Resource resource); - - /** - * Find the highest version of the same resource name which is available for downgrade (has lower - * version and is strictly compatible). - * - * @param resource resource to upgrade - * @return strictly compatible resource or null if none found - */ - Resource findNearestDowngrade(Resource resource); - - /** - * Find the lowest version of the same resource name which is available for downgrage (has lower - * version and is strictly compatible). - * - * @param resource resource to upgrade - * @return strictly compatible resource or null if none found - */ - Resource findLowestDowngrade(Resource resource); -} +package cz.zcu.kiv.crce.compatibility.service; + +import java.util.List; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * Service for searching compatibilities or resources by compatibility criteria. + *

+ * Doesnt contain services for modification of compatibility data. + *

+ * Date: 20.11.13 + * + * @author Jakub Danek + */ +public interface CompatibilitySearchService { + + /** + * List all compatibility data of the given resource with upper version. + * + * @param resource resource present in crce + * @return list + */ + List listUpperCompatibilities(Resource resource); + + /** + * List all compatibility data of the given resource with lower versions. + * + * @param resource resource present in crce + * @return list + */ + List listLowerCompatibilities(Resource resource); + + /** + * Find the nearest version of the same resource name which is available for upgrade (has higher + * version and is strictly compatible). + * + * @param resource resource to upgrade + * @return strictly compatible resource or null if none found + */ + Resource findNearestUpgrade(Resource resource); + + /** + * Find the highest version of the same resource name which is available for upgrade (has higher + * version and is strictly compatible). + * + * @param resource resource to upgrade + * @return strictly compatible resource or null if none found + */ + Resource findHighestUpgrade(Resource resource); + + /** + * Find the highest version of the same resource name which is available for downgrade (has lower + * version and is strictly compatible). + * + * @param resource resource to upgrade + * @return strictly compatible resource or null if none found + */ + Resource findNearestDowngrade(Resource resource); + + /** + * Find the lowest version of the same resource name which is available for downgrage (has lower + * version and is strictly compatible). + * + * @param resource resource to upgrade + * @return strictly compatible resource or null if none found + */ + Resource findLowestDowngrade(Resource resource); +} diff --git a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilityService.java b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilityService.java index f213123a..c1f69b74 100644 --- a/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilityService.java +++ b/modules/crce-compatibility-api/src/main/java/cz/zcu/kiv/crce/compatibility/service/CompatibilityService.java @@ -1,44 +1,44 @@ -package cz.zcu.kiv.crce.compatibility.service; - -import java.util.List; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * Service for Compatibility data management. - *

- * Allows user to create and modify Compatibility data. For convenience provides all available search capabilities - * as well. - *

- * Date: 19.11.13 - * - * @author Jakub Danek - */ -public interface CompatibilityService extends CompatibilitySearchService { - /** - * Calculates Compatibility data between the {@code resource} and the list of {@code additionalBaseResources} - * - * @param resource new resource - * @param additionalBaseResources list of resources to be used as base - * @return calculated compatibilities - */ - List calculateAdditionalCompatibilities(Resource resource, List additionalBaseResources); - - /** - * Calculates Compatibility data between {@code resource} and all its previous versions. - * - * @param resource new resource - * @return calculated compatibilities - */ - List calculateCompatibilities(Resource resource); - - /** - * Removes all compatibility information about the resource - * i.e. all Compatibilities where the resource has been used as either - * upper or lower value. - * - * @param resource the resource to be removed - */ - void removeCompatibilities(Resource resource); -} +package cz.zcu.kiv.crce.compatibility.service; + +import java.util.List; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * Service for Compatibility data management. + *

+ * Allows user to create and modify Compatibility data. For convenience provides all available search capabilities + * as well. + *

+ * Date: 19.11.13 + * + * @author Jakub Danek + */ +public interface CompatibilityService extends CompatibilitySearchService { + /** + * Calculates Compatibility data between the {@code resource} and the list of {@code additionalBaseResources} + * + * @param resource new resource + * @param additionalBaseResources list of resources to be used as base + * @return calculated compatibilities + */ + List calculateAdditionalCompatibilities(Resource resource, List additionalBaseResources); + + /** + * Calculates Compatibility data between {@code resource} and all its previous versions. + * + * @param resource new resource + * @return calculated compatibilities + */ + List calculateCompatibilities(Resource resource); + + /** + * Removes all compatibility information about the resource + * i.e. all Compatibilities where the resource has been used as either + * upper or lower value. + * + * @param resource the resource to be removed + */ + void removeCompatibilities(Resource resource); +} diff --git a/modules/crce-compatibility-api/src/main/resources/cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd b/modules/crce-compatibility-api/src/main/resources/cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd index 69402d01..be16e047 100644 --- a/modules/crce-compatibility-api/src/main/resources/cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd +++ b/modules/crce-compatibility-api/src/main/resources/cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd @@ -1,110 +1,110 @@ - - - - - - - Information about resource compatibility with another resource. Difference - meta-data included. - - - - - - - - - - - Name of the base resource which this compatibility instance relates to. - - - - - - - Version of the base resource which this compatibility instance relates to. - - - - - - - Area of the compatibility - e.g. syntax - - - - - - - Aggregated difference value between the two resources. - - - - - - - - - - Piece of difference metadata between resource contents. E.g. changes of a - class, method, etc. - - - - - - - - - - Type of element this diff is related to - e.g. package, class or method. - - - - - - - Role of the element this diff is related to - e.g. a capability or requirement - - - - - - - Namespace of the diff. - - - - - - - Name of the element this diff is related to. - - - - - - - Language syntax the element is consistent with (e.g. if it is a Java class, then - syntax is Java) - - - - - - - Aggregated difference value for the element. - - - - + + + + + + + Information about resource compatibility with another resource. Difference + meta-data included. + + + + + + + + + + + Name of the base resource which this compatibility instance relates to. + + + + + + + Version of the base resource which this compatibility instance relates to. + + + + + + + Area of the compatibility - e.g. syntax + + + + + + + Aggregated difference value between the two resources. + + + + + + + + + + Piece of difference metadata between resource contents. E.g. changes of a + class, method, etc. + + + + + + + + + + Type of element this diff is related to - e.g. package, class or method. + + + + + + + Role of the element this diff is related to - e.g. a capability or requirement + + + + + + + Namespace of the diff. + + + + + + + Name of the element this diff is related to. + + + + + + + Language syntax the element is consistent with (e.g. if it is a Java class, then + syntax is Java) + + + + + + + Aggregated difference value for the element. + + + + \ No newline at end of file diff --git a/modules/crce-compatibility-dao-api/pom.xml b/modules/crce-compatibility-dao-api/pom.xml index 442780a4..55a2c7bb 100644 --- a/modules/crce-compatibility-dao-api/pom.xml +++ b/modules/crce-compatibility-dao-api/pom.xml @@ -1,42 +1,42 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-compatibility-dao-api - bundle - - CRCE - Compatibility DAO API - - - ${namespace}.compatibility.dao.api - ${namespace}.compatibility.dao - - - - - - - ${project.groupId} - crce-core - pom - - - - - - ${project.groupId} - crce-compatibility-api - ${project.version} - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-compatibility-dao-api + bundle + + CRCE - Compatibility DAO API + + + ${namespace}.compatibility.dao.api + ${namespace}.compatibility.dao + + + + + + + ${project.groupId} + crce-core + pom + + + + + + ${project.groupId} + crce-compatibility-api + ${project.version} + + + + \ No newline at end of file diff --git a/modules/crce-compatibility-dao-api/src/main/java/cz/zcu/kiv/crce/compatibility/dao/CompatibilityDao.java b/modules/crce-compatibility-dao-api/src/main/java/cz/zcu/kiv/crce/compatibility/dao/CompatibilityDao.java index b9cb8cea..ded23bbe 100644 --- a/modules/crce-compatibility-dao-api/src/main/java/cz/zcu/kiv/crce/compatibility/dao/CompatibilityDao.java +++ b/modules/crce-compatibility-dao-api/src/main/java/cz/zcu/kiv/crce/compatibility/dao/CompatibilityDao.java @@ -1,87 +1,87 @@ -package cz.zcu.kiv.crce.compatibility.dao; - -import java.util.List; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Interface for Compatibility DAO object. - *

- * Date: 16.11.13 - * - * @author Jakub Danek - */ -public interface CompatibilityDao { - - /** - * @param id unique ID, implementation depends on underlying persistence design - * @return compatibility with the given ID or null if not found - */ - Compatibility readCompability(String id); - - /** - * Saves new Compatibility or updates existing. - * - * @param compatibility compatibility to create or update (difference recognition depends on underlying implemetnation) - * @return created/persisted object (ensured to have ID set) - */ - Compatibility saveCompatibility(Compatibility compatibility); - - /** - * Deletes the compability from persistence. - * - * @param compatibility compatibility to delete - */ - void deleteCompatibility(Compatibility compatibility); - - /** - * Deletes all compatibility data related to a resource with the given name an version. - * That is it doesnt matter whether the resource has been the new version or the base. - * - * @param resourceName symbolic name - * @param resourceVersion version - */ - void deleteAllRelatedCompatibilities(String resourceName, Version resourceVersion); - - /** - * List of all compatibilities owned by a resource with the given name and version - * i.e. all Compatibility data where this resource has been the "new" version - * - * @param resourceName name of the resource - * @param resourceVersion version of the resource - * @return - */ - List listOwnedCompatibilities(String resourceName, Version resourceVersion); - - /* - List of differences - */ - - /** - * Returns Compatibility data for provided baseName and with resource version higher than - * the base version provided. - *

- * The diffValue of Compatibility must be one of those in differences list. - * - * @param baseName requested base name - * @param baseVersion requested base version - * @param differences list of permitted difference values - * @return list of compatibilities or empty list if none found - */ - List findHigher(String baseName, Version baseVersion, List differences); - - /** - * Returns Compatibility data for provided resourceName and with base version lower than - * the resource version provided. - *

- * The diffValue of Compatibility must be one of those in differences list. - * - * @param resourceName requested base name - * @param resourceVersion requested base version - * @param differences list of permitted difference values - * @return list of compatibilities or empty list if none found - */ - List findLower(String resourceName, Version resourceVersion, List differences); -} +package cz.zcu.kiv.crce.compatibility.dao; + +import java.util.List; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Interface for Compatibility DAO object. + *

+ * Date: 16.11.13 + * + * @author Jakub Danek + */ +public interface CompatibilityDao { + + /** + * @param id unique ID, implementation depends on underlying persistence design + * @return compatibility with the given ID or null if not found + */ + Compatibility readCompability(String id); + + /** + * Saves new Compatibility or updates existing. + * + * @param compatibility compatibility to create or update (difference recognition depends on underlying implemetnation) + * @return created/persisted object (ensured to have ID set) + */ + Compatibility saveCompatibility(Compatibility compatibility); + + /** + * Deletes the compability from persistence. + * + * @param compatibility compatibility to delete + */ + void deleteCompatibility(Compatibility compatibility); + + /** + * Deletes all compatibility data related to a resource with the given name an version. + * That is it doesnt matter whether the resource has been the new version or the base. + * + * @param resourceName symbolic name + * @param resourceVersion version + */ + void deleteAllRelatedCompatibilities(String resourceName, Version resourceVersion); + + /** + * List of all compatibilities owned by a resource with the given name and version + * i.e. all Compatibility data where this resource has been the "new" version + * + * @param resourceName name of the resource + * @param resourceVersion version of the resource + * @return + */ + List listOwnedCompatibilities(String resourceName, Version resourceVersion); + + /* + List of differences + */ + + /** + * Returns Compatibility data for provided baseName and with resource version higher than + * the base version provided. + *

+ * The diffValue of Compatibility must be one of those in differences list. + * + * @param baseName requested base name + * @param baseVersion requested base version + * @param differences list of permitted difference values + * @return list of compatibilities or empty list if none found + */ + List findHigher(String baseName, Version baseVersion, List differences); + + /** + * Returns Compatibility data for provided resourceName and with base version lower than + * the resource version provided. + *

+ * The diffValue of Compatibility must be one of those in differences list. + * + * @param resourceName requested base name + * @param resourceVersion requested base version + * @param differences list of permitted difference values + * @return list of compatibilities or empty list if none found + */ + List findLower(String resourceName, Version resourceVersion, List differences); +} diff --git a/modules/crce-compatibility-dao-mongodb/osgi.bnd b/modules/crce-compatibility-dao-mongodb/osgi.bnd index 75d1af80..233fc0c9 100644 --- a/modules/crce-compatibility-dao-mongodb/osgi.bnd +++ b/modules/crce-compatibility-dao-mongodb/osgi.bnd @@ -1,5 +1,5 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + Bundle-Activator: ${bundle.namespace}.internal.Activator \ No newline at end of file diff --git a/modules/crce-compatibility-dao-mongodb/pom.xml b/modules/crce-compatibility-dao-mongodb/pom.xml index 01fae91b..a11ac8ff 100644 --- a/modules/crce-compatibility-dao-mongodb/pom.xml +++ b/modules/crce-compatibility-dao-mongodb/pom.xml @@ -1,57 +1,57 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-compatibility-dao-mongodb - bundle - - CRCE - Compatibility DAO MongoDB Implementation - - - ${namespace}.compatibility.dao.mongodb - ${namespace}.compatibility.dao - - - - - - - ${project.groupId} - crce-core - pom - - - - - - ${project.groupId} - crce-compatibility-api - ${project.version} - - - ${project.groupId} - crce-compatibility-dao-api - ${project.version} - - - - - org.mongodb - mongo-java-driver - - - - junit - junit - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-compatibility-dao-mongodb + bundle + + CRCE - Compatibility DAO MongoDB Implementation + + + ${namespace}.compatibility.dao.mongodb + ${namespace}.compatibility.dao + + + + + + + ${project.groupId} + crce-core + pom + + + + + + ${project.groupId} + crce-compatibility-api + ${project.version} + + + ${project.groupId} + crce-compatibility-dao-api + ${project.version} + + + + + org.mongodb + mongo-java-driver + + + + junit + junit + + + \ No newline at end of file diff --git a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/Activator.java b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/Activator.java index cdcccab3..3aabf5d1 100644 --- a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/Activator.java +++ b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/Activator.java @@ -1,64 +1,64 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; -import org.osgi.service.cm.ManagedService; - -import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; -import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; - -/** - * Date: 17.11.13 - * - * @author Jakub Danek - */ -public class Activator extends DependencyActivatorBase { - /** - * Initialize the dependency manager. Here you can add all components and their dependencies. - * If something goes wrong and you do not want your bundle to be started, you can throw an - * exception. This exception will be passed on to the start() method of the - * bundle activator, causing the bundle not to start. - * - * @param context the bundle context - * @param manager the dependency manager - * @throws Exception if the initialization fails - */ - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - //set service PID - Dictionary compatibilityProps = new Hashtable(1); - compatibilityProps.put("service.pid","cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao"); - - //Register as both CompatibilityDao and ManagedService - String s[] = {CompatibilityDao.class.getName(), ManagedService.class.getName()}; - manager.add(createComponent() - .setInterface(s, compatibilityProps) - .setFactory(new CompatibilityDaoMongoFactory(), "get") - //requires CompatibilityFactory for proper mapping - .add(createServiceDependency().setRequired(true) - .setService(CompatibilityFactory.class)) - ); - } - - /** - * Destroy the dependency manager. Here you can remove all components and their dependencies. - * Actually, the base class will clean up your dependencies anyway, so most of the time you - * don't need to do anything here. - *

- * If something goes wrong and you do not want your bundle to be stopped, you can throw an - * exception. This exception will be passed on to the stop() method of the - * bundle activator, causing the bundle not to stop. - * - * @param context the bundle context - * @param manager the dependency manager - * @throws Exception if the destruction fails - */ - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - DbContext.stop(); //close existing mongo connections - } -} +package cz.zcu.kiv.crce.compatibility.dao.internal; + +import java.util.Dictionary; +import java.util.Hashtable; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; +import org.osgi.service.cm.ManagedService; + +import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; +import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; + +/** + * Date: 17.11.13 + * + * @author Jakub Danek + */ +public class Activator extends DependencyActivatorBase { + /** + * Initialize the dependency manager. Here you can add all components and their dependencies. + * If something goes wrong and you do not want your bundle to be started, you can throw an + * exception. This exception will be passed on to the start() method of the + * bundle activator, causing the bundle not to start. + * + * @param context the bundle context + * @param manager the dependency manager + * @throws Exception if the initialization fails + */ + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + //set service PID + Dictionary compatibilityProps = new Hashtable(1); + compatibilityProps.put("service.pid","cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao"); + + //Register as both CompatibilityDao and ManagedService + String s[] = {CompatibilityDao.class.getName(), ManagedService.class.getName()}; + manager.add(createComponent() + .setInterface(s, compatibilityProps) + .setFactory(new CompatibilityDaoMongoFactory(), "get") + //requires CompatibilityFactory for proper mapping + .add(createServiceDependency().setRequired(true) + .setService(CompatibilityFactory.class)) + ); + } + + /** + * Destroy the dependency manager. Here you can remove all components and their dependencies. + * Actually, the base class will clean up your dependencies anyway, so most of the time you + * don't need to do anything here. + *

+ * If something goes wrong and you do not want your bundle to be stopped, you can throw an + * exception. This exception will be passed on to the stop() method of the + * bundle activator, causing the bundle not to stop. + * + * @param context the bundle context + * @param manager the dependency manager + * @throws Exception if the destruction fails + */ + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + DbContext.stop(); //close existing mongo connections + } +} diff --git a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoFactory.java b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoFactory.java index 97d56e8d..f195d826 100644 --- a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoFactory.java +++ b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoFactory.java @@ -1,42 +1,42 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal; - -import java.net.UnknownHostException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; - -/** - * Factory for CompatibilityDao implementation using MongoDB. - * - * Ensures the dao object is singleton within the application. - * - * Date: 17.11.13 - * - * @author Jakub Danek - */ -public class CompatibilityDaoMongoFactory { - private static final Logger logger = LoggerFactory.getLogger(CompatibilityDaoMongoFactory.class); - - private CompatibilityDao dao; - - /** - * - * @return instance of CompatibilityDao MongoDB implementation. - */ - public CompatibilityDao get() { - if(dao == null) { - try { - dao = new CompatibilityDaoMongoImpl(DbContext.getConnection()); - } catch (UnknownHostException e) { - logger.error("Unable to open connection to the database!", e); - return null; - } - } - - return dao; - } - - -} +package cz.zcu.kiv.crce.compatibility.dao.internal; + +import java.net.UnknownHostException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; + +/** + * Factory for CompatibilityDao implementation using MongoDB. + * + * Ensures the dao object is singleton within the application. + * + * Date: 17.11.13 + * + * @author Jakub Danek + */ +public class CompatibilityDaoMongoFactory { + private static final Logger logger = LoggerFactory.getLogger(CompatibilityDaoMongoFactory.class); + + private CompatibilityDao dao; + + /** + * + * @return instance of CompatibilityDao MongoDB implementation. + */ + public CompatibilityDao get() { + if(dao == null) { + try { + dao = new CompatibilityDaoMongoImpl(DbContext.getConnection()); + } catch (UnknownHostException e) { + logger.error("Unable to open connection to the database!", e); + return null; + } + } + + return dao; + } + + +} diff --git a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoImpl.java b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoImpl.java index 35470e9f..8dec4608 100644 --- a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoImpl.java +++ b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/CompatibilityDaoMongoImpl.java @@ -1,283 +1,283 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal; - -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.List; - -import org.bson.types.ObjectId; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.mongodb.BasicDBObject; -import com.mongodb.BasicDBObjectBuilder; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.DBObject; -import com.mongodb.MongoClient; -import com.mongodb.QueryBuilder; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; -import cz.zcu.kiv.crce.compatibility.dao.internal.mapping.MongoCompatibilityMapper; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Implementation of CompatibilityDao for MongoDB. - * - * Implements ManagedService - change of database on air is supported. This feature is however - * meant primarily for use during integration tests. Use with caution. - * - * Database access is thread safe due to MongoDB inner implementation. Currently whole database (DB instance) is - * locked - multiple read locks and single write lock with higher priority than the read locks. - * Read more at http://docs.mongodb.org/ecosystem/drivers/java-concurrency/ - * and http://docs.mongodb.org/manual/faq/concurrency/ - * - * Date: 17.11.13 - * - * @author Jakub Danek - */ -public class CompatibilityDaoMongoImpl implements CompatibilityDao, ManagedService { - - private static final Logger logger = LoggerFactory.getLogger(CompatibilityDaoMongoImpl.class); - /* - * Flags for operation used during search by version. - * - * Either resources with higher or lower version are searched for. - */ - private static final int V_HIGHER = 1; - private static final int V_LOWER = 2; - - /* - OSGi stuff - */ - @Override - public void updated(Dictionary props) throws ConfigurationException { - String name = DbContext.DEFAULT_DB_NAME; - - if ( props != null) { - Object o = props.get("cz.zcu.kiv.crce.mongodb.dbname"); - if ( o != null ) - name = (String) o; - } - - if ( !dbName.equals(name) ) { - logger.info("Changing database to: {}", name); - openDB(name); - logger.info("Database has been changed."); - } - } - - /** - * Name of currently used database. - */ - private volatile String dbName = DbContext.DEFAULT_DB_NAME; - /** - * Convenient collection reference - */ - private DBCollection col; - /** - * Currently used database reference. - */ - private DB db; - private Object dbLock; - /** - * MongoClient reference holding current connection. - */ - private MongoClient client; - - private CompatibilityFactory factory; /*injected by DependencyManager*/ - - /** - * Creates new CompatibilityDao implementation for MongoDB - * @param client MongoDB driver client with open connection. - */ - public CompatibilityDaoMongoImpl(MongoClient client) { - this.client = client; - this.dbLock = new Object(); - openDB(dbName); - } - - /** - * Thread-safe method for switching database on-air. - * @param name name of the new database - */ - private void openDB(String name) { - synchronized (dbLock) { - dbName = name; - db = client.getDB(name); - col = db.getCollection("compatibility"); - } - } - - @Override - public Compatibility readCompability(String id) { - logger.debug("Read compatibility with id: {}", id); - BasicDBObject query = new BasicDBObject("_id", ObjectId.massageToObjectId(id)); - - DBObject ret = col.findOne(query); - - return MongoCompatibilityMapper.mapToCompatibility(ret, factory); - } - - @Override - public Compatibility saveCompatibility(Compatibility compatibility) { - DBObject cmp = MongoCompatibilityMapper.mapToDbObject(compatibility); - - //TODO catch MONGO exception for failure handling - col.save(cmp); - logger.debug("Saved compatibility: {}", cmp); - return MongoCompatibilityMapper.mapToCompatibility(cmp, factory); - } - - @Override - public void deleteCompatibility(Compatibility compatibility) { - if(logger.isDebugEnabled()) { - logger.debug("Delete compatibility id: {}", compatibility.getId()); - } - BasicDBObject query = new BasicDBObject("_id", ObjectId.massageToObjectId(compatibility.getId())); - col.remove(query); - } - - @Override - public void deleteAllRelatedCompatibilities(String resourceName, Version resourceVersion) { - logger.debug("Deleting all compatibility data related to {}-{}", resourceName, resourceVersion); - DBObject qRes = QueryBuilder.start(MongoCompatibilityMapper.C_RESOURCE_NAME).is(resourceName) - .and(MongoCompatibilityMapper.C_RESOURCE_VERSION).is(MongoCompatibilityMapper.mapVersion(resourceVersion)) - .get(); - DBObject qBase = QueryBuilder.start(MongoCompatibilityMapper.C_BASE_NAME).is(resourceName) - .and(MongoCompatibilityMapper.C_BASE_VERSION).is(MongoCompatibilityMapper.mapVersion(resourceVersion)) - .get(); - DBObject q = QueryBuilder.start().or(qRes, qBase).get(); - - col.remove(q); - } - - @Override - public List listOwnedCompatibilities(String resourceName, Version resourceVersion) { - DBObject query = BasicDBObjectBuilder.start(MongoCompatibilityMapper.C_RESOURCE_NAME, resourceName) - .add(MongoCompatibilityMapper.C_RESOURCE_VERSION, MongoCompatibilityMapper.mapVersion(resourceVersion)).get(); - - DBCursor cursor = col.find(query); - if(logger.isDebugEnabled()) { - logger.debug("Compatibilities found for {}-{}: {}", resourceName, resourceVersion, cursor.size()); - } - - return parseCursor(cursor); - } - - @Override - public List findHigher(String baseName, Version baseVersion, List difference) { - return findByVersion(V_HIGHER, baseName, baseVersion, difference); - } - - @Override - public List findLower(String resourceName, Version resourceVersion, List difference) { - return findByVersion(V_LOWER, resourceName, resourceVersion, difference); - } - - /** - * Shared method for Compatibility-data search by version. - * - * - * @param flag flag designating whether search for higher or lower version is requested - * @param name resource name - * @param version current resource version which will be compared against - * @param differences list of allowed difference values, at least one is required - * @return list of found compatibility data items - */ - private List findByVersion(int flag, String name, Version version, List differences) { - final String nameKey, fixedVersionKey, searchVersionkey, op; - switch (flag) { - case V_HIGHER: //search for higher versions - //method arguments represent the resource which has been compared-to - //query will return list of Compatibility data, where the provided resource (via arguments) served - //as BASE resource - nameKey = MongoCompatibilityMapper.C_BASE_NAME; - fixedVersionKey = MongoCompatibilityMapper.C_BASE_VERSION; - searchVersionkey = MongoCompatibilityMapper.C_RESOURCE_VERSION; - op = "$gt"; - break; - case V_LOWER: //search for lower versions - //method arguments represent the resource which was compared to all others - //query will return list of Compatibility data, where the provided resource (via arguments) served - //as NEW resource - nameKey = MongoCompatibilityMapper.C_RESOURCE_NAME; - fixedVersionKey = MongoCompatibilityMapper.C_RESOURCE_VERSION; - searchVersionkey = MongoCompatibilityMapper.C_BASE_VERSION; - op = "$lt"; - break; - default: //unsupported - throw new RuntimeException("Invalid flag argument!"); - } - - List diffNames = MongoCompatibilityMapper.parseEnum(differences); - - DBObject q = QueryBuilder.start(nameKey).is(name) //name - .and(fixedVersionKey).is(MongoCompatibilityMapper.mapVersion(version)) - .and(createVersionComparisonQuery(version, searchVersionkey, op)) - .and(MongoCompatibilityMapper.C_BUNDLE_DIFF).in(diffNames).get(); - - logger.debug("findByVersion params: name: {}; version: {}; differences: {}", name, version, differences); - logger.debug("findByVersion query, flag ({}): {}", flag, q); - DBCursor cursor = col.find(q); - return parseCursor(cursor); - } - - /** - * Parse cursor into a list of Compatibility items - * @param cursor cursor gained by a query execution - * @return list of Compatibilities or an empty list if cursor empty - */ - private List parseCursor(DBCursor cursor) { - List retList = new ArrayList(); - - - DBObject tmp; - while(cursor.hasNext()) { - tmp = cursor.next(); - retList.add(MongoCompatibilityMapper.mapToCompatibility(tmp, factory)); - } - - return retList; - } - - /** - * Creates query for greater/less than comparioson of serialized Version structure. - *
- *
- * NOTE: While this query works for EQUALITY comparison as well, it is not recommended due to performance overhead. - * Use simple query by serialized Version object instead. - * - * @param version version for comparions - * @param baseKey key of the version structure within document - * @param op operation for comparison (either $gt or $lt) - * @return query object - */ - private DBObject createVersionComparisonQuery(Version version, String baseKey, String op) { - String majorKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MAJOR; - String minorKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MINOR; - String microKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MICRO; - - DBObject major = BasicDBObjectBuilder.start(majorKey, new BasicDBObject(op, version.getMajor())) - .get(); - logger.debug("Version comparison query - major: {}", major); - DBObject minor = QueryBuilder.start().and(new BasicDBObject(majorKey, version.getMajor()), - new BasicDBObject(minorKey, new BasicDBObject(op, version.getMinor()))) - .get(); - logger.debug("Version comparison query - minor: {}", minor); - DBObject micro = QueryBuilder.start().and(new BasicDBObject(majorKey, version.getMajor()), - new BasicDBObject(minorKey, version.getMinor()), - new BasicDBObject(microKey, new BasicDBObject(op, version.getMicro()))) - .get(); - logger.debug("Version comparison query - micro: {}", micro); - - DBObject query = QueryBuilder.start().or(major, minor, micro).get(); - logger.debug("Version comparison query: {}", query); - return query; - } -} +package cz.zcu.kiv.crce.compatibility.dao.internal; + +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.List; + +import org.bson.types.ObjectId; +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.mongodb.BasicDBObject; +import com.mongodb.BasicDBObjectBuilder; +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.DBCursor; +import com.mongodb.DBObject; +import com.mongodb.MongoClient; +import com.mongodb.QueryBuilder; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.dao.CompatibilityDao; +import cz.zcu.kiv.crce.compatibility.dao.internal.mapping.MongoCompatibilityMapper; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Implementation of CompatibilityDao for MongoDB. + * + * Implements ManagedService - change of database on air is supported. This feature is however + * meant primarily for use during integration tests. Use with caution. + * + * Database access is thread safe due to MongoDB inner implementation. Currently whole database (DB instance) is + * locked - multiple read locks and single write lock with higher priority than the read locks. + * Read more at http://docs.mongodb.org/ecosystem/drivers/java-concurrency/ + * and http://docs.mongodb.org/manual/faq/concurrency/ + * + * Date: 17.11.13 + * + * @author Jakub Danek + */ +public class CompatibilityDaoMongoImpl implements CompatibilityDao, ManagedService { + + private static final Logger logger = LoggerFactory.getLogger(CompatibilityDaoMongoImpl.class); + /* + * Flags for operation used during search by version. + * + * Either resources with higher or lower version are searched for. + */ + private static final int V_HIGHER = 1; + private static final int V_LOWER = 2; + + /* + OSGi stuff + */ + @Override + public void updated(Dictionary props) throws ConfigurationException { + String name = DbContext.DEFAULT_DB_NAME; + + if ( props != null) { + Object o = props.get("cz.zcu.kiv.crce.mongodb.dbname"); + if ( o != null ) + name = (String) o; + } + + if ( !dbName.equals(name) ) { + logger.info("Changing database to: {}", name); + openDB(name); + logger.info("Database has been changed."); + } + } + + /** + * Name of currently used database. + */ + private volatile String dbName = DbContext.DEFAULT_DB_NAME; + /** + * Convenient collection reference + */ + private DBCollection col; + /** + * Currently used database reference. + */ + private DB db; + private Object dbLock; + /** + * MongoClient reference holding current connection. + */ + private MongoClient client; + + private CompatibilityFactory factory; /*injected by DependencyManager*/ + + /** + * Creates new CompatibilityDao implementation for MongoDB + * @param client MongoDB driver client with open connection. + */ + public CompatibilityDaoMongoImpl(MongoClient client) { + this.client = client; + this.dbLock = new Object(); + openDB(dbName); + } + + /** + * Thread-safe method for switching database on-air. + * @param name name of the new database + */ + private void openDB(String name) { + synchronized (dbLock) { + dbName = name; + db = client.getDB(name); + col = db.getCollection("compatibility"); + } + } + + @Override + public Compatibility readCompability(String id) { + logger.debug("Read compatibility with id: {}", id); + BasicDBObject query = new BasicDBObject("_id", ObjectId.massageToObjectId(id)); + + DBObject ret = col.findOne(query); + + return MongoCompatibilityMapper.mapToCompatibility(ret, factory); + } + + @Override + public Compatibility saveCompatibility(Compatibility compatibility) { + DBObject cmp = MongoCompatibilityMapper.mapToDbObject(compatibility); + + //TODO catch MONGO exception for failure handling + col.save(cmp); + logger.debug("Saved compatibility: {}", cmp); + return MongoCompatibilityMapper.mapToCompatibility(cmp, factory); + } + + @Override + public void deleteCompatibility(Compatibility compatibility) { + if(logger.isDebugEnabled()) { + logger.debug("Delete compatibility id: {}", compatibility.getId()); + } + BasicDBObject query = new BasicDBObject("_id", ObjectId.massageToObjectId(compatibility.getId())); + col.remove(query); + } + + @Override + public void deleteAllRelatedCompatibilities(String resourceName, Version resourceVersion) { + logger.debug("Deleting all compatibility data related to {}-{}", resourceName, resourceVersion); + DBObject qRes = QueryBuilder.start(MongoCompatibilityMapper.C_RESOURCE_NAME).is(resourceName) + .and(MongoCompatibilityMapper.C_RESOURCE_VERSION).is(MongoCompatibilityMapper.mapVersion(resourceVersion)) + .get(); + DBObject qBase = QueryBuilder.start(MongoCompatibilityMapper.C_BASE_NAME).is(resourceName) + .and(MongoCompatibilityMapper.C_BASE_VERSION).is(MongoCompatibilityMapper.mapVersion(resourceVersion)) + .get(); + DBObject q = QueryBuilder.start().or(qRes, qBase).get(); + + col.remove(q); + } + + @Override + public List listOwnedCompatibilities(String resourceName, Version resourceVersion) { + DBObject query = BasicDBObjectBuilder.start(MongoCompatibilityMapper.C_RESOURCE_NAME, resourceName) + .add(MongoCompatibilityMapper.C_RESOURCE_VERSION, MongoCompatibilityMapper.mapVersion(resourceVersion)).get(); + + DBCursor cursor = col.find(query); + if(logger.isDebugEnabled()) { + logger.debug("Compatibilities found for {}-{}: {}", resourceName, resourceVersion, cursor.size()); + } + + return parseCursor(cursor); + } + + @Override + public List findHigher(String baseName, Version baseVersion, List difference) { + return findByVersion(V_HIGHER, baseName, baseVersion, difference); + } + + @Override + public List findLower(String resourceName, Version resourceVersion, List difference) { + return findByVersion(V_LOWER, resourceName, resourceVersion, difference); + } + + /** + * Shared method for Compatibility-data search by version. + * + * + * @param flag flag designating whether search for higher or lower version is requested + * @param name resource name + * @param version current resource version which will be compared against + * @param differences list of allowed difference values, at least one is required + * @return list of found compatibility data items + */ + private List findByVersion(int flag, String name, Version version, List differences) { + final String nameKey, fixedVersionKey, searchVersionkey, op; + switch (flag) { + case V_HIGHER: //search for higher versions + //method arguments represent the resource which has been compared-to + //query will return list of Compatibility data, where the provided resource (via arguments) served + //as BASE resource + nameKey = MongoCompatibilityMapper.C_BASE_NAME; + fixedVersionKey = MongoCompatibilityMapper.C_BASE_VERSION; + searchVersionkey = MongoCompatibilityMapper.C_RESOURCE_VERSION; + op = "$gt"; + break; + case V_LOWER: //search for lower versions + //method arguments represent the resource which was compared to all others + //query will return list of Compatibility data, where the provided resource (via arguments) served + //as NEW resource + nameKey = MongoCompatibilityMapper.C_RESOURCE_NAME; + fixedVersionKey = MongoCompatibilityMapper.C_RESOURCE_VERSION; + searchVersionkey = MongoCompatibilityMapper.C_BASE_VERSION; + op = "$lt"; + break; + default: //unsupported + throw new RuntimeException("Invalid flag argument!"); + } + + List diffNames = MongoCompatibilityMapper.parseEnum(differences); + + DBObject q = QueryBuilder.start(nameKey).is(name) //name + .and(fixedVersionKey).is(MongoCompatibilityMapper.mapVersion(version)) + .and(createVersionComparisonQuery(version, searchVersionkey, op)) + .and(MongoCompatibilityMapper.C_BUNDLE_DIFF).in(diffNames).get(); + + logger.debug("findByVersion params: name: {}; version: {}; differences: {}", name, version, differences); + logger.debug("findByVersion query, flag ({}): {}", flag, q); + DBCursor cursor = col.find(q); + return parseCursor(cursor); + } + + /** + * Parse cursor into a list of Compatibility items + * @param cursor cursor gained by a query execution + * @return list of Compatibilities or an empty list if cursor empty + */ + private List parseCursor(DBCursor cursor) { + List retList = new ArrayList(); + + + DBObject tmp; + while(cursor.hasNext()) { + tmp = cursor.next(); + retList.add(MongoCompatibilityMapper.mapToCompatibility(tmp, factory)); + } + + return retList; + } + + /** + * Creates query for greater/less than comparioson of serialized Version structure. + *
+ *
+ * NOTE: While this query works for EQUALITY comparison as well, it is not recommended due to performance overhead. + * Use simple query by serialized Version object instead. + * + * @param version version for comparions + * @param baseKey key of the version structure within document + * @param op operation for comparison (either $gt or $lt) + * @return query object + */ + private DBObject createVersionComparisonQuery(Version version, String baseKey, String op) { + String majorKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MAJOR; + String minorKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MINOR; + String microKey = baseKey + "." + MongoCompatibilityMapper.C_VERSION_MICRO; + + DBObject major = BasicDBObjectBuilder.start(majorKey, new BasicDBObject(op, version.getMajor())) + .get(); + logger.debug("Version comparison query - major: {}", major); + DBObject minor = QueryBuilder.start().and(new BasicDBObject(majorKey, version.getMajor()), + new BasicDBObject(minorKey, new BasicDBObject(op, version.getMinor()))) + .get(); + logger.debug("Version comparison query - minor: {}", minor); + DBObject micro = QueryBuilder.start().and(new BasicDBObject(majorKey, version.getMajor()), + new BasicDBObject(minorKey, version.getMinor()), + new BasicDBObject(microKey, new BasicDBObject(op, version.getMicro()))) + .get(); + logger.debug("Version comparison query - micro: {}", micro); + + DBObject query = QueryBuilder.start().or(major, minor, micro).get(); + logger.debug("Version comparison query: {}", query); + return query; + } +} diff --git a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/DbContext.java b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/DbContext.java index 8a81b286..a15389f4 100644 --- a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/DbContext.java +++ b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/DbContext.java @@ -1,45 +1,45 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal; - -import java.net.UnknownHostException; - -import com.mongodb.MongoClient; - -/** - * Context class responsible for connection management to MongoDB. - *

- * Probably should be relocated to a public place in case more modules started using the database. - *

- * Date: 17.11.13 - * - * @author Jakub Danek - */ -public class DbContext { - - /** - * Name of the database used by CRCE. - */ - public static final String DEFAULT_DB_NAME = "crce"; - - private static MongoClient client; - - /** - * Singleton instance of Mongo connection driver. Client holds its own connection pool and therefore - * should be used as singleton within the application - */ - public static MongoClient getConnection() throws UnknownHostException { - if (client == null) { - client = new MongoClient("localhost", 27017); - } - - return client; - } - - /** - * Close current connection. Probably used only on bundle shutdown. - */ - public static void stop() { - if (client != null) { - client.close(); - } - } -} +package cz.zcu.kiv.crce.compatibility.dao.internal; + +import java.net.UnknownHostException; + +import com.mongodb.MongoClient; + +/** + * Context class responsible for connection management to MongoDB. + *

+ * Probably should be relocated to a public place in case more modules started using the database. + *

+ * Date: 17.11.13 + * + * @author Jakub Danek + */ +public class DbContext { + + /** + * Name of the database used by CRCE. + */ + public static final String DEFAULT_DB_NAME = "crce"; + + private static MongoClient client; + + /** + * Singleton instance of Mongo connection driver. Client holds its own connection pool and therefore + * should be used as singleton within the application + */ + public static MongoClient getConnection() throws UnknownHostException { + if (client == null) { + client = new MongoClient("localhost", 27017); + } + + return client; + } + + /** + * Close current connection. Probably used only on bundle shutdown. + */ + public static void stop() { + if (client != null) { + client.close(); + } + } +} diff --git a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapper.java b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapper.java index c18ef23a..1d239f9d 100644 --- a/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapper.java +++ b/modules/crce-compatibility-dao-mongodb/src/main/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapper.java @@ -1,250 +1,250 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; - -import java.util.ArrayList; -import java.util.List; - -import org.bson.types.ObjectId; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; -import cz.zcu.kiv.crce.compatibility.Contract; -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.DifferenceRole; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Serialization/Deserialization support class between Compatibility and MongoDB. - * - * Date: 17.11.13 - * - * @author Jakub Danek - */ -public class MongoCompatibilityMapper { - - /* - KEY SPACE - */ - public static final String C_RESOURCE_NAME = "resourceName"; - public static final String C_RESOURCE_VERSION = "resourceVersion"; - public static final String C_BASE_NAME = "baseName"; - public static final String C_BASE_VERSION = "baseVersion"; - public static final String C_BUNDLE_DIFF = "bundleDifference"; - public static final String C_CONTRACT = "contract"; - - public static final String C_VERSION_MAJOR = "major"; - public static final String C_VERSION_MINOR = "minor"; - public static final String C_VERSION_MICRO = "micro"; - public static final String C_VERSION_QUALIFIER = "qualifier"; - - public static final String C_DETAILS = "details"; - public static final String C_DETAILS_CHILDREN = "children"; - public static final String C_DETAILS_LEVEL = "level"; - public static final String C_DETAILS_NAME = "name"; - public static final String C_DETAILS_NAMESPACE = "namespace"; - public static final String C_DETAILS_ROLE = "role"; - public static final String C_DETAILS_VALUE = "value"; - public static final String C_DETAILS_SYNTAX = "syntax"; - - - /** - * Map given string to ObjectId or generate a new one if empty/null. - * @param id - * @return ObjectId instance - */ - private static ObjectId mapId(String id) { - ObjectId oid; - if(id == null || id.isEmpty()) { - oid = ObjectId.get(); - } else { - oid = ObjectId.massageToObjectId(id); - } - return oid; - } - - /** - * Maps Compatibility do DBObject - */ - public static DBObject mapToDbObject(Compatibility compatibility) { - DBObject obj = new BasicDBObject(); - - obj.put("_id", mapId(compatibility.getId())); - - obj.put(C_RESOURCE_NAME, compatibility.getResourceName()); - obj.put(C_RESOURCE_VERSION, mapVersion(compatibility.getResourceVersion())); - - obj.put(C_BASE_NAME, compatibility.getBaseResourceName()); - obj.put(C_BASE_VERSION, mapVersion(compatibility.getBaseResourceVersion())); - - obj.put(C_BUNDLE_DIFF, compatibility.getDiffValue().name()); - - obj.put(C_CONTRACT, compatibility.getContract().name()); - - List details = new ArrayList<>(compatibility.getDiffDetails().size()); - for (Diff detail : compatibility.getDiffDetails()) { - details.add(mapDifferenceDetails(detail)); - } - obj.put(C_DETAILS, details); - - return obj; - } - - /** - * Maps DBObject to compability - * @param source source DBObject - * @param factory factory class for creating new Compatibility instance - * @return - */ - public static Compatibility mapToCompatibility(DBObject source, CompatibilityFactory factory) { - if(source == null) { - return null; - } - - String id = source.get("_id").toString(); - String baseName = (String) source.get(C_BASE_NAME); - Version baseVersion = mapToVersion((DBObject) source.get(C_BASE_VERSION)); - String resourceName = (String) source.get(C_RESOURCE_NAME); - Version resrouceVersion = mapToVersion((DBObject) source.get(C_RESOURCE_VERSION)); - Difference diffValue = getEnumFromValue(Difference.class, (String) source.get(C_BUNDLE_DIFF)); - Contract contract = getEnumFromValue(Contract.class, (String) source.get(C_CONTRACT)); - - List diffDetails = new ArrayList<>(); - List children = (List) source.get(C_DETAILS); - if (children != null) { - for (DBObject o : children) { - diffDetails.add(mapToDiff(o, factory)); - } - } - - return factory.createCompatibility(id, resourceName, resrouceVersion, baseName, baseVersion, diffValue, diffDetails, contract); - } - - /** - * Maps version object to DBObject - * @param version - * @return - */ - public static DBObject mapVersion(Version version) { - DBObject obj = new BasicDBObject(C_VERSION_MAJOR, version.getMajor()); - obj.put(C_VERSION_MINOR, version.getMinor()); - obj.put(C_VERSION_MICRO, version.getMicro()); - obj.put(C_VERSION_QUALIFIER, version.getQualifier()); - - return obj; - } - - /** - * Maps DBObject to Version instance. - * @param source - * @return - */ - public static Version mapToVersion(DBObject source) { - int major = (int) source.get(C_VERSION_MAJOR); - int minor = (int) source.get(C_VERSION_MINOR); - int micro = (int) source.get(C_VERSION_MICRO); - String qualifier = (String) source.get(C_VERSION_QUALIFIER); - - return new Version(major, minor, micro, qualifier); - } - - /** - * Map Diff into JSON format. - * @param details to be mapped - * @return DbObject instance - */ - public static DBObject mapDifferenceDetails(Diff details) { - DBObject obj = new BasicDBObject(C_DETAILS_NAME, details.getName()); - obj.put(C_DETAILS_LEVEL, details.getLevel().name()); - obj.put(C_DETAILS_VALUE, details.getValue().name()); - obj.put(C_DETAILS_NAMESPACE, details.getNamespace()); - obj.put(C_DETAILS_SYNTAX, details.getSyntax()); - - if (details.getRole() != null) { - obj.put(C_DETAILS_ROLE, details.getRole().name()); - } - - List children = new ArrayList<>(details.getChildren().size()); - for (Diff child : details.getChildren()) { - children.add(mapDifferenceDetails(child)); - } - obj.put(C_DETAILS_CHILDREN, children); - - return obj; - } - - /** - * Maps from JSON to Diff - * - * @param obj JSON formatted data - * @param compatibilityFactory factory - * @return diff instance with the data - */ - public static Diff mapToDiff(DBObject obj, CompatibilityFactory compatibilityFactory) { - Diff d = compatibilityFactory.createEmptyDiff(); - - //string values - String tmp = (String) obj.get(C_DETAILS_NAME); - d.setName(tmp); - tmp = (String) obj.get(C_DETAILS_NAMESPACE); - d.setNamespace(tmp); - tmp = (String) obj.get(C_DETAILS_SYNTAX); - d.setSyntax(tmp); - - //enums - Difference value = getEnumFromValue(Difference.class, (String) obj.get(C_DETAILS_VALUE)); - DifferenceRole role = getEnumFromValue(DifferenceRole.class, (String) obj.get(C_DETAILS_ROLE)); - DifferenceLevel level = getEnumFromValue(DifferenceLevel.class, (String) obj.get(C_DETAILS_LEVEL)); - - d.setValue(value); - d.setRole(role); - d.setLevel(level); - - //children - List children = (List) obj.get(C_DETAILS_CHILDREN); - if (children != null) { - for (DBObject o : children) { - d.addChild(mapToDiff(o, compatibilityFactory)); - } - } - - return d; - } - - /** - * Safe method to get enum value from strings stored in db. - *

- * Returns null if the value is null or doesnt match any enum value. - * - * @param clazz enum class - * @param value value to parse - * @param enum type - * @return enum value - */ - public static > E getEnumFromValue(Class clazz, String value) { - try { - return E.valueOf(clazz, value); - } catch (Exception ex) { - return null; - } - } - - /** - * Parse list of Enums to a list of Strings using their name() value. - * @param e list of enumerations - * @return list of strings - */ - public static List parseEnum(List e) { - if(e == null) { - return new ArrayList<>(); - } - List names = new ArrayList<>(e.size()); - for(Enum d : e) { - names.add(d.name()); - } - return names; - } -} +package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; + +import java.util.ArrayList; +import java.util.List; + +import org.bson.types.ObjectId; + +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; +import cz.zcu.kiv.crce.compatibility.Contract; +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.DifferenceRole; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Serialization/Deserialization support class between Compatibility and MongoDB. + * + * Date: 17.11.13 + * + * @author Jakub Danek + */ +public class MongoCompatibilityMapper { + + /* + KEY SPACE + */ + public static final String C_RESOURCE_NAME = "resourceName"; + public static final String C_RESOURCE_VERSION = "resourceVersion"; + public static final String C_BASE_NAME = "baseName"; + public static final String C_BASE_VERSION = "baseVersion"; + public static final String C_BUNDLE_DIFF = "bundleDifference"; + public static final String C_CONTRACT = "contract"; + + public static final String C_VERSION_MAJOR = "major"; + public static final String C_VERSION_MINOR = "minor"; + public static final String C_VERSION_MICRO = "micro"; + public static final String C_VERSION_QUALIFIER = "qualifier"; + + public static final String C_DETAILS = "details"; + public static final String C_DETAILS_CHILDREN = "children"; + public static final String C_DETAILS_LEVEL = "level"; + public static final String C_DETAILS_NAME = "name"; + public static final String C_DETAILS_NAMESPACE = "namespace"; + public static final String C_DETAILS_ROLE = "role"; + public static final String C_DETAILS_VALUE = "value"; + public static final String C_DETAILS_SYNTAX = "syntax"; + + + /** + * Map given string to ObjectId or generate a new one if empty/null. + * @param id + * @return ObjectId instance + */ + private static ObjectId mapId(String id) { + ObjectId oid; + if(id == null || id.isEmpty()) { + oid = ObjectId.get(); + } else { + oid = ObjectId.massageToObjectId(id); + } + return oid; + } + + /** + * Maps Compatibility do DBObject + */ + public static DBObject mapToDbObject(Compatibility compatibility) { + DBObject obj = new BasicDBObject(); + + obj.put("_id", mapId(compatibility.getId())); + + obj.put(C_RESOURCE_NAME, compatibility.getResourceName()); + obj.put(C_RESOURCE_VERSION, mapVersion(compatibility.getResourceVersion())); + + obj.put(C_BASE_NAME, compatibility.getBaseResourceName()); + obj.put(C_BASE_VERSION, mapVersion(compatibility.getBaseResourceVersion())); + + obj.put(C_BUNDLE_DIFF, compatibility.getDiffValue().name()); + + obj.put(C_CONTRACT, compatibility.getContract().name()); + + List details = new ArrayList<>(compatibility.getDiffDetails().size()); + for (Diff detail : compatibility.getDiffDetails()) { + details.add(mapDifferenceDetails(detail)); + } + obj.put(C_DETAILS, details); + + return obj; + } + + /** + * Maps DBObject to compability + * @param source source DBObject + * @param factory factory class for creating new Compatibility instance + * @return + */ + public static Compatibility mapToCompatibility(DBObject source, CompatibilityFactory factory) { + if(source == null) { + return null; + } + + String id = source.get("_id").toString(); + String baseName = (String) source.get(C_BASE_NAME); + Version baseVersion = mapToVersion((DBObject) source.get(C_BASE_VERSION)); + String resourceName = (String) source.get(C_RESOURCE_NAME); + Version resrouceVersion = mapToVersion((DBObject) source.get(C_RESOURCE_VERSION)); + Difference diffValue = getEnumFromValue(Difference.class, (String) source.get(C_BUNDLE_DIFF)); + Contract contract = getEnumFromValue(Contract.class, (String) source.get(C_CONTRACT)); + + List diffDetails = new ArrayList<>(); + List children = (List) source.get(C_DETAILS); + if (children != null) { + for (DBObject o : children) { + diffDetails.add(mapToDiff(o, factory)); + } + } + + return factory.createCompatibility(id, resourceName, resrouceVersion, baseName, baseVersion, diffValue, diffDetails, contract); + } + + /** + * Maps version object to DBObject + * @param version + * @return + */ + public static DBObject mapVersion(Version version) { + DBObject obj = new BasicDBObject(C_VERSION_MAJOR, version.getMajor()); + obj.put(C_VERSION_MINOR, version.getMinor()); + obj.put(C_VERSION_MICRO, version.getMicro()); + obj.put(C_VERSION_QUALIFIER, version.getQualifier()); + + return obj; + } + + /** + * Maps DBObject to Version instance. + * @param source + * @return + */ + public static Version mapToVersion(DBObject source) { + int major = (int) source.get(C_VERSION_MAJOR); + int minor = (int) source.get(C_VERSION_MINOR); + int micro = (int) source.get(C_VERSION_MICRO); + String qualifier = (String) source.get(C_VERSION_QUALIFIER); + + return new Version(major, minor, micro, qualifier); + } + + /** + * Map Diff into JSON format. + * @param details to be mapped + * @return DbObject instance + */ + public static DBObject mapDifferenceDetails(Diff details) { + DBObject obj = new BasicDBObject(C_DETAILS_NAME, details.getName()); + obj.put(C_DETAILS_LEVEL, details.getLevel().name()); + obj.put(C_DETAILS_VALUE, details.getValue().name()); + obj.put(C_DETAILS_NAMESPACE, details.getNamespace()); + obj.put(C_DETAILS_SYNTAX, details.getSyntax()); + + if (details.getRole() != null) { + obj.put(C_DETAILS_ROLE, details.getRole().name()); + } + + List children = new ArrayList<>(details.getChildren().size()); + for (Diff child : details.getChildren()) { + children.add(mapDifferenceDetails(child)); + } + obj.put(C_DETAILS_CHILDREN, children); + + return obj; + } + + /** + * Maps from JSON to Diff + * + * @param obj JSON formatted data + * @param compatibilityFactory factory + * @return diff instance with the data + */ + public static Diff mapToDiff(DBObject obj, CompatibilityFactory compatibilityFactory) { + Diff d = compatibilityFactory.createEmptyDiff(); + + //string values + String tmp = (String) obj.get(C_DETAILS_NAME); + d.setName(tmp); + tmp = (String) obj.get(C_DETAILS_NAMESPACE); + d.setNamespace(tmp); + tmp = (String) obj.get(C_DETAILS_SYNTAX); + d.setSyntax(tmp); + + //enums + Difference value = getEnumFromValue(Difference.class, (String) obj.get(C_DETAILS_VALUE)); + DifferenceRole role = getEnumFromValue(DifferenceRole.class, (String) obj.get(C_DETAILS_ROLE)); + DifferenceLevel level = getEnumFromValue(DifferenceLevel.class, (String) obj.get(C_DETAILS_LEVEL)); + + d.setValue(value); + d.setRole(role); + d.setLevel(level); + + //children + List children = (List) obj.get(C_DETAILS_CHILDREN); + if (children != null) { + for (DBObject o : children) { + d.addChild(mapToDiff(o, compatibilityFactory)); + } + } + + return d; + } + + /** + * Safe method to get enum value from strings stored in db. + *

+ * Returns null if the value is null or doesnt match any enum value. + * + * @param clazz enum class + * @param value value to parse + * @param enum type + * @return enum value + */ + public static > E getEnumFromValue(Class clazz, String value) { + try { + return E.valueOf(clazz, value); + } catch (Exception ex) { + return null; + } + } + + /** + * Parse list of Enums to a list of Strings using their name() value. + * @param e list of enumerations + * @return list of strings + */ + public static List parseEnum(List e) { + if(e == null) { + return new ArrayList<>(); + } + List names = new ArrayList<>(e.size()); + for(Enum d : e) { + names.add(d.name()); + } + return names; + } +} diff --git a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/CompatibilityTestImpl.java b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/CompatibilityTestImpl.java index 7a9b31d2..423326ff 100644 --- a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/CompatibilityTestImpl.java +++ b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/CompatibilityTestImpl.java @@ -1,161 +1,161 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; - -import java.util.List; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.Contract; -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Implementation of Compatibility interface for testing purposes. - *

- * Date: 15.3.14 - * - * @author Jakub Danek - */ -public class CompatibilityTestImpl implements Compatibility { - private String id; - private String resourceName; - private Version resourceVersion; - private String baseResourceName; - private Version baseResourceVersion; - private Difference diffValue; - private List diffDetails; - private Contract contract; - - /** - * Empty constructor, creates uninitialized instance. - */ - CompatibilityTestImpl() { - - } - - /** - * Fully initialized instance. See {@link Compatibility} for parameter documentation. - * - * @see Compatibility - */ - CompatibilityTestImpl(String id, String resourceName, Version resourceVersion, - String baseResourceName, Version baseResourceVersion, - Difference diffValue, List diffDetails, Contract contract) { - this.id = id; - this.resourceName = resourceName; - this.resourceVersion = resourceVersion; - this.baseResourceName = baseResourceName; - this.baseResourceVersion = baseResourceVersion; - this.diffValue = diffValue; - this.diffDetails = diffDetails; - this.contract = contract; - } - - @Override - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - @Override - public Version getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(Version resourceVersion) { - this.resourceVersion = resourceVersion; - } - - @Override - public String getBaseResourceName() { - if (baseResourceName == null || baseResourceName.isEmpty()) { - return getResourceName(); - } - return baseResourceName; - } - - public void setBaseResourceName(String baseResourceName) { - this.baseResourceName = baseResourceName; - } - - @Override - public Version getBaseResourceVersion() { - return baseResourceVersion; - } - - public void setBaseResourceVersion(Version baseResourceVersion) { - this.baseResourceVersion = baseResourceVersion; - } - - @Override - public Difference getDiffValue() { - return diffValue; - } - - public void setDiffValue(Difference diffValue) { - this.diffValue = diffValue; - } - - @Override - public List getDiffDetails() { - return diffDetails; - } - - public void setDiffDetails(List diffDetails) { - this.diffDetails = diffDetails; - } - - @Override - public Contract getContract() { - return contract; - } - - public void setContract(Contract contract) { - this.contract = contract; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CompatibilityTestImpl that = (CompatibilityTestImpl) o; - - if (baseResourceName != null ? !baseResourceName.equals(that.baseResourceName) : that.baseResourceName != null) - return false; - if (baseResourceVersion != null ? !baseResourceVersion.equals(that.baseResourceVersion) : that.baseResourceVersion != null) - return false; - if (diffDetails != null ? !diffDetails.equals(that.diffDetails) : that.diffDetails != null) return false; - if (diffValue != that.diffValue) return false; - if (contract != that.contract) return false; - if (resourceName != null ? !resourceName.equals(that.resourceName) : that.resourceName != null) return false; - if (resourceVersion != null ? !resourceVersion.equals(that.resourceVersion) : that.resourceVersion != null) - return false; - - return true; - } - - @Override - public int hashCode() { - int result = resourceName != null ? resourceName.hashCode() : 0; - result = 31 * result + (resourceVersion != null ? resourceVersion.hashCode() : 0); - result = 31 * result + (baseResourceName != null ? baseResourceName.hashCode() : 0); - result = 31 * result + (baseResourceVersion != null ? baseResourceVersion.hashCode() : 0); - result = 31 * result + (diffValue != null ? diffValue.hashCode() : 0); - result = 31 * result + (diffDetails != null ? diffDetails.hashCode() : 0); - result = 31 * result + (contract != null ? contract.hashCode() : 0); - return result; - } - -} +package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; + +import java.util.List; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.Contract; +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Implementation of Compatibility interface for testing purposes. + *

+ * Date: 15.3.14 + * + * @author Jakub Danek + */ +public class CompatibilityTestImpl implements Compatibility { + private String id; + private String resourceName; + private Version resourceVersion; + private String baseResourceName; + private Version baseResourceVersion; + private Difference diffValue; + private List diffDetails; + private Contract contract; + + /** + * Empty constructor, creates uninitialized instance. + */ + CompatibilityTestImpl() { + + } + + /** + * Fully initialized instance. See {@link Compatibility} for parameter documentation. + * + * @see Compatibility + */ + CompatibilityTestImpl(String id, String resourceName, Version resourceVersion, + String baseResourceName, Version baseResourceVersion, + Difference diffValue, List diffDetails, Contract contract) { + this.id = id; + this.resourceName = resourceName; + this.resourceVersion = resourceVersion; + this.baseResourceName = baseResourceName; + this.baseResourceVersion = baseResourceVersion; + this.diffValue = diffValue; + this.diffDetails = diffDetails; + this.contract = contract; + } + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @Override + public Version getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(Version resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @Override + public String getBaseResourceName() { + if (baseResourceName == null || baseResourceName.isEmpty()) { + return getResourceName(); + } + return baseResourceName; + } + + public void setBaseResourceName(String baseResourceName) { + this.baseResourceName = baseResourceName; + } + + @Override + public Version getBaseResourceVersion() { + return baseResourceVersion; + } + + public void setBaseResourceVersion(Version baseResourceVersion) { + this.baseResourceVersion = baseResourceVersion; + } + + @Override + public Difference getDiffValue() { + return diffValue; + } + + public void setDiffValue(Difference diffValue) { + this.diffValue = diffValue; + } + + @Override + public List getDiffDetails() { + return diffDetails; + } + + public void setDiffDetails(List diffDetails) { + this.diffDetails = diffDetails; + } + + @Override + public Contract getContract() { + return contract; + } + + public void setContract(Contract contract) { + this.contract = contract; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + CompatibilityTestImpl that = (CompatibilityTestImpl) o; + + if (baseResourceName != null ? !baseResourceName.equals(that.baseResourceName) : that.baseResourceName != null) + return false; + if (baseResourceVersion != null ? !baseResourceVersion.equals(that.baseResourceVersion) : that.baseResourceVersion != null) + return false; + if (diffDetails != null ? !diffDetails.equals(that.diffDetails) : that.diffDetails != null) return false; + if (diffValue != that.diffValue) return false; + if (contract != that.contract) return false; + if (resourceName != null ? !resourceName.equals(that.resourceName) : that.resourceName != null) return false; + if (resourceVersion != null ? !resourceVersion.equals(that.resourceVersion) : that.resourceVersion != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = resourceName != null ? resourceName.hashCode() : 0; + result = 31 * result + (resourceVersion != null ? resourceVersion.hashCode() : 0); + result = 31 * result + (baseResourceName != null ? baseResourceName.hashCode() : 0); + result = 31 * result + (baseResourceVersion != null ? baseResourceVersion.hashCode() : 0); + result = 31 * result + (diffValue != null ? diffValue.hashCode() : 0); + result = 31 * result + (diffDetails != null ? diffDetails.hashCode() : 0); + result = 31 * result + (contract != null ? contract.hashCode() : 0); + return result; + } + +} diff --git a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/DiffTestImpl.java b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/DiffTestImpl.java index 6b4054a3..fe7201a4 100644 --- a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/DiffTestImpl.java +++ b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/DiffTestImpl.java @@ -1,137 +1,137 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; - -import java.util.ArrayList; -import java.util.List; - -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.DifferenceRole; - -/** - * Implementation of Diff interface for testing purposes. - *

- * Date: 15.3.14 - * - * @author Jakub Danek - */ -public class DiffTestImpl implements Diff { - private String name; - private Difference value; - private DifferenceLevel level; - private DifferenceRole role; - private List children; - private String namespace; - private String syntax; - - public DiffTestImpl() { - this.children = new ArrayList<>(); - this.name = ""; - this.value = Difference.UNK; - this.level = DifferenceLevel.UNKNOWN; - } - - @Override - public String getNamespace() { - return namespace; - } - - @Override - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - @Override - public List getChildren() { - return children; - } - - @Override - public void addChild(Diff child) { - this.children.add(child); - } - - @Override - public void addChildren(List children) { - this.children.addAll(children); - } - - @Override - public DifferenceRole getRole() { - return role; - } - - @Override - public void setRole(DifferenceRole role) { - this.role = role; - } - - @Override - public DifferenceLevel getLevel() { - return level; - } - - @Override - public void setLevel(DifferenceLevel level) { - this.level = level; - } - - @Override - public Difference getValue() { - return value; - } - - @Override - public void setValue(Difference value) { - this.value = value; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSyntax() { - return syntax; - } - - public void setSyntax(String syntax) { - this.syntax = syntax; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - DiffTestImpl diff = (DiffTestImpl) o; - - if (children != null ? !children.equals(diff.children) : diff.children != null) return false; - if (level != diff.level) return false; - if (name != null ? !name.equals(diff.name) : diff.name != null) return false; - if (namespace != null ? !namespace.equals(diff.namespace) : diff.namespace != null) return false; - if (syntax != null ? !syntax.equals(diff.syntax) : diff.syntax != null) return false; - if (role != diff.role) return false; - if (value != diff.value) return false; - - return true; - } - - @Override - public int hashCode() { - int result = name != null ? name.hashCode() : 0; - result = 31 * result + (value != null ? value.hashCode() : 0); - result = 31 * result + (level != null ? level.hashCode() : 0); - result = 31 * result + (role != null ? role.hashCode() : 0); - result = 31 * result + (children != null ? children.hashCode() : 0); - result = 31 * result + (syntax != null ? syntax.hashCode() : 0); - result = 31 * result + (namespace != null ? namespace.hashCode() : 0); - return result; - } -} - +package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; + +import java.util.ArrayList; +import java.util.List; + +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.DifferenceRole; + +/** + * Implementation of Diff interface for testing purposes. + *

+ * Date: 15.3.14 + * + * @author Jakub Danek + */ +public class DiffTestImpl implements Diff { + private String name; + private Difference value; + private DifferenceLevel level; + private DifferenceRole role; + private List children; + private String namespace; + private String syntax; + + public DiffTestImpl() { + this.children = new ArrayList<>(); + this.name = ""; + this.value = Difference.UNK; + this.level = DifferenceLevel.UNKNOWN; + } + + @Override + public String getNamespace() { + return namespace; + } + + @Override + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + @Override + public List getChildren() { + return children; + } + + @Override + public void addChild(Diff child) { + this.children.add(child); + } + + @Override + public void addChildren(List children) { + this.children.addAll(children); + } + + @Override + public DifferenceRole getRole() { + return role; + } + + @Override + public void setRole(DifferenceRole role) { + this.role = role; + } + + @Override + public DifferenceLevel getLevel() { + return level; + } + + @Override + public void setLevel(DifferenceLevel level) { + this.level = level; + } + + @Override + public Difference getValue() { + return value; + } + + @Override + public void setValue(Difference value) { + this.value = value; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getSyntax() { + return syntax; + } + + public void setSyntax(String syntax) { + this.syntax = syntax; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + DiffTestImpl diff = (DiffTestImpl) o; + + if (children != null ? !children.equals(diff.children) : diff.children != null) return false; + if (level != diff.level) return false; + if (name != null ? !name.equals(diff.name) : diff.name != null) return false; + if (namespace != null ? !namespace.equals(diff.namespace) : diff.namespace != null) return false; + if (syntax != null ? !syntax.equals(diff.syntax) : diff.syntax != null) return false; + if (role != diff.role) return false; + if (value != diff.value) return false; + + return true; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (value != null ? value.hashCode() : 0); + result = 31 * result + (level != null ? level.hashCode() : 0); + result = 31 * result + (role != null ? role.hashCode() : 0); + result = 31 * result + (children != null ? children.hashCode() : 0); + result = 31 * result + (syntax != null ? syntax.hashCode() : 0); + result = 31 * result + (namespace != null ? namespace.hashCode() : 0); + return result; + } +} + diff --git a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapperTest.java b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapperTest.java index 4f4a184b..196d080c 100644 --- a/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapperTest.java +++ b/modules/crce-compatibility-dao-mongodb/src/test/java/cz/zcu/kiv/crce/compatibility/dao/internal/mapping/MongoCompatibilityMapperTest.java @@ -1,92 +1,92 @@ -package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.mongodb.DBObject; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; -import cz.zcu.kiv.crce.compatibility.Contract; -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.DifferenceRole; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Date: 15.3.14 - * - * @author Jakub Danek - */ -public class MongoCompatibilityMapperTest { - - /** - * Test implementation of CompatibilityFactory - */ - static class CompatibilityFactoryTestImpl implements CompatibilityFactory { - @Override - public Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, String baseName, Version baseVersion, Difference diffValue, List diffValues, Contract contract) { - return new CompatibilityTestImpl(id, resourceName, resourceVersion, baseName, baseVersion, diffValue, diffValues, contract); - } - - @Override - public Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, Version baseVersion, Difference diffValue, List diffValues, Contract contract) { - return new CompatibilityTestImpl(id, resourceName, resourceVersion, resourceName, baseVersion, diffValue, diffValues, contract); - } - - @Override - public Diff createEmptyDiff() { - return new DiffTestImpl(); - } - } - - private static CompatibilityFactory factory; - - @BeforeClass - public static void beforeClass() throws Exception { - factory = new CompatibilityFactoryTestImpl(); - } - - @Test - public void consistencyTest() throws Exception { - Diff root = factory.createEmptyDiff(); - root.setLevel(DifferenceLevel.PACKAGE); - ; - root.setNamespace("osgi.wiring.package"); - root.setName("cz.zcu.kiv"); - root.setRole(DifferenceRole.CAPABILITY); - root.setValue(Difference.MUT); - - Diff child = factory.createEmptyDiff(); - root.setLevel(DifferenceLevel.TYPE); - ; - root.setName("cz.zcu.kiv.Clazz1"); - root.setValue(Difference.DEL); - root.addChild(child); - - child = factory.createEmptyDiff(); - root.setLevel(DifferenceLevel.TYPE); - ; - root.setName("cz.zcu.kiv.Clazz2"); - root.setValue(Difference.INS); - root.addChild(child); - - List diffs = new ArrayList<>(); - diffs.add(root); - - Compatibility toMap = factory.createCompatibility(null, "cz.kiv.zcu.TestName", - new Version(1, 25, 33, "ahoj"), new Version(2, 0, 55), Difference.MUT, diffs, Contract.SYNTAX); - - DBObject obj = MongoCompatibilityMapper.mapToDbObject(toMap); - - Compatibility res = MongoCompatibilityMapper.mapToCompatibility(obj, factory); - - assertEquals(toMap, res); - } -} +package cz.zcu.kiv.crce.compatibility.dao.internal.mapping; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.mongodb.DBObject; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.CompatibilityFactory; +import cz.zcu.kiv.crce.compatibility.Contract; +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.DifferenceRole; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Date: 15.3.14 + * + * @author Jakub Danek + */ +public class MongoCompatibilityMapperTest { + + /** + * Test implementation of CompatibilityFactory + */ + static class CompatibilityFactoryTestImpl implements CompatibilityFactory { + @Override + public Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, String baseName, Version baseVersion, Difference diffValue, List diffValues, Contract contract) { + return new CompatibilityTestImpl(id, resourceName, resourceVersion, baseName, baseVersion, diffValue, diffValues, contract); + } + + @Override + public Compatibility createCompatibility(String id, String resourceName, Version resourceVersion, Version baseVersion, Difference diffValue, List diffValues, Contract contract) { + return new CompatibilityTestImpl(id, resourceName, resourceVersion, resourceName, baseVersion, diffValue, diffValues, contract); + } + + @Override + public Diff createEmptyDiff() { + return new DiffTestImpl(); + } + } + + private static CompatibilityFactory factory; + + @BeforeClass + public static void beforeClass() throws Exception { + factory = new CompatibilityFactoryTestImpl(); + } + + @Test + public void consistencyTest() throws Exception { + Diff root = factory.createEmptyDiff(); + root.setLevel(DifferenceLevel.PACKAGE); + ; + root.setNamespace("osgi.wiring.package"); + root.setName("cz.zcu.kiv"); + root.setRole(DifferenceRole.CAPABILITY); + root.setValue(Difference.MUT); + + Diff child = factory.createEmptyDiff(); + root.setLevel(DifferenceLevel.TYPE); + ; + root.setName("cz.zcu.kiv.Clazz1"); + root.setValue(Difference.DEL); + root.addChild(child); + + child = factory.createEmptyDiff(); + root.setLevel(DifferenceLevel.TYPE); + ; + root.setName("cz.zcu.kiv.Clazz2"); + root.setValue(Difference.INS); + root.addChild(child); + + List diffs = new ArrayList<>(); + diffs.add(root); + + Compatibility toMap = factory.createCompatibility(null, "cz.kiv.zcu.TestName", + new Version(1, 25, 33, "ahoj"), new Version(2, 0, 55), Difference.MUT, diffs, Contract.SYNTAX); + + DBObject obj = MongoCompatibilityMapper.mapToDbObject(toMap); + + Compatibility res = MongoCompatibilityMapper.mapToCompatibility(obj, factory); + + assertEquals(toMap, res); + } +} diff --git a/modules/crce-concurrency/osgi.bnd b/modules/crce-concurrency/osgi.bnd index bbf9feb0..287b03fe 100644 --- a/modules/crce-concurrency/osgi.bnd +++ b/modules/crce-concurrency/osgi.bnd @@ -1,7 +1,7 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + Service-Component: OSGi-INF/service.xml \ No newline at end of file diff --git a/modules/crce-concurrency/pom.xml b/modules/crce-concurrency/pom.xml index 2848a8f8..c18008a0 100644 --- a/modules/crce-concurrency/pom.xml +++ b/modules/crce-concurrency/pom.xml @@ -1,33 +1,33 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-concurrency - bundle - - CRCE - Concurrency API - - - ${namespace}.concurrency - ${namespace}.concurrency - - - - - - - junit - junit - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-concurrency + bundle + + CRCE - Concurrency API + + + ${namespace}.concurrency + ${namespace}.concurrency + + + + + + + junit + junit + + + + \ No newline at end of file diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/Activator.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/Activator.java index e7545487..71b7995a 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/Activator.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/Activator.java @@ -1,46 +1,46 @@ -package cz.zcu.kiv.crce.concurrency.internal; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; - -/** - * Date: 11.11.13 - * - * @author Jakub Danek - */ -public class Activator extends DependencyActivatorBase { - - /** - * Initialize the dependency manager. Here you can add all components and their dependencies. - * If something goes wrong and you do not want your bundle to be started, you can throw an - * exception. This exception will be passed on to the start() method of the - * bundle activator, causing the bundle not to start. - * - * @param context the bundle context - * @param manager the dependency manager - * @throws Exception if the initialization fails - */ - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - - } - - /** - * Destroy the dependency manager. Here you can remove all components and their dependencies. - * Actually, the base class will clean up your dependencies anyway, so most of the time you - * don't need to do anything here. - *

- * If something goes wrong and you do not want your bundle to be stopped, you can throw an - * exception. This exception will be passed on to the stop() method of the - * bundle activator, causing the bundle not to stop. - * - * @param context the bundle context - * @param manager the dependency manager - * @throws Exception if the destruction fails - */ - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - TaskRunner.get().stop(); - } -} +package cz.zcu.kiv.crce.concurrency.internal; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +/** + * Date: 11.11.13 + * + * @author Jakub Danek + */ +public class Activator extends DependencyActivatorBase { + + /** + * Initialize the dependency manager. Here you can add all components and their dependencies. + * If something goes wrong and you do not want your bundle to be started, you can throw an + * exception. This exception will be passed on to the start() method of the + * bundle activator, causing the bundle not to start. + * + * @param context the bundle context + * @param manager the dependency manager + * @throws Exception if the initialization fails + */ + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + + } + + /** + * Destroy the dependency manager. Here you can remove all components and their dependencies. + * Actually, the base class will clean up your dependencies anyway, so most of the time you + * don't need to do anything here. + *

+ * If something goes wrong and you do not want your bundle to be stopped, you can throw an + * exception. This exception will be passed on to the stop() method of the + * bundle activator, causing the bundle not to stop. + * + * @param context the bundle context + * @param manager the dependency manager + * @throws Exception if the destruction fails + */ + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + TaskRunner.get().stop(); + } +} diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunner.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunner.java index feef4ae4..e92e42e2 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunner.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunner.java @@ -1,122 +1,122 @@ -package cz.zcu.kiv.crce.concurrency.internal; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.concurrency.model.Task; - - -/** - * TaskRunner class using FixedThreadPool to control crce's thread resources. - *

- *

- * Date: 11.11.13 - * - * @author Jakub Danek - */ -public class TaskRunner { - /* - STATIC CODE - */ - private static final Logger logger = LoggerFactory.getLogger(TaskRunner.class); - - private volatile static TaskRunner instance = new TaskRunner(); - - /** - * TaskRunner.init(threadCount) must be run before the instance can be recovered. If not, TaskRunner initializes - * to default thread count. - * - * @return singleton instance of TaskRunner - */ - public synchronized static TaskRunner get() { - return instance; - } - - /** - * This static method can be used to reinitialize TaskRunner queue. It will first call stop() on the - * current instance and then replace it with new instance. - * - * @param maxThreads - */ - public static synchronized void init(int maxThreads) { - instance.stop(); - instance = new TaskRunner(maxThreads); - } - - /* - MEMBER CODE - */ - - private ExecutorService executor; - private final int maxThreads; - - /** - * Initializes TaskRunner to default configuration. - */ - private TaskRunner() { - //TODO change this to configuration - this(4); - } - - /** - * @param maxThreads maximum number of threads the pool will be able to spawn - */ - private TaskRunner(int maxThreads) { - executor = Executors.newFixedThreadPool(maxThreads); - this.maxThreads = maxThreads; - } - - /** - * @return maximum number of allowed threads for this TaskRunner - */ - public int getMaxThreads() { - return maxThreads; - } - - /** - * Attempts to stop the TaskRunner. - *

- * First waits for running and scheduled tasks to finish, while not accepting any other tasks. In case some of the - * running tasks wont finish in time, attempts to interrupt them. - */ - public void stop() { - try { - logger.info("Shutting down, waiting for scheduled tasks to finish..."); - this.executor.shutdown(); - boolean shutdown = this.executor.awaitTermination(10, TimeUnit.SECONDS); - - if (!shutdown) { - logger.warn("All tasks did not finish in time. Interrupting..."); - int number = this.executor.shutdownNow().size(); - shutdown = this.executor.awaitTermination(2, TimeUnit.SECONDS); - if (number > 0) { - logger.warn("{} tasks were scheduled but never run.", number); - } - if (!shutdown) { - logger.warn("Failed to interrupt all tasks before quitting."); - } - } - - } catch (InterruptedException e) { - logger.warn("TaskRunner thread interrupted before it was able to shutdown all running tasks."); - } - - logger.info("TaskRunner stopped."); - } - - /** - * Schedules new task to be run - * - * @param task task to be scheduled - * @return Future reference which can be used to gain results after the Task has finished - */ - public synchronized Future scheduleTask(Task task) { - logger.info("Task {} called by {} has been scheduled.", task.getId(), task.getCaller()); - return this.executor.submit(task); - } -} +package cz.zcu.kiv.crce.concurrency.internal; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.concurrency.model.Task; + + +/** + * TaskRunner class using FixedThreadPool to control crce's thread resources. + *

+ *

+ * Date: 11.11.13 + * + * @author Jakub Danek + */ +public class TaskRunner { + /* + STATIC CODE + */ + private static final Logger logger = LoggerFactory.getLogger(TaskRunner.class); + + private volatile static TaskRunner instance = new TaskRunner(); + + /** + * TaskRunner.init(threadCount) must be run before the instance can be recovered. If not, TaskRunner initializes + * to default thread count. + * + * @return singleton instance of TaskRunner + */ + public synchronized static TaskRunner get() { + return instance; + } + + /** + * This static method can be used to reinitialize TaskRunner queue. It will first call stop() on the + * current instance and then replace it with new instance. + * + * @param maxThreads + */ + public static synchronized void init(int maxThreads) { + instance.stop(); + instance = new TaskRunner(maxThreads); + } + + /* + MEMBER CODE + */ + + private ExecutorService executor; + private final int maxThreads; + + /** + * Initializes TaskRunner to default configuration. + */ + private TaskRunner() { + //TODO change this to configuration + this(4); + } + + /** + * @param maxThreads maximum number of threads the pool will be able to spawn + */ + private TaskRunner(int maxThreads) { + executor = Executors.newFixedThreadPool(maxThreads); + this.maxThreads = maxThreads; + } + + /** + * @return maximum number of allowed threads for this TaskRunner + */ + public int getMaxThreads() { + return maxThreads; + } + + /** + * Attempts to stop the TaskRunner. + *

+ * First waits for running and scheduled tasks to finish, while not accepting any other tasks. In case some of the + * running tasks wont finish in time, attempts to interrupt them. + */ + public void stop() { + try { + logger.info("Shutting down, waiting for scheduled tasks to finish..."); + this.executor.shutdown(); + boolean shutdown = this.executor.awaitTermination(10, TimeUnit.SECONDS); + + if (!shutdown) { + logger.warn("All tasks did not finish in time. Interrupting..."); + int number = this.executor.shutdownNow().size(); + shutdown = this.executor.awaitTermination(2, TimeUnit.SECONDS); + if (number > 0) { + logger.warn("{} tasks were scheduled but never run.", number); + } + if (!shutdown) { + logger.warn("Failed to interrupt all tasks before quitting."); + } + } + + } catch (InterruptedException e) { + logger.warn("TaskRunner thread interrupted before it was able to shutdown all running tasks."); + } + + logger.info("TaskRunner stopped."); + } + + /** + * Schedules new task to be run + * + * @param task task to be scheduled + * @return Future reference which can be used to gain results after the Task has finished + */ + public synchronized Future scheduleTask(Task task) { + logger.info("Task {} called by {} has been scheduled.", task.getId(), task.getCaller()); + return this.executor.submit(task); + } +} diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/Task.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/Task.java index 2a6a8598..ef0d6ae3 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/Task.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/Task.java @@ -1,97 +1,97 @@ -package cz.zcu.kiv.crce.concurrency.model; - -import java.util.concurrent.Callable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Task base class to be used by client modules. Override this class to provide - * the actual code of the job to be done in background. - * - * @param Job result type - * - * Date: 11.11.13 - * - * @author Jakub Danek - */ -public abstract class Task implements Callable { - - private static final Logger logger = LoggerFactory.getLogger(Task.class); - - private final String id; - private final String description; - private final String caller; - private TaskState state; - - /** - * Initialize Task description for easy tracking. Keep in mind that id,module pair should be always - * unique! - * - * @param id job ID - * @param description job description - * @param module calling module - for easy tracking of where the Task has come from - */ - protected Task(String id, String description, String module) { - this.id = id; - this.description = description; - this.caller = module; - setState(TaskState.CREATED); - } - - public String getId() { - return id; - } - - public String getDescription() { - return description; - } - - public String getCaller() { - return caller; - } - - /** - * - * @return state the task finds itself in currently - */ - public synchronized TaskState getState() { - return state; - } - - public final synchronized void setState(TaskState state) { - this.state = state; - } - - /** - * Computes a result, or throws an exception if unable to do so. - * - * @return computed result - * @throws Exception if unable to compute a result - */ - @Override - @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) - public final T call() throws Exception { - setState(TaskState.RUNNING); - logger.info("Task {} called by {} has been started.", id, caller); - logger.debug("Task description: {}", description); - T obj; - try { - obj = run(); - } catch (Throwable t) { - logger.error("Error while executing task {}", id, t); - throw t; - } - setState(TaskState.FINISHED); //should be set AFTER returning the object - // probably will require listener thread for the TaskRunner - logger.info("Task {} called by {} has finished.", id, caller); - return obj; - } - - /** - * Override this to provide job's logic. Optionaly the job can return a result. - * @return - * @throws Exception - */ - protected abstract T run() throws Exception; -} +package cz.zcu.kiv.crce.concurrency.model; + +import java.util.concurrent.Callable; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Task base class to be used by client modules. Override this class to provide + * the actual code of the job to be done in background. + * + * @param Job result type + * + * Date: 11.11.13 + * + * @author Jakub Danek + */ +public abstract class Task implements Callable { + + private static final Logger logger = LoggerFactory.getLogger(Task.class); + + private final String id; + private final String description; + private final String caller; + private TaskState state; + + /** + * Initialize Task description for easy tracking. Keep in mind that id,module pair should be always + * unique! + * + * @param id job ID + * @param description job description + * @param module calling module - for easy tracking of where the Task has come from + */ + protected Task(String id, String description, String module) { + this.id = id; + this.description = description; + this.caller = module; + setState(TaskState.CREATED); + } + + public String getId() { + return id; + } + + public String getDescription() { + return description; + } + + public String getCaller() { + return caller; + } + + /** + * + * @return state the task finds itself in currently + */ + public synchronized TaskState getState() { + return state; + } + + public final synchronized void setState(TaskState state) { + this.state = state; + } + + /** + * Computes a result, or throws an exception if unable to do so. + * + * @return computed result + * @throws Exception if unable to compute a result + */ + @Override + @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) + public final T call() throws Exception { + setState(TaskState.RUNNING); + logger.info("Task {} called by {} has been started.", id, caller); + logger.debug("Task description: {}", description); + T obj; + try { + obj = run(); + } catch (Throwable t) { + logger.error("Error while executing task {}", id, t); + throw t; + } + setState(TaskState.FINISHED); //should be set AFTER returning the object + // probably will require listener thread for the TaskRunner + logger.info("Task {} called by {} has finished.", id, caller); + return obj; + } + + /** + * Override this to provide job's logic. Optionaly the job can return a result. + * @return + * @throws Exception + */ + protected abstract T run() throws Exception; +} diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/TaskState.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/TaskState.java index cfdc1219..af82135d 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/TaskState.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/model/TaskState.java @@ -1,23 +1,23 @@ -package cz.zcu.kiv.crce.concurrency.model; - -/** - * Enumeration for marking the state of a particular Task. - * - * Date: 13.11.13 - * - * @author Jakub Danek - */ -public enum TaskState { - /** - * The task has been created and potentially scheduled. - */ - CREATED, - /** - * The task has started its job. - */ - RUNNING, - /** - * The task has finished its job. - */ - FINISHED -} +package cz.zcu.kiv.crce.concurrency.model; + +/** + * Enumeration for marking the state of a particular Task. + * + * Date: 13.11.13 + * + * @author Jakub Danek + */ +public enum TaskState { + /** + * The task has been created and potentially scheduled. + */ + CREATED, + /** + * The task has started its job. + */ + RUNNING, + /** + * The task has finished its job. + */ + FINISHED +} diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/TaskRunnerService.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/TaskRunnerService.java index 23dfb37b..03a6c173 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/TaskRunnerService.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/TaskRunnerService.java @@ -1,23 +1,23 @@ -package cz.zcu.kiv.crce.concurrency.service; - -import cz.zcu.kiv.crce.concurrency.model.Task; - -/** - * Public API for TaskRunner. - * - * Date: 11.11.13 - * - * @author Jakub Danek - */ -public interface TaskRunnerService { - - /** - * Schedule a task to be run in background when crce has available resources. - * - * There is no definition nor assurance of when the task will be run. - * - * @param task {@link Task instance containing the definition of the job to be done} - * @throws {@link java.util.concurrent.RejectedExecutionException} when the task cannot be scheduled - */ - void scheduleTask(Task task); -} +package cz.zcu.kiv.crce.concurrency.service; + +import cz.zcu.kiv.crce.concurrency.model.Task; + +/** + * Public API for TaskRunner. + * + * Date: 11.11.13 + * + * @author Jakub Danek + */ +public interface TaskRunnerService { + + /** + * Schedule a task to be run in background when crce has available resources. + * + * There is no definition nor assurance of when the task will be run. + * + * @param task {@link Task instance containing the definition of the job to be done} + * @throws {@link java.util.concurrent.RejectedExecutionException} when the task cannot be scheduled + */ + void scheduleTask(Task task); +} diff --git a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/internal/TaskRunnerServiceImpl.java b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/internal/TaskRunnerServiceImpl.java index d88c9f1b..01f86f4b 100644 --- a/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/internal/TaskRunnerServiceImpl.java +++ b/modules/crce-concurrency/src/main/java/cz/zcu/kiv/crce/concurrency/service/internal/TaskRunnerServiceImpl.java @@ -1,31 +1,31 @@ -package cz.zcu.kiv.crce.concurrency.service.internal; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.concurrency.model.Task; -import cz.zcu.kiv.crce.concurrency.internal.TaskRunner; -import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; - -/** - * Date: 11.11.13 - * - * @author Jakub Danek - */ -public class TaskRunnerServiceImpl implements TaskRunnerService { - private static final Logger logger = LoggerFactory.getLogger(TaskRunnerServiceImpl.class); - - /** - * Schedule a task to be run in background when crce has available resources. - *

- * There is no definition nor assurance of when the task will be run and user may not - * count on that. - * - * @param task {@link cz.zcu.kiv.crce.concurrency.model.Task instance containing the definition of the job to be done} - */ - @Override - public void scheduleTask(Task task) { - logger.debug("Service scheduleTask(task) has been called."); - TaskRunner.get().scheduleTask(task); - } -} +package cz.zcu.kiv.crce.concurrency.service.internal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.concurrency.model.Task; +import cz.zcu.kiv.crce.concurrency.internal.TaskRunner; +import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; + +/** + * Date: 11.11.13 + * + * @author Jakub Danek + */ +public class TaskRunnerServiceImpl implements TaskRunnerService { + private static final Logger logger = LoggerFactory.getLogger(TaskRunnerServiceImpl.class); + + /** + * Schedule a task to be run in background when crce has available resources. + *

+ * There is no definition nor assurance of when the task will be run and user may not + * count on that. + * + * @param task {@link cz.zcu.kiv.crce.concurrency.model.Task instance containing the definition of the job to be done} + */ + @Override + public void scheduleTask(Task task) { + logger.debug("Service scheduleTask(task) has been called."); + TaskRunner.get().scheduleTask(task); + } +} diff --git a/modules/crce-concurrency/src/main/resources/OSGi-INF/service.xml b/modules/crce-concurrency/src/main/resources/OSGi-INF/service.xml index 73d5fb17..2b57ea15 100644 --- a/modules/crce-concurrency/src/main/resources/OSGi-INF/service.xml +++ b/modules/crce-concurrency/src/main/resources/OSGi-INF/service.xml @@ -1,14 +1,14 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/modules/crce-concurrency/src/test/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunnerTest.java b/modules/crce-concurrency/src/test/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunnerTest.java index 75ed7eff..d8fd866f 100644 --- a/modules/crce-concurrency/src/test/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunnerTest.java +++ b/modules/crce-concurrency/src/test/java/cz/zcu/kiv/crce/concurrency/internal/TaskRunnerTest.java @@ -1,136 +1,136 @@ -package cz.zcu.kiv.crce.concurrency.internal; - -import static org.junit.Assert.*; - -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import cz.zcu.kiv.crce.concurrency.model.Task; -import cz.zcu.kiv.crce.concurrency.model.TaskState; - -/** - * TaskRunner functional tests. - * - * Date: 14.11.13 - * - * @author Jakub Danek - */ -public class TaskRunnerTest { - - private TaskRunner runner; - - /** - * Simple task for testing purposes. - * - * Adds two numbers and waits for particular amount of time. - */ - private class TestTask extends Task { - - private int a, b; - private long millisToSleep; - - private TestTask(String id, String description, int a, int b, long millisToSleep) { - super(id, description, "test"); - this.a = a; - this.b = b; - this.millisToSleep = millisToSleep; - } - - @Override - protected Integer run() throws Exception { - Thread.sleep(millisToSleep); - return a + b; - } - } - - @Before - public void before() { - //yes, this is one of the typical reasons why singleton pattern is WRONG. - TaskRunner.init(3); - runner = TaskRunner.get(); - } - - @After - public void after() { - runner.stop(); - } - - /** - * Test that scheduler starts a Task and the Task does its job. - * @throws Exception - */ - @Test - public void taskRunTest() throws Exception{ - Task t = new TestTask("taskRunTest", "Simple task testing rung.", 1, 1, 0); - Future f = runner.scheduleTask(t); - try { - int result = f.get(3, TimeUnit.SECONDS); - assertEquals("How can one make an error in a 1 + 1 calculation?", 2, result); - } catch (TimeoutException e) { //just let other exception bubble up - fail("Simple Task took too long to run, something must have gone wrong."); - } - } - - /** - * Test that only allowed number of threads is spawned. - * - * WARNING: This tests heavily depends on Thread.sleep() functionality. That might potentially lead to instability. - * Might save you some time of debugging in case of failure. - * @throws Exception - */ - @Test - public void resourceUsageTest() throws Exception { - Task t1, t2, t3, t4; - Future f1, f2, f3, f4; - - t1 = new TestTask("resourceUsageTest1", "Sloooooow task", 5, 5, 3000); - t2 = new TestTask("resourceUsageTest2", "Sloooooow task", 5, 5, 3000); - t3 = new TestTask("resourceUsageTest3", "Sloooooow task", 5, 5, 3000); - t4 = new TestTask("resourceUsageTest4", "Speedy Gonzales", 6, 6, 0); - - f1 = runner.scheduleTask(t1); - f2 = runner.scheduleTask(t2); - f3 = runner.scheduleTask(t3); - f4 = runner.scheduleTask(t4); - - assertFalse(f1.isDone()); - assertFalse(f2.isDone()); - assertFalse(f3.isDone()); - assertFalse(f4.isDone()); - - Thread.sleep(100);//give scheduler some time to actually start the tasks - - //only the first 3 are running now - assertEquals("Expected to be running!", TaskState.RUNNING, t1.getState()); - assertEquals("Expected to be running!", TaskState.RUNNING, t2.getState()); - assertEquals("Expected to be running!", TaskState.RUNNING, t3.getState()); - assertEquals("Expected to be waiting!", TaskState.CREATED, t4.getState()); - - try { - f4.get(6, TimeUnit.SECONDS); //wait until t4 is finished - f1.get(1, TimeUnit.SECONDS); - f2.get(1, TimeUnit.SECONDS); - f3.get(1, TimeUnit.SECONDS); - } catch (TimeoutException ex) { - fail("Tasks took too long to run, something must have gone wrong."); - } - - //all finished now - assertEquals("Expected to be running!", TaskState.FINISHED, t1.getState()); - assertEquals("Expected to be running!", TaskState.FINISHED, t2.getState()); - assertEquals("Expected to be running!", TaskState.FINISHED, t3.getState()); - assertEquals("Expected to be waiting!", TaskState.FINISHED, t4.getState()); - - //final check that all the calculations went through correctly - int result = f1.get() + f2.get() + f3.get() + f4.get(); - assertEquals("It's all clear now. The Life, the Universe, and (the) Everything.", 42, result); - - } - - -} +package cz.zcu.kiv.crce.concurrency.internal; + +import static org.junit.Assert.*; + +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import cz.zcu.kiv.crce.concurrency.model.Task; +import cz.zcu.kiv.crce.concurrency.model.TaskState; + +/** + * TaskRunner functional tests. + * + * Date: 14.11.13 + * + * @author Jakub Danek + */ +public class TaskRunnerTest { + + private TaskRunner runner; + + /** + * Simple task for testing purposes. + * + * Adds two numbers and waits for particular amount of time. + */ + private class TestTask extends Task { + + private int a, b; + private long millisToSleep; + + private TestTask(String id, String description, int a, int b, long millisToSleep) { + super(id, description, "test"); + this.a = a; + this.b = b; + this.millisToSleep = millisToSleep; + } + + @Override + protected Integer run() throws Exception { + Thread.sleep(millisToSleep); + return a + b; + } + } + + @Before + public void before() { + //yes, this is one of the typical reasons why singleton pattern is WRONG. + TaskRunner.init(3); + runner = TaskRunner.get(); + } + + @After + public void after() { + runner.stop(); + } + + /** + * Test that scheduler starts a Task and the Task does its job. + * @throws Exception + */ + @Test + public void taskRunTest() throws Exception{ + Task t = new TestTask("taskRunTest", "Simple task testing rung.", 1, 1, 0); + Future f = runner.scheduleTask(t); + try { + int result = f.get(3, TimeUnit.SECONDS); + assertEquals("How can one make an error in a 1 + 1 calculation?", 2, result); + } catch (TimeoutException e) { //just let other exception bubble up + fail("Simple Task took too long to run, something must have gone wrong."); + } + } + + /** + * Test that only allowed number of threads is spawned. + * + * WARNING: This tests heavily depends on Thread.sleep() functionality. That might potentially lead to instability. + * Might save you some time of debugging in case of failure. + * @throws Exception + */ + @Test + public void resourceUsageTest() throws Exception { + Task t1, t2, t3, t4; + Future f1, f2, f3, f4; + + t1 = new TestTask("resourceUsageTest1", "Sloooooow task", 5, 5, 3000); + t2 = new TestTask("resourceUsageTest2", "Sloooooow task", 5, 5, 3000); + t3 = new TestTask("resourceUsageTest3", "Sloooooow task", 5, 5, 3000); + t4 = new TestTask("resourceUsageTest4", "Speedy Gonzales", 6, 6, 0); + + f1 = runner.scheduleTask(t1); + f2 = runner.scheduleTask(t2); + f3 = runner.scheduleTask(t3); + f4 = runner.scheduleTask(t4); + + assertFalse(f1.isDone()); + assertFalse(f2.isDone()); + assertFalse(f3.isDone()); + assertFalse(f4.isDone()); + + Thread.sleep(100);//give scheduler some time to actually start the tasks + + //only the first 3 are running now + assertEquals("Expected to be running!", TaskState.RUNNING, t1.getState()); + assertEquals("Expected to be running!", TaskState.RUNNING, t2.getState()); + assertEquals("Expected to be running!", TaskState.RUNNING, t3.getState()); + assertEquals("Expected to be waiting!", TaskState.CREATED, t4.getState()); + + try { + f4.get(6, TimeUnit.SECONDS); //wait until t4 is finished + f1.get(1, TimeUnit.SECONDS); + f2.get(1, TimeUnit.SECONDS); + f3.get(1, TimeUnit.SECONDS); + } catch (TimeoutException ex) { + fail("Tasks took too long to run, something must have gone wrong."); + } + + //all finished now + assertEquals("Expected to be running!", TaskState.FINISHED, t1.getState()); + assertEquals("Expected to be running!", TaskState.FINISHED, t2.getState()); + assertEquals("Expected to be running!", TaskState.FINISHED, t3.getState()); + assertEquals("Expected to be waiting!", TaskState.FINISHED, t4.getState()); + + //final check that all the calculations went through correctly + int result = f1.get() + f2.get() + f3.get() + f4.get(); + assertEquals("It's all clear now. The Life, the Universe, and (the) Everything.", 42, result); + + } + + +} diff --git a/modules/crce-handler-metrics/osgi.bnd b/modules/crce-handler-metrics/osgi.bnd index f11edfe8..1a26af23 100644 --- a/modules/crce-handler-metrics/osgi.bnd +++ b/modules/crce-handler-metrics/osgi.bnd @@ -1,7 +1,7 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + Embed-Dependency: org.apache.felix.utils \ No newline at end of file diff --git a/modules/crce-handler-metrics/pom.xml b/modules/crce-handler-metrics/pom.xml index 26822521..61b79509 100644 --- a/modules/crce-handler-metrics/pom.xml +++ b/modules/crce-handler-metrics/pom.xml @@ -1,52 +1,52 @@ - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-handler-metrics - bundle - - CRCE - Plugin - Metrics Action Handler - - - ${namespace}.handler.metrics - ${namespace}.handler.metrics - - - - - - - ${project.groupId} - crce-core - pom - - - - - - ${project.groupId} - crce-metadata-osgi-bundle - ${project.version} - - - ${project.groupId} - crce-concurrency - ${project.version} - - - - - - org.ow2.asm - asm-all - 5.0.3 - - + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-handler-metrics + bundle + + CRCE - Plugin - Metrics Action Handler + + + ${namespace}.handler.metrics + ${namespace}.handler.metrics + + + + + + + ${project.groupId} + crce-core + pom + + + + + + ${project.groupId} + crce-metadata-osgi-bundle + ${project.version} + + + ${project.groupId} + crce-concurrency + ${project.version} + + + + + + org.ow2.asm + asm-all + 5.0.3 + + \ No newline at end of file diff --git a/modules/crce-handler-metrics/src/main/java/cz/zcu/kiv/crce/handler/metrics/internal/Activator.java b/modules/crce-handler-metrics/src/main/java/cz/zcu/kiv/crce/handler/metrics/internal/Activator.java index 9fcfa0dc..e936a1f5 100644 --- a/modules/crce-handler-metrics/src/main/java/cz/zcu/kiv/crce/handler/metrics/internal/Activator.java +++ b/modules/crce-handler-metrics/src/main/java/cz/zcu/kiv/crce/handler/metrics/internal/Activator.java @@ -14,7 +14,7 @@ /** - * Activator of this plugin (indexer). + * Activator of this plugin2 (indexer). * * @author Jan Smajcl (smajcl@students.zcu.cz) */ diff --git a/modules/crce-integration-tests/pom.xml b/modules/crce-integration-tests/pom.xml index 65ca7742..ac6b4ece 100644 --- a/modules/crce-integration-tests/pom.xml +++ b/modules/crce-integration-tests/pom.xml @@ -1,185 +1,185 @@ - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.0-SNAPSHOT - - - crce-integration-tests - jar - - CRCE - Integration tests - - - 3.3.0 - UTF-8 - - - - - - org.apache.servicemix.tooling - depends-maven-plugin - - - generate-depends-file - generate-test-resources - - generate-depends-file - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - integration-test - - - - - always - none - 1 - - - - - - - - - - org.osgi - org.osgi.core - test - - - org.apache.felix - org.apache.felix.dependencymanager - test - - - org.apache.felix - org.apache.felix.dependencymanager.runtime - test - - - org.apache.felix - org.apache.felix.configadmin - test - - - org.apache.felix - org.apache.felix.eventadmin - test - - - org.apache.felix - org.apache.felix.bundlerepository - test - - - commons-io - commons-io - test - - - commons-net - commons-net - test - - - org.slf4j - slf4j-api - test - - - org.slf4j - log4j-over-slf4j - test - - - - - - org.ops4j.pax.exam - pax-exam-container-native - ${version.pax-exam} - test - - - org.ops4j.pax.exam - pax-exam-junit4 - ${version.pax-exam} - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - ${version.pax-exam} - test - - - - org.apache.felix - org.apache.felix.framework - test - - - - ch.qos.logback - logback-core - test - - - ch.qos.logback - logback-classic - test - - - com.h2database - h2 - test - - - org.mybatis - mybatis - test - - - - org.apache.ace - org.apache.ace.obr.metadata - test - - - org.apache.ace - org.apache.ace.obr.storage - test - - - org.skyscreamer - jsonassert - test - - - - - - ${project.groupId} - crce-core - pom - test - - - - - + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.0-SNAPSHOT + + + crce-integration-tests + jar + + CRCE - Integration tests + + + 3.3.0 + UTF-8 + + + + + + org.apache.servicemix.tooling + depends-maven-plugin + + + generate-depends-file + generate-test-resources + + generate-depends-file + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + + + + + always + none + 1 + + + + + + + + + + org.osgi + org.osgi.core + test + + + org.apache.felix + org.apache.felix.dependencymanager + test + + + org.apache.felix + org.apache.felix.dependencymanager.runtime + test + + + org.apache.felix + org.apache.felix.configadmin + test + + + org.apache.felix + org.apache.felix.eventadmin + test + + + org.apache.felix + org.apache.felix.bundlerepository + test + + + commons-io + commons-io + test + + + commons-net + commons-net + test + + + org.slf4j + slf4j-api + test + + + org.slf4j + log4j-over-slf4j + test + + + + + + org.ops4j.pax.exam + pax-exam-container-native + ${version.pax-exam} + test + + + org.ops4j.pax.exam + pax-exam-junit4 + ${version.pax-exam} + test + + + org.ops4j.pax.exam + pax-exam-link-mvn + ${version.pax-exam} + test + + + + org.apache.felix + org.apache.felix.framework + test + + + + ch.qos.logback + logback-core + test + + + ch.qos.logback + logback-classic + test + + + com.h2database + h2 + test + + + org.mybatis + mybatis + test + + + + org.apache.ace + org.apache.ace.obr.metadata + test + + + org.apache.ace + org.apache.ace.obr.storage + test + + + org.skyscreamer + jsonassert + test + + + + + + ${project.groupId} + crce-core + pom + test + + + + + diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Configuration.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Configuration.java index ce3f46b0..1e79b10e 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Configuration.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Configuration.java @@ -1,27 +1,27 @@ -package cz.zcu.kiv.crce.it; - -import java.io.IOException; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Configuration { - - public static void metadataDao(IntegrationTestBase integrationTestBase) throws IOException { - integrationTestBase.configure( - cz.zcu.kiv.crce.metadata.dao.internal.Activator.PID, - "jdbc.driver", "org.h2.Driver", - "jdbc.url", "jdbc:h2:mem:it;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", -// "jdbc.url", "jdbc:h2:file:target/metadata/crce;MODE=PostgreSQL;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=19090", - "jdbc.username", "sa", - "jdbc.password", ""); - } - - public static void repository(IntegrationTestBase integrationTestBase) throws IOException { - integrationTestBase.configureFactory( - cz.zcu.kiv.crce.repository.filebased.internal.Activator.PID, - cz.zcu.kiv.crce.repository.filebased.internal.Activator.CFG_PROPERTY__STORE_URI, "target/store" - ); - } -} +package cz.zcu.kiv.crce.it; + +import java.io.IOException; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Configuration { + + public static void metadataDao(IntegrationTestBase integrationTestBase) throws IOException { + integrationTestBase.configure( + cz.zcu.kiv.crce.metadata.dao.internal.Activator.PID, + "jdbc.driver", "org.h2.Driver", + "jdbc.url", "jdbc:h2:mem:it;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", +// "jdbc.url", "jdbc:h2:file:target/metadata/crce;MODE=PostgreSQL;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=19090", + "jdbc.username", "sa", + "jdbc.password", ""); + } + + public static void repository(IntegrationTestBase integrationTestBase) throws IOException { + integrationTestBase.configureFactory( + cz.zcu.kiv.crce.repository.filebased.internal.Activator.PID, + cz.zcu.kiv.crce.repository.filebased.internal.Activator.CFG_PROPERTY__STORE_URI, "target/store" + ); + } +} diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Options.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Options.java index 9c1fcbaa..2f990a75 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Options.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/Options.java @@ -197,7 +197,7 @@ public static MavenArtifactProvisionOption metadataOsgiBundle() { } public static MavenArtifactProvisionOption pluginApi() { - return maven("crce-plugin-api"); + return maven("crce-plugin2-api"); } public static MavenArtifactProvisionOption resolverApi() { diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/context/ContextIT.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/context/ContextIT.java index f84b2d8f..6c2d455d 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/context/ContextIT.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/context/ContextIT.java @@ -1,144 +1,144 @@ -package cz.zcu.kiv.crce.it.context; - -import static junit.framework.TestCase.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.options; - -import java.io.IOException; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; -import org.ops4j.pax.exam.junit.PaxExam; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.osgi.framework.Bundle; -import org.osgi.framework.Constants; - -import org.apache.felix.dm.Component; - -import org.ops4j.pax.exam.spi.reactors.PerMethod; - -import cz.zcu.kiv.crce.it.Configuration; -import cz.zcu.kiv.crce.it.IntegrationTestBase; -import cz.zcu.kiv.crce.it.Options; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * Tests application context, starting of components and services, etc. - */ -@RunWith(PaxExam.class) -@ExamReactorStrategy(PerMethod.class) -public class ContextIT extends IntegrationTestBase { - - private static final Logger logger = LoggerFactory.getLogger(ContextIT.class); - - // injected by dependency manager - private volatile PluginManager pluginManager; - private volatile MetadataFactory metadataFactory; - private volatile ResourceDAO resourceDAO; - private volatile RepositoryDAO repositoryDAO; - private volatile ResourceLoader resourceLoader; - private volatile MetadataService metadataService; - private volatile Store store; - - /** - * Configuration of the OSGi runtime. - * - * @return the configuration - */ - @org.ops4j.pax.exam.Configuration - public final Option[] configuration() { - - logger.info("Option config"); - return options( - junitBundles(), - Options.logging(), - Options.Felix.dependencyManager(), - Options.Felix.configAdmin(), - Options.Felix.eventAdmin(), - Options.Felix.bundleRepository(), - Options.Osgi.compendium(), - - mavenBundle("commons-io", "commons-io"), - - Options.Crce.pluginApi(), - - Options.Crce.metadata(), - Options.Crce.metadataDao(), - Options.Crce.metadataService(), - Options.Crce.resolver(), - Options.Crce.repository(), - - Options.Crce.metadataIndexerApi(), - Options.Crce.metadataIndexerImpl() - - ); - } - - @Override - protected void before() throws IOException { - Configuration.metadataDao(this); - Configuration.repository(this); - } - - @Override - protected Component[] getDependencies() { - return new Component[]{ - createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(PluginManager.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) - .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(ResourceLoader.class).setRequired(true)) - .add(createServiceDependency().setService(Store.class).setRequired(true)) - }; - } - - - @Test - @SuppressWarnings("deprecation") - public void testContext() throws InvalidSyntaxException, InterruptedException { - logger.info("A Simple OSGi Integration Test"); - - assertNotNull(bundleContext); - assertNotNull(dependencyManager); - - logger.info("INIT"); - - logger.info("Property {}: {}", Constants.FRAMEWORK_VENDOR, bundleContext.getProperty(Constants.FRAMEWORK_VENDOR)); - logger.info("Property {}: {}", Constants.FRAMEWORK_VERSION, bundleContext.getProperty(Constants.FRAMEWORK_VERSION)); - logger.info("Property {}: {}", Constants.FRAMEWORK_EXECUTIONENVIRONMENT, bundleContext.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT)); - - logger.info("SERVICES: [service reference] (bundle symbolic name)"); - - for (ServiceReference serviceReference : bundleContext.getAllServiceReferences(null, null)) { - logger.info("Service reference: {} ({})", serviceReference.toString(), serviceReference.getBundle().getSymbolicName()); - } - - logger.info("BUNDLES: symbolic name (location)"); - for (Bundle bundle : bundleContext.getBundles()) { - logger.info("Bundle: {} ({})", bundle.getSymbolicName(), bundle.getLocation()); - } - - assertNotNull(pluginManager); - assertNotNull(metadataFactory); - assertNotNull(resourceDAO); - assertNotNull(repositoryDAO); - assertNotNull(resourceLoader); - assertNotNull(metadataService); - assertNotNull(store); - } -} +package cz.zcu.kiv.crce.it.context; + +import static junit.framework.TestCase.assertNotNull; +import static org.ops4j.pax.exam.CoreOptions.junitBundles; +import static org.ops4j.pax.exam.CoreOptions.options; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; +import org.ops4j.pax.exam.junit.PaxExam; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.osgi.framework.Bundle; +import org.osgi.framework.Constants; + +import org.apache.felix.dm.Component; + +import org.ops4j.pax.exam.spi.reactors.PerMethod; + +import cz.zcu.kiv.crce.it.Configuration; +import cz.zcu.kiv.crce.it.IntegrationTestBase; +import cz.zcu.kiv.crce.it.Options; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * Tests application context, starting of components and services, etc. + */ +@RunWith(PaxExam.class) +@ExamReactorStrategy(PerMethod.class) +public class ContextIT extends IntegrationTestBase { + + private static final Logger logger = LoggerFactory.getLogger(ContextIT.class); + + // injected by dependency manager + private volatile PluginManager pluginManager; + private volatile MetadataFactory metadataFactory; + private volatile ResourceDAO resourceDAO; + private volatile RepositoryDAO repositoryDAO; + private volatile ResourceLoader resourceLoader; + private volatile MetadataService metadataService; + private volatile Store store; + + /** + * Configuration of the OSGi runtime. + * + * @return the configuration + */ + @org.ops4j.pax.exam.Configuration + public final Option[] configuration() { + + logger.info("Option config"); + return options( + junitBundles(), + Options.logging(), + Options.Felix.dependencyManager(), + Options.Felix.configAdmin(), + Options.Felix.eventAdmin(), + Options.Felix.bundleRepository(), + Options.Osgi.compendium(), + + mavenBundle("commons-io", "commons-io"), + + Options.Crce.pluginApi(), + + Options.Crce.metadata(), + Options.Crce.metadataDao(), + Options.Crce.metadataService(), + Options.Crce.resolver(), + Options.Crce.repository(), + + Options.Crce.metadataIndexerApi(), + Options.Crce.metadataIndexerImpl() + + ); + } + + @Override + protected void before() throws IOException { + Configuration.metadataDao(this); + Configuration.repository(this); + } + + @Override + protected Component[] getDependencies() { + return new Component[]{ + createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(PluginManager.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) + .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(ResourceLoader.class).setRequired(true)) + .add(createServiceDependency().setService(Store.class).setRequired(true)) + }; + } + + + @Test + @SuppressWarnings("deprecation") + public void testContext() throws InvalidSyntaxException, InterruptedException { + logger.info("A Simple OSGi Integration Test"); + + assertNotNull(bundleContext); + assertNotNull(dependencyManager); + + logger.info("INIT"); + + logger.info("Property {}: {}", Constants.FRAMEWORK_VENDOR, bundleContext.getProperty(Constants.FRAMEWORK_VENDOR)); + logger.info("Property {}: {}", Constants.FRAMEWORK_VERSION, bundleContext.getProperty(Constants.FRAMEWORK_VERSION)); + logger.info("Property {}: {}", Constants.FRAMEWORK_EXECUTIONENVIRONMENT, bundleContext.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT)); + + logger.info("SERVICES: [service reference] (bundle symbolic name)"); + + for (ServiceReference serviceReference : bundleContext.getAllServiceReferences(null, null)) { + logger.info("Service reference: {} ({})", serviceReference.toString(), serviceReference.getBundle().getSymbolicName()); + } + + logger.info("BUNDLES: symbolic name (location)"); + for (Bundle bundle : bundleContext.getBundles()) { + logger.info("Bundle: {} ({})", bundle.getSymbolicName(), bundle.getLocation()); + } + + assertNotNull(pluginManager); + assertNotNull(metadataFactory); + assertNotNull(resourceDAO); + assertNotNull(repositoryDAO); + assertNotNull(resourceLoader); + assertNotNull(metadataService); + assertNotNull(store); + } +} diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/dao/ResourceDAOIT.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/dao/ResourceDAOIT.java index bf84744d..6f2cd72b 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/dao/ResourceDAOIT.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/dao/ResourceDAOIT.java @@ -1,200 +1,200 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *//* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package cz.zcu.kiv.crce.it.dao; - -import static org.ops4j.pax.exam.CoreOptions.*; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.commons.io.FileUtils; -import org.apache.felix.dm.Component; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.it.Configuration; -import cz.zcu.kiv.crce.it.IntegrationTestBase; -import cz.zcu.kiv.crce.it.Options; -import cz.zcu.kiv.crce.it.Options.Crce; -import cz.zcu.kiv.crce.it.Options.Felix; -import cz.zcu.kiv.crce.it.Options.Osgi; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * This class serves as a minimal example of our integration tests. Also, if this test fails, something is likely wrong with the environment - */ -@RunWith(PaxExam.class) -public class ResourceDAOIT extends IntegrationTestBase { - - private static final Logger logger = LoggerFactory.getLogger(ResourceDAOIT.class); - - /* - @Configuration - public Option[] configuration() { - return options( - // you can add additional directives, e.g. systemProperty or VMOptions here - junitBundles(), - provision( - Osgi.compendium(), - Felix.dependencyManager() - // add additional bundles here - ) - ); - } - */ - - /** - * Container includes and provides these packages when container is started. - */ - private final String systemPackages - = "com.sun.*,javax.xml.*,com.sun.org.apache.xerces.internal.*," - + "javax.accessibility,javax.annotation,javax.inject,javax.jmdns,javax.jms,javax.mail," - + "javax.mail.internet,javax.management,javax.management.modelmbean,javax.management.remote," - + "javax.microedition.io,javax.naming,javax.naming.spi,javax.script,javax.security.auth.x500,javax.servlet," - + "javax.servlet.http,javax.servlet.jsp,javax.sql," - + "org.w3c.dom,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers," - + "org.w3c.dom.xpath,sun.io,org.w3c.dom.ls," - + "com.sun.java_cup.internal,com.sun.xml.internal.bind.v2," - + "javax.net,javax.net.ssl,javax.transaction.xa," - + "org.apache.commons.io"; - - // This allows delegation of XPathFactory implementation to MyBatis. - private final String bootDelegationPackages = "sun.*,com.sun.*"; - - /** - * Configuration of the OSGi runtime. - * - * @return the configuration - */ - @org.ops4j.pax.exam.Configuration - public Option[] configuration() { - - return options( - systemPackage(systemPackages), - bootDelegationPackage(bootDelegationPackages), - junitBundles(), - Options.logging(), - Felix.dependencyManager(), - - Osgi.compendium(), - Felix.configAdmin(), - - Crce.pluginApi(), - - Crce.metadata(), - Crce.metadataService(), - Crce.metadataJson(), - Crce.metadataDao() - ); - } - - @Override - protected void before() throws IOException { - // configure the services you need; you cannot use the injected members yet - Configuration.metadataDao(this); - } - - @Override - protected Component[] getDependencies() { - return new Component[]{ - // create Dependency Manager components that should be started before the - // test starts. - createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) - .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) - }; - } - - // You can inject services as usual. - private volatile MetadataFactory metadataFactory; /* injected by dependency manager */ - private volatile ResourceDAO resourceDAO; /* injected by dependency manager */ - private volatile RepositoryDAO repositoryDAO; /* injected by dependency manager */ - private volatile MetadataService metadataService; /* injected by dependency manager */ - private volatile MetadataJsonMapper metadataJsonMapper; - - - @Test - public void testResourceDAOImp() throws IOException, URISyntaxException { - - Repository repository = metadataFactory.createRepository(new URI("file://a/b")); - - repositoryDAO.saveRepository(repository); - - Resource expected = metadataJsonMapper.deserialize(FileUtils.readFileToString(new File("src/test/resources/dao/Resource1.json"))); - assertNotNull(expected); - - //test boolean loading - assertTrue(metadataService.getIdentity(expected).getAttribute(new SimpleAttributeType("confirmed", Boolean.class)).getValue()); - - metadataService.getIdentity(expected).setAttribute("repository-id", String.class, repository.getId()); - - URI uri = metadataService.getUri(expected); - - resourceDAO.saveResource(expected); - Resource actual = resourceDAO.loadResource(uri); - - assertNotNull(actual); - - assertEquals(expected, actual); - - assertTrue(expected.equalsTo(actual, EqualityLevel.KEY)); - assertTrue(expected.equalsTo(actual, EqualityLevel.SHALLOW_NO_KEY)); - assertTrue(expected.equalsTo(actual, EqualityLevel.SHALLOW_WITH_KEY)); - assertTrue(expected.equalsTo(actual, EqualityLevel.DEEP_NO_KEY)); - assertTrue(expected.equalsTo(actual, EqualityLevel.DEEP_WITH_KEY)); - - //test boolean storage - assertTrue(metadataService.getIdentity(actual).getAttribute(new SimpleAttributeType("confirmed", Boolean.class)).getValue()); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *//* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package cz.zcu.kiv.crce.it.dao; + +import static org.ops4j.pax.exam.CoreOptions.*; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.commons.io.FileUtils; +import org.apache.felix.dm.Component; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.PaxExam; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.it.Configuration; +import cz.zcu.kiv.crce.it.IntegrationTestBase; +import cz.zcu.kiv.crce.it.Options; +import cz.zcu.kiv.crce.it.Options.Crce; +import cz.zcu.kiv.crce.it.Options.Felix; +import cz.zcu.kiv.crce.it.Options.Osgi; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * This class serves as a minimal example of our integration tests. Also, if this test fails, something is likely wrong with the environment + */ +@RunWith(PaxExam.class) +public class ResourceDAOIT extends IntegrationTestBase { + + private static final Logger logger = LoggerFactory.getLogger(ResourceDAOIT.class); + + /* + @Configuration + public Option[] configuration() { + return options( + // you can add additional directives, e.g. systemProperty or VMOptions here + junitBundles(), + provision( + Osgi.compendium(), + Felix.dependencyManager() + // add additional bundles here + ) + ); + } + */ + + /** + * Container includes and provides these packages when container is started. + */ + private final String systemPackages + = "com.sun.*,javax.xml.*,com.sun.org.apache.xerces.internal.*," + + "javax.accessibility,javax.annotation,javax.inject,javax.jmdns,javax.jms,javax.mail," + + "javax.mail.internet,javax.management,javax.management.modelmbean,javax.management.remote," + + "javax.microedition.io,javax.naming,javax.naming.spi,javax.script,javax.security.auth.x500,javax.servlet," + + "javax.servlet.http,javax.servlet.jsp,javax.sql," + + "org.w3c.dom,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers," + + "org.w3c.dom.xpath,sun.io,org.w3c.dom.ls," + + "com.sun.java_cup.internal,com.sun.xml.internal.bind.v2," + + "javax.net,javax.net.ssl,javax.transaction.xa," + + "org.apache.commons.io"; + + // This allows delegation of XPathFactory implementation to MyBatis. + private final String bootDelegationPackages = "sun.*,com.sun.*"; + + /** + * Configuration of the OSGi runtime. + * + * @return the configuration + */ + @org.ops4j.pax.exam.Configuration + public Option[] configuration() { + + return options( + systemPackage(systemPackages), + bootDelegationPackage(bootDelegationPackages), + junitBundles(), + Options.logging(), + Felix.dependencyManager(), + + Osgi.compendium(), + Felix.configAdmin(), + + Crce.pluginApi(), + + Crce.metadata(), + Crce.metadataService(), + Crce.metadataJson(), + Crce.metadataDao() + ); + } + + @Override + protected void before() throws IOException { + // configure the services you need; you cannot use the injected members yet + Configuration.metadataDao(this); + } + + @Override + protected Component[] getDependencies() { + return new Component[]{ + // create Dependency Manager components that should be started before the + // test starts. + createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) + .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) + }; + } + + // You can inject services as usual. + private volatile MetadataFactory metadataFactory; /* injected by dependency manager */ + private volatile ResourceDAO resourceDAO; /* injected by dependency manager */ + private volatile RepositoryDAO repositoryDAO; /* injected by dependency manager */ + private volatile MetadataService metadataService; /* injected by dependency manager */ + private volatile MetadataJsonMapper metadataJsonMapper; + + + @Test + public void testResourceDAOImp() throws IOException, URISyntaxException { + + Repository repository = metadataFactory.createRepository(new URI("file://a/b")); + + repositoryDAO.saveRepository(repository); + + Resource expected = metadataJsonMapper.deserialize(FileUtils.readFileToString(new File("src/test/resources/dao/Resource1.json"))); + assertNotNull(expected); + + //test boolean loading + assertTrue(metadataService.getIdentity(expected).getAttribute(new SimpleAttributeType("confirmed", Boolean.class)).getValue()); + + metadataService.getIdentity(expected).setAttribute("repository-id", String.class, repository.getId()); + + URI uri = metadataService.getUri(expected); + + resourceDAO.saveResource(expected); + Resource actual = resourceDAO.loadResource(uri); + + assertNotNull(actual); + + assertEquals(expected, actual); + + assertTrue(expected.equalsTo(actual, EqualityLevel.KEY)); + assertTrue(expected.equalsTo(actual, EqualityLevel.SHALLOW_NO_KEY)); + assertTrue(expected.equalsTo(actual, EqualityLevel.SHALLOW_WITH_KEY)); + assertTrue(expected.equalsTo(actual, EqualityLevel.DEEP_NO_KEY)); + assertTrue(expected.equalsTo(actual, EqualityLevel.DEEP_WITH_KEY)); + + //test boolean storage + assertTrue(metadataService.getIdentity(actual).getAttribute(new SimpleAttributeType("confirmed", Boolean.class)).getValue()); + } +} diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/json/MetadataJsonMapperIT.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/json/MetadataJsonMapperIT.java index 57f93559..d9d32214 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/json/MetadataJsonMapperIT.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/json/MetadataJsonMapperIT.java @@ -1,294 +1,294 @@ -package cz.zcu.kiv.crce.it.json; - -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.options; - -import java.util.Arrays; -import java.util.List; - -import org.apache.felix.dm.Component; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.ops4j.pax.exam.CoreOptions; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; -import org.ops4j.pax.exam.spi.reactors.PerMethod; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.it.IntegrationTestBase; -import cz.zcu.kiv.crce.it.Options; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@RunWith(PaxExam.class) -@ExamReactorStrategy(PerMethod.class) -public class MetadataJsonMapperIT extends IntegrationTestBase { - - private static final Logger logger = LoggerFactory.getLogger(MetadataJsonMapperIT.class); - - private volatile MetadataJsonMapper mapper; - private volatile MetadataFactory metadataFactory; - - @org.ops4j.pax.exam.Configuration - public final Option[] configuration() { - - logger.info("Option config"); - - return options( - CoreOptions.systemPackage("org.skyscreamer.jsonassert"), - junitBundles(), - Options.logging(), - Options.Osgi.compendium(), - Options.Felix.dependencyManager(), - Options.Felix.configAdmin(), - - Options.Crce.metadata(), - Options.Crce.metadataJson() - ); - } - - @Override - protected Component[] getDependencies() { - return new Component[]{ - createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - }; - } - - @Test - public void testContext() { - assertNotNull(metadataFactory); - assertNotNull(mapper); - } - - @Test - public void testResourceSerialization() throws Exception { - Resource resource = createResource(); - - // --- test --- - - String json = mapper.serialize(resource); - assertNotNull(json); - - Resource actual = mapper.deserialize(json); - assertNotNull(actual); - - assertTrue(actual.equalsTo(resource, EqualityLevel.DEEP_WITH_KEY)); - - JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); - } - - @Test - public void testCapabilitySerialization() throws Exception { - List capabilities = Arrays.asList(new Capability[]{createCapability1(null), createCapability2(null)}); - for (Capability capability : capabilities) { - - String json = mapper.serialize(capability); - assertNotNull(json); - - Capability actual = mapper.deserialize(json, Capability.class); - assertNotNull(actual); - - assertTrue(capability.getNamespace(), actual.equalsTo(capability, EqualityLevel.DEEP_WITH_KEY)); - - JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); - } - } - - @Test - public void testRequirementSerialization() throws Exception { - List requirements = Arrays.asList(new Requirement[]{createRequirement1(null), createRequirement2(null)}); - for (Requirement requirement : requirements) { - - String json = mapper.serialize(requirement); - assertNotNull(json); - - Requirement actual = mapper.deserialize(json, Requirement.class); - assertNotNull(actual); - - assertTrue(actual.equalsTo(requirement, EqualityLevel.DEEP_WITH_KEY)); - - JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); - } - } - - @Test - @SuppressWarnings("unchecked") - public void testPropertySerialization() throws Exception { - List properties = Arrays.asList(new Property[]{createProperty1(null), createProperty2(null)}); - for (Property property : properties) { - - String json = mapper.serialize(property); - assertNotNull(json); - - Property actual = mapper.deserialize(json, Property.class); - assertNotNull(actual); - - assertTrue(actual.equalsTo(property, EqualityLevel.DEEP_WITH_KEY)); - - JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); - } - } - - private Resource createResource() throws Exception { - Resource resource = metadataFactory.createResource("res1"); - - createProperty1(resource); - - createCapability1(resource); - - createCapability2(resource); - - createRequirement1(resource); - - createRequirement2(resource); - - return resource; - } - - private Property createProperty1(Resource resource) { - Property resourceProperty = metadataFactory.createProperty("prop.ns1", "prop1"); - resourceProperty.setAttribute(new SimpleAttributeType<>("patr1", String.class), "pval1", Operator.NOT_EQUAL); - resourceProperty.setAttribute(new SimpleAttributeType<>("patr2", Long.class), 123L, Operator.LESS); - - if (resource != null) { - resource.addProperty(resourceProperty); - } - return resourceProperty; - } - - private Requirement createRequirement2(Resource resource) { - // --- requirement 2 --- - Requirement requirement = metadataFactory.createRequirement("ns7", "req3"); - if (resource != null) { - resource.addRequirement(requirement); - } - - requirement.addAttribute(new SimpleAttributeType<>("atr1", String.class), "a", Operator.GREATER); - - return requirement; - } - - private Requirement createRequirement1(Resource resource) { - Requirement requirement = metadataFactory.createRequirement("ns5", "req1"); - if (resource != null) { - resource.addRequirement(requirement); - } - - requirement.addAttribute(new SimpleAttributeType<>("atr1", Version.class), new Version(1, 2, 3), Operator.GREATER); - requirement.addAttribute(new SimpleAttributeType<>("atr2", Version.class), new Version(2, 0, 0), Operator.LESS); - - requirement.setDirective("dir1", "aa"); - requirement.setDirective("dir2", "bb"); - - Requirement child = metadataFactory.createRequirement("ns6", "req2"); - requirement.addChild(child); - - child.addAttribute(new SimpleAttributeType<>("atr1", String.class), "a1", Operator.GREATER); - child.addAttribute(new SimpleAttributeType<>("atr2", String.class), "a2", Operator.LESS); - - child.setDirective("dir1", "aa"); - child.setDirective("dir2", "bb"); - - return requirement; - } - - private Capability createCapability1(Resource resource) { - Capability capability = metadataFactory.createCapability("ns1", "cap1"); - if (resource != null) { - resource.addCapability(capability); - resource.addRootCapability(capability); - } - - // attributes - capability.setAttribute(new SimpleAttributeType<>("atr1", String.class), "val1", Operator.EQUAL); - capability.setAttribute(new SimpleAttributeType<>("atr2", Long.class), 123L, Operator.GREATER); - capability.setAttribute(new SimpleAttributeType<>("atr3", Double.class), 3.14, Operator.APPROX); - capability.setAttribute(new SimpleAttributeType<>("atr4", Version.class), new Version(1, 2, 3, "SNAPSHOT"), Operator.NOT_EQUAL); - capability.setAttribute(new ListAttributeType("atr5"), Arrays.asList("a", "b", "c")); - - // directives - capability.setDirective("d1", "a"); - capability.setDirective("d2", "b"); - - createProperty2(capability); - - // --- capability 1 children --- - // child 1 - Capability child = metadataFactory.createCapability("ns2", "cap2"); - if (resource != null) { - resource.addCapability(child); - } - - capability.addChild(child); - - child.setAttribute(new SimpleAttributeType<>("c1atr1", String.class), "c1val1", Operator.EQUAL); - - // child 2 - child = metadataFactory.createCapability("ns3", "cap3"); - if (resource != null) { - resource.addCapability(child); - } - - capability.addChild(child); - - child.setAttribute(new SimpleAttributeType<>("c2atr1", String.class), "c2val1", Operator.EQUAL); - - // requirements - Requirement requirement1 = metadataFactory.createRequirement("ns8", "c2req1"); - requirement1.addAttribute("c2req1atr1", String.class, "c2req1atr1val"); - requirement1.addAttribute("c2req1atr2", String.class, "c2req1atr2val"); - - capability.addRequirement(requirement1); - - Requirement requirement2 = metadataFactory.createRequirement("ns8", "c2req2"); - requirement2.addAttribute("c2req2atr1", String.class, "c2req2atr1val"); - requirement2.addAttribute("c2req2atr2", Long.class, 123L); - - requirement1.addChild(requirement2); - - return capability; - } - - private Property createProperty2(Capability capability) { - // properties - Property property = metadataFactory.createProperty("ns2", "prop1"); - property.setAttribute("atr6", String.class, "pval1"); - property.setAttribute("atr7", String.class, "pval2"); - - if (capability != null) { - capability.addProperty(property); - } - - return property; - } - - private Capability createCapability2(Resource resource) { - Capability capability = metadataFactory.createCapability("ns4", "cap4"); - if (resource != null) { - resource.addCapability(capability); - resource.addRootCapability(capability); - } - return capability; - } -} +package cz.zcu.kiv.crce.it.json; + +import static org.ops4j.pax.exam.CoreOptions.junitBundles; +import static org.ops4j.pax.exam.CoreOptions.options; + +import java.util.Arrays; +import java.util.List; + +import org.apache.felix.dm.Component; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.CoreOptions; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.PaxExam; +import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; +import org.ops4j.pax.exam.spi.reactors.PerMethod; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.it.IntegrationTestBase; +import cz.zcu.kiv.crce.it.Options; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@RunWith(PaxExam.class) +@ExamReactorStrategy(PerMethod.class) +public class MetadataJsonMapperIT extends IntegrationTestBase { + + private static final Logger logger = LoggerFactory.getLogger(MetadataJsonMapperIT.class); + + private volatile MetadataJsonMapper mapper; + private volatile MetadataFactory metadataFactory; + + @org.ops4j.pax.exam.Configuration + public final Option[] configuration() { + + logger.info("Option config"); + + return options( + CoreOptions.systemPackage("org.skyscreamer.jsonassert"), + junitBundles(), + Options.logging(), + Options.Osgi.compendium(), + Options.Felix.dependencyManager(), + Options.Felix.configAdmin(), + + Options.Crce.metadata(), + Options.Crce.metadataJson() + ); + } + + @Override + protected Component[] getDependencies() { + return new Component[]{ + createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + }; + } + + @Test + public void testContext() { + assertNotNull(metadataFactory); + assertNotNull(mapper); + } + + @Test + public void testResourceSerialization() throws Exception { + Resource resource = createResource(); + + // --- test --- + + String json = mapper.serialize(resource); + assertNotNull(json); + + Resource actual = mapper.deserialize(json); + assertNotNull(actual); + + assertTrue(actual.equalsTo(resource, EqualityLevel.DEEP_WITH_KEY)); + + JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + public void testCapabilitySerialization() throws Exception { + List capabilities = Arrays.asList(new Capability[]{createCapability1(null), createCapability2(null)}); + for (Capability capability : capabilities) { + + String json = mapper.serialize(capability); + assertNotNull(json); + + Capability actual = mapper.deserialize(json, Capability.class); + assertNotNull(actual); + + assertTrue(capability.getNamespace(), actual.equalsTo(capability, EqualityLevel.DEEP_WITH_KEY)); + + JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); + } + } + + @Test + public void testRequirementSerialization() throws Exception { + List requirements = Arrays.asList(new Requirement[]{createRequirement1(null), createRequirement2(null)}); + for (Requirement requirement : requirements) { + + String json = mapper.serialize(requirement); + assertNotNull(json); + + Requirement actual = mapper.deserialize(json, Requirement.class); + assertNotNull(actual); + + assertTrue(actual.equalsTo(requirement, EqualityLevel.DEEP_WITH_KEY)); + + JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); + } + } + + @Test + @SuppressWarnings("unchecked") + public void testPropertySerialization() throws Exception { + List properties = Arrays.asList(new Property[]{createProperty1(null), createProperty2(null)}); + for (Property property : properties) { + + String json = mapper.serialize(property); + assertNotNull(json); + + Property actual = mapper.deserialize(json, Property.class); + assertNotNull(actual); + + assertTrue(actual.equalsTo(property, EqualityLevel.DEEP_WITH_KEY)); + + JSONAssert.assertEquals(json, mapper.serialize(actual), JSONCompareMode.NON_EXTENSIBLE); + } + } + + private Resource createResource() throws Exception { + Resource resource = metadataFactory.createResource("res1"); + + createProperty1(resource); + + createCapability1(resource); + + createCapability2(resource); + + createRequirement1(resource); + + createRequirement2(resource); + + return resource; + } + + private Property createProperty1(Resource resource) { + Property resourceProperty = metadataFactory.createProperty("prop.ns1", "prop1"); + resourceProperty.setAttribute(new SimpleAttributeType<>("patr1", String.class), "pval1", Operator.NOT_EQUAL); + resourceProperty.setAttribute(new SimpleAttributeType<>("patr2", Long.class), 123L, Operator.LESS); + + if (resource != null) { + resource.addProperty(resourceProperty); + } + return resourceProperty; + } + + private Requirement createRequirement2(Resource resource) { + // --- requirement 2 --- + Requirement requirement = metadataFactory.createRequirement("ns7", "req3"); + if (resource != null) { + resource.addRequirement(requirement); + } + + requirement.addAttribute(new SimpleAttributeType<>("atr1", String.class), "a", Operator.GREATER); + + return requirement; + } + + private Requirement createRequirement1(Resource resource) { + Requirement requirement = metadataFactory.createRequirement("ns5", "req1"); + if (resource != null) { + resource.addRequirement(requirement); + } + + requirement.addAttribute(new SimpleAttributeType<>("atr1", Version.class), new Version(1, 2, 3), Operator.GREATER); + requirement.addAttribute(new SimpleAttributeType<>("atr2", Version.class), new Version(2, 0, 0), Operator.LESS); + + requirement.setDirective("dir1", "aa"); + requirement.setDirective("dir2", "bb"); + + Requirement child = metadataFactory.createRequirement("ns6", "req2"); + requirement.addChild(child); + + child.addAttribute(new SimpleAttributeType<>("atr1", String.class), "a1", Operator.GREATER); + child.addAttribute(new SimpleAttributeType<>("atr2", String.class), "a2", Operator.LESS); + + child.setDirective("dir1", "aa"); + child.setDirective("dir2", "bb"); + + return requirement; + } + + private Capability createCapability1(Resource resource) { + Capability capability = metadataFactory.createCapability("ns1", "cap1"); + if (resource != null) { + resource.addCapability(capability); + resource.addRootCapability(capability); + } + + // attributes + capability.setAttribute(new SimpleAttributeType<>("atr1", String.class), "val1", Operator.EQUAL); + capability.setAttribute(new SimpleAttributeType<>("atr2", Long.class), 123L, Operator.GREATER); + capability.setAttribute(new SimpleAttributeType<>("atr3", Double.class), 3.14, Operator.APPROX); + capability.setAttribute(new SimpleAttributeType<>("atr4", Version.class), new Version(1, 2, 3, "SNAPSHOT"), Operator.NOT_EQUAL); + capability.setAttribute(new ListAttributeType("atr5"), Arrays.asList("a", "b", "c")); + + // directives + capability.setDirective("d1", "a"); + capability.setDirective("d2", "b"); + + createProperty2(capability); + + // --- capability 1 children --- + // child 1 + Capability child = metadataFactory.createCapability("ns2", "cap2"); + if (resource != null) { + resource.addCapability(child); + } + + capability.addChild(child); + + child.setAttribute(new SimpleAttributeType<>("c1atr1", String.class), "c1val1", Operator.EQUAL); + + // child 2 + child = metadataFactory.createCapability("ns3", "cap3"); + if (resource != null) { + resource.addCapability(child); + } + + capability.addChild(child); + + child.setAttribute(new SimpleAttributeType<>("c2atr1", String.class), "c2val1", Operator.EQUAL); + + // requirements + Requirement requirement1 = metadataFactory.createRequirement("ns8", "c2req1"); + requirement1.addAttribute("c2req1atr1", String.class, "c2req1atr1val"); + requirement1.addAttribute("c2req1atr2", String.class, "c2req1atr2val"); + + capability.addRequirement(requirement1); + + Requirement requirement2 = metadataFactory.createRequirement("ns8", "c2req2"); + requirement2.addAttribute("c2req2atr1", String.class, "c2req2atr1val"); + requirement2.addAttribute("c2req2atr2", Long.class, 123L); + + requirement1.addChild(requirement2); + + return capability; + } + + private Property createProperty2(Capability capability) { + // properties + Property property = metadataFactory.createProperty("ns2", "prop1"); + property.setAttribute("atr6", String.class, "pval1"); + property.setAttribute("atr7", String.class, "pval2"); + + if (capability != null) { + capability.addProperty(property); + } + + return property; + } + + private Capability createCapability2(Resource resource) { + Capability capability = metadataFactory.createCapability("ns4", "cap4"); + if (resource != null) { + resource.addCapability(capability); + resource.addRootCapability(capability); + } + return capability; + } +} diff --git a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/resolver/ResolverLoaderIT.java b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/resolver/ResolverLoaderIT.java index 0a585611..484db6ce 100644 --- a/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/resolver/ResolverLoaderIT.java +++ b/modules/crce-integration-tests/src/test/java/cz/zcu/kiv/crce/it/resolver/ResolverLoaderIT.java @@ -1,300 +1,300 @@ -package cz.zcu.kiv.crce.it.resolver; - -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.options; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -import org.apache.commons.io.FileUtils; -import org.apache.felix.dm.Component; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.ops4j.pax.exam.CoreOptions; - -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; -import org.ops4j.pax.exam.spi.reactors.PerMethod; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.it.Configuration; -import cz.zcu.kiv.crce.it.IntegrationTestBase; -import cz.zcu.kiv.crce.it.Options; -import cz.zcu.kiv.crce.metadata.EqualityLevel; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@SuppressWarnings("null") -@RunWith(PaxExam.class) -@ExamReactorStrategy(PerMethod.class) -public class ResolverLoaderIT extends IntegrationTestBase { - - private static final Logger logger = LoggerFactory.getLogger(ResolverLoaderIT.class); - - private volatile ResourceLoader resourceLoader; - private volatile ResourceDAO resourceDAO; - private volatile RepositoryDAO repositoryDAO; - private volatile MetadataFactory metadataFactory; - private volatile MetadataService metadataService; - private volatile MetadataJsonMapper metadataJsonMapper; - - private Repository repository; - private Resource resource1; - private Resource resource2; - private Resource resource3; - - @Override - protected void before() throws IOException, URISyntaxException { - Configuration.metadataDao(this); - } - - @org.ops4j.pax.exam.Configuration - public final Option[] configuration() { - - logger.info("Option config"); - return options( - CoreOptions.systemPackage("org.apache.commons.io"), - junitBundles(), - Options.logging(), - Options.Osgi.compendium(), - Options.Felix.dependencyManager(), - Options.Felix.configAdmin(), - Options.Felix.eventAdmin(), - Options.Felix.bundleRepository(), - - Options.Crce.pluginApi(), - - Options.Crce.metadataJson(), - Options.Crce.metadata(), - Options.Crce.metadataDao(), - Options.Crce.metadataService(), - Options.Crce.resolver() - - ); - } - - @Override - protected Component[] getDependencies() { - return new Component[]{ - createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(ResourceLoader.class).setRequired(true)) - .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) - .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) - }; - } - - @Override - public void setupTest() throws Exception { - super.setupTest(); - - String json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource1.json")); - resource1 = metadataJsonMapper.deserialize(json); - - assertNotNull(resource1); - - repository = metadataFactory.createRepository(new URI("file:/C:/some/repository/path/"), "d9e321fc-7e2d-a123-bc9f-f2ead3d5ac88"); - assertNotNull(repository); - assertNotNull(repository.getUri()); - - json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource2.json")); - resource2 = metadataJsonMapper.deserialize(json); - assertNotNull(resource2); -// assertNotNull(resource2.getRepository()); -// assertNotNull(resource2.getRepository().getURI()); - -// assertEquals(repository.getUri(), resource2.getRepository().getURI()); - assertFalse(resource1.equalsTo(resource2, EqualityLevel.KEY)); - assertFalse(resource1.equalsTo(resource2, EqualityLevel.DEEP_WITH_KEY)); - - json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource3.json")); - resource3 = metadataJsonMapper.deserialize(json); - assertNotNull(resource3); -// assertNotNull(resource3.getRepository()); -// assertNotNull(resource3.getRepository().getURI()); - -// assertEquals(repository.getUri(), resource3.getRepository().getURI()); - assertFalse(resource1.equalsTo(resource3, EqualityLevel.KEY)); - assertFalse(resource1.equalsTo(resource3, EqualityLevel.DEEP_WITH_KEY)); - assertFalse(resource2.equalsTo(resource3, EqualityLevel.KEY)); - assertFalse(resource2.equalsTo(resource3, EqualityLevel.DEEP_WITH_KEY)); - - repositoryDAO.saveRepository(repository); - resourceDAO.saveResource(resource1); - resourceDAO.saveResource(resource2); - resourceDAO.saveResource(resource3); - - List resources = resourceDAO.loadResources(repository); - assertNotNull(resources); - assertEquals(3, resources.size()); - } - - @Test - public void testContext() throws Exception { - assertNotNull(resourceLoader); - assertNotNull(resourceDAO); - assertNotNull(repositoryDAO); - assertNotNull(metadataFactory); - assertNotNull(metadataJsonMapper); - assertNotNull(metadataService); - } - - @Test - public void testRequirementWithNoAttributes() throws Exception { - Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - List resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertTrue(resources.contains(resource3)); - } - - @Test - public void testRequirementWithOneAttribute() throws Exception { - Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test", Operator.EQUAL); - - List resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertFalse(resources.contains(resource3)); - } - - @Test - public void testRequirementWithTwoAttributes() throws Exception { - Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.EQUAL); - - List resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertFalse(resources.contains(resource2)); - assertFalse(resources.contains(resource3)); - } - - @Test - public void testRequirementsWithVersion() throws Exception { - Requirement requirement; - List resources; - - // GREATER - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.GREATER); - - resources = resourceLoader.getResources(repository, requirement); - - assertFalse(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertTrue(resources.contains(resource3)); - - - // GREATER_EQUAL - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.GREATER_EQUAL); - - resources = resourceLoader.getResources(repository, requirement); - - assertFalse(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertTrue(resources.contains(resource3)); - - - // LESS - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.1.0"), Operator.LESS); - - resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertFalse(resources.contains(resource3)); - - - // LESS_EQUAL - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.LESS_EQUAL); - - resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertFalse(resources.contains(resource3)); - - - // NOT_EQUAL - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.NOT_EQUAL); - - resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertFalse(resources.contains(resource2)); - assertTrue(resources.contains(resource3)); - - - // APPROX - requirement = metadataFactory.createRequirement("osgi.wiring.package"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); - requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.APPROX); - - resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertTrue(resources.contains(resource2)); - assertFalse(resources.contains(resource3)); - } - - @Test - public void testRequirementWithOrOperatorDirective() throws Exception { - Requirement requirement = metadataFactory.createRequirement("osgi.identity"); - - requirement.addAttribute("name", String.class, "cz.zcu.kiv.test-bundle-1.0.0", Operator.EQUAL); - requirement.addAttribute("name", String.class, "cz.zcu.kiv.other-test-bundle-1.0.0", Operator.EQUAL); - requirement.setDirective("operator", "or"); - - List resources = resourceLoader.getResources(repository, requirement); - - assertTrue(resources.contains(resource1)); - assertFalse(resources.contains(resource2)); - assertTrue(resources.contains(resource3)); - } - -} +package cz.zcu.kiv.crce.it.resolver; + +import static org.ops4j.pax.exam.CoreOptions.junitBundles; +import static org.ops4j.pax.exam.CoreOptions.options; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.felix.dm.Component; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.CoreOptions; + +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.PaxExam; +import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; +import org.ops4j.pax.exam.spi.reactors.PerMethod; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.it.Configuration; +import cz.zcu.kiv.crce.it.IntegrationTestBase; +import cz.zcu.kiv.crce.it.Options; +import cz.zcu.kiv.crce.metadata.EqualityLevel; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.json.MetadataJsonMapper; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@SuppressWarnings("null") +@RunWith(PaxExam.class) +@ExamReactorStrategy(PerMethod.class) +public class ResolverLoaderIT extends IntegrationTestBase { + + private static final Logger logger = LoggerFactory.getLogger(ResolverLoaderIT.class); + + private volatile ResourceLoader resourceLoader; + private volatile ResourceDAO resourceDAO; + private volatile RepositoryDAO repositoryDAO; + private volatile MetadataFactory metadataFactory; + private volatile MetadataService metadataService; + private volatile MetadataJsonMapper metadataJsonMapper; + + private Repository repository; + private Resource resource1; + private Resource resource2; + private Resource resource3; + + @Override + protected void before() throws IOException, URISyntaxException { + Configuration.metadataDao(this); + } + + @org.ops4j.pax.exam.Configuration + public final Option[] configuration() { + + logger.info("Option config"); + return options( + CoreOptions.systemPackage("org.apache.commons.io"), + junitBundles(), + Options.logging(), + Options.Osgi.compendium(), + Options.Felix.dependencyManager(), + Options.Felix.configAdmin(), + Options.Felix.eventAdmin(), + Options.Felix.bundleRepository(), + + Options.Crce.pluginApi(), + + Options.Crce.metadataJson(), + Options.Crce.metadata(), + Options.Crce.metadataDao(), + Options.Crce.metadataService(), + Options.Crce.resolver() + + ); + } + + @Override + protected Component[] getDependencies() { + return new Component[]{ + createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(ResourceLoader.class).setRequired(true)) + .add(createServiceDependency().setService(ResourceDAO.class).setRequired(true)) + .add(createServiceDependency().setService(RepositoryDAO.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataJsonMapper.class).setRequired(true)) + }; + } + + @Override + public void setupTest() throws Exception { + super.setupTest(); + + String json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource1.json")); + resource1 = metadataJsonMapper.deserialize(json); + + assertNotNull(resource1); + + repository = metadataFactory.createRepository(new URI("file:/C:/some/repository/path/"), "d9e321fc-7e2d-a123-bc9f-f2ead3d5ac88"); + assertNotNull(repository); + assertNotNull(repository.getUri()); + + json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource2.json")); + resource2 = metadataJsonMapper.deserialize(json); + assertNotNull(resource2); +// assertNotNull(resource2.getRepository()); +// assertNotNull(resource2.getRepository().getURI()); + +// assertEquals(repository.getUri(), resource2.getRepository().getURI()); + assertFalse(resource1.equalsTo(resource2, EqualityLevel.KEY)); + assertFalse(resource1.equalsTo(resource2, EqualityLevel.DEEP_WITH_KEY)); + + json = FileUtils.readFileToString(new File("src/test/resources/resolver/Resource3.json")); + resource3 = metadataJsonMapper.deserialize(json); + assertNotNull(resource3); +// assertNotNull(resource3.getRepository()); +// assertNotNull(resource3.getRepository().getURI()); + +// assertEquals(repository.getUri(), resource3.getRepository().getURI()); + assertFalse(resource1.equalsTo(resource3, EqualityLevel.KEY)); + assertFalse(resource1.equalsTo(resource3, EqualityLevel.DEEP_WITH_KEY)); + assertFalse(resource2.equalsTo(resource3, EqualityLevel.KEY)); + assertFalse(resource2.equalsTo(resource3, EqualityLevel.DEEP_WITH_KEY)); + + repositoryDAO.saveRepository(repository); + resourceDAO.saveResource(resource1); + resourceDAO.saveResource(resource2); + resourceDAO.saveResource(resource3); + + List resources = resourceDAO.loadResources(repository); + assertNotNull(resources); + assertEquals(3, resources.size()); + } + + @Test + public void testContext() throws Exception { + assertNotNull(resourceLoader); + assertNotNull(resourceDAO); + assertNotNull(repositoryDAO); + assertNotNull(metadataFactory); + assertNotNull(metadataJsonMapper); + assertNotNull(metadataService); + } + + @Test + public void testRequirementWithNoAttributes() throws Exception { + Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + List resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertTrue(resources.contains(resource3)); + } + + @Test + public void testRequirementWithOneAttribute() throws Exception { + Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test", Operator.EQUAL); + + List resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertFalse(resources.contains(resource3)); + } + + @Test + public void testRequirementWithTwoAttributes() throws Exception { + Requirement requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.EQUAL); + + List resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertFalse(resources.contains(resource2)); + assertFalse(resources.contains(resource3)); + } + + @Test + public void testRequirementsWithVersion() throws Exception { + Requirement requirement; + List resources; + + // GREATER + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.GREATER); + + resources = resourceLoader.getResources(repository, requirement); + + assertFalse(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertTrue(resources.contains(resource3)); + + + // GREATER_EQUAL + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.GREATER_EQUAL); + + resources = resourceLoader.getResources(repository, requirement); + + assertFalse(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertTrue(resources.contains(resource3)); + + + // LESS + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.1.0"), Operator.LESS); + + resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertFalse(resources.contains(resource3)); + + + // LESS_EQUAL + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.LESS_EQUAL); + + resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertFalse(resources.contains(resource3)); + + + // NOT_EQUAL + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.1"), Operator.NOT_EQUAL); + + resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertFalse(resources.contains(resource2)); + assertTrue(resources.contains(resource3)); + + + // APPROX + requirement = metadataFactory.createRequirement("osgi.wiring.package"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test.helper", Operator.EQUAL); + requirement.addAttribute("version", Version.class, new Version("1.0.0"), Operator.APPROX); + + resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertTrue(resources.contains(resource2)); + assertFalse(resources.contains(resource3)); + } + + @Test + public void testRequirementWithOrOperatorDirective() throws Exception { + Requirement requirement = metadataFactory.createRequirement("osgi.identity"); + + requirement.addAttribute("name", String.class, "cz.zcu.kiv.test-bundle-1.0.0", Operator.EQUAL); + requirement.addAttribute("name", String.class, "cz.zcu.kiv.other-test-bundle-1.0.0", Operator.EQUAL); + requirement.setDirective("operator", "or"); + + List resources = resourceLoader.getResources(repository, requirement); + + assertTrue(resources.contains(resource1)); + assertFalse(resources.contains(resource2)); + assertTrue(resources.contains(resource3)); + } + +} diff --git a/modules/crce-integration-tests/src/test/resources/dao/Resource1.json b/modules/crce-integration-tests/src/test/resources/dao/Resource1.json index 4ebaecb7..2fb9ad0e 100644 --- a/modules/crce-integration-tests/src/test/resources/dao/Resource1.json +++ b/modules/crce-integration-tests/src/test/resources/dao/Resource1.json @@ -1,250 +1,250 @@ -{ - "id": "ag123815-2d6c-478b-92e8-87b3dz99dhrf", - "capabilities": [ - { - "id": "asd68hj3-1e21-4d19-b812-add51h2u6r28", - "namespace": "crce.identity", - "attributes": [ - { - "name": "file-name", - "type": "String", - "value": "crce-test.jar" - }, { - "name": "name", - "type": "String", - "value": "CRCE Testing Bundle" - }, { - "name": "categories", - "type": "List", - "value": "zip,osgi" - }, { - "name": "uri", - "type": "URI", - "value": "file://a/b/c" - }, { - "name": "size", - "type": "Long", - "value": "990836" - }, { - "name": "repository-id", - "type": "String", - "value": "d9e321fc-7e2d-a123-bc9f-f2ead3d5ac88" - }, { - "name": "confirmed", - "type": "Boolean", - "value": "true" - } - ] - }, { - "id": "sd6f8437-e321-4fa3-b033-46a21d231193", - "namespace": "osgi.wiring.bundle", - "attributes": [ - { - "name": "manifestversion", - "type": "String", - "value": "2" - }, { - "name": "symbolicname", - "type": "String", - "value": "cz.zcu.kiv.test-bundle" - }, { - "name": "presentationname", - "type": "String", - "value": "CRCE Testing Bundle" - }, { - "name": "version", - "type": "Version", - "value": "1.0.0" - } - ], - "directives": { - "directive1": "value1" - }, - "requirements": [ - { - "id": "asd213e2-e20a-4b21-w321-dsda3212d3fd", - "namespace": "nested.requirement", - "attributes": [ - { - "name": "nested", - "type": "String", - "value": "nested requirement value" - }, - { - "name": "version", - "type": "Version", - "operator": "equal", - "value": "1.2.3" - } - ], - "directives": { - "some-directive": "This is a directive" - } - } - ], - "children": [ - { - "id": "fasd23h8-0a73-a54e-b716-a0f55de847fa", - "namespace": "osgi.wiring.package", - "attributes": [ - { - "name": "name", - "type": "String", - "value": "cz.zcu.kiv.test" - }, { - "name": "version", - "type": "Version", - "value": "1.0.0" - } - ], - "directives": { - "uses": "javax.servlet" - } - }, { - "id": "e321r2d8-d843-447d-b524-47a3651f28cd", - "namespace": "osgi.wiring.package", - "attributes": [ - { - "name": "name", - "type": "String", - "value": "cz.zcu.kiv.test.helper" - }, { - "name": "version", - "type": "Version", - "value": "1.0.0" - } - ] - } - ] - }, { - "id": "ad6513g2-e20a-4b21-w321-d321f32s03fd", - "namespace": "osgi.identity", - "attributes": [ - { - "name": "description", - "type": "String", - "value": "This is a virtual bundle for integration tests purposes." - }, { - "name": "name", - "type": "String", - "value": "cz.zcu.kiv.test-bundle-1.0.0" - }, { - "name": "symbolicname", - "type": "String", - "value": "cz.zcu.kiv.test-bundle" - }, { - "name": "documentation", - "type": "String", - "value": "https://www.assembla.com/spaces/crce" - }, { - "name": "presentationname", - "type": "String", - "value": "CRCE Testing Bundle" - }, { - "name": "license", - "type": "String", - "value": "http://www.apache.org/licenses/LICENSE-2.0" - }, { - "name": "version", - "type": "String", - "value": "1.0.0" - } - ] - } - ], - "requirements": [ - { - "id": "dasd2e12-e20a-4b21-w321-dsd2f13203fd", - "namespace": "osgi.wiring.package", - "attributes": [ - { - "name": "name", - "type": "String", - "value": "org.osgi.util.tracker" - }, - { - "name": "version", - "type": "Version", - "operator": "greater-equal", - "value": "1.5.6" - }, - { - "name": "version", - "type": "Version", - "operator": "less", - "value": "3.0.0" - } - ], - "directives": { - "text": "Import package org.osgi.util.tracker;version=\"[1.5,2)\"" - }, - "children": [ - { - "id": "g2w13d12-a32a-w321-d321-z2w15532s1fd", - "namespace": "osgi.wiring.package.virtual", - "attributes": [ - { - "name": "some-name", - "type": "String", - "value": "some-value" - }, - { - "name": "some-other-name", - "type": "Long", - "value": 4 - } - ], - "directives": { - "dir1": "aa", - "dir2": "bb" - } - } - ] - }, { - "id": "asd213e2-e20a-4b21-w321-dsda3212d3fd", - "namespace": "osgi.wiring.package", - "attributes": [ - { - "name": "name", - "type": "String", - "value": "org.osgi.util.version" - }, - { - "name": "version", - "type": "Version", - "operator": "greater-equal", - "value": "3.0.1" - }, - { - "name": "version", - "type": "Version", - "operator": "less", - "value": "4.0.0" - } - ], - "directives": { - "text": "Import package org.osgi.util.version;version=\"[3.0.1,4)\"" - } - } - ], - "properties": [ - { - "id": "12313d12-465a-w321-d321-8462132373fd", - "namespace": "prop.ns1", - "attributes": [ - { - "name": "patr2", - "type": "Long", - "operator": "less", - "value": "123" - }, - { - "name": "patr1", - "type": "String", - "operator": "not-equal", - "value": "pval1" - } - ] - } - ] +{ + "id": "ag123815-2d6c-478b-92e8-87b3dz99dhrf", + "capabilities": [ + { + "id": "asd68hj3-1e21-4d19-b812-add51h2u6r28", + "namespace": "crce.identity", + "attributes": [ + { + "name": "file-name", + "type": "String", + "value": "crce-test.jar" + }, { + "name": "name", + "type": "String", + "value": "CRCE Testing Bundle" + }, { + "name": "categories", + "type": "List", + "value": "zip,osgi" + }, { + "name": "uri", + "type": "URI", + "value": "file://a/b/c" + }, { + "name": "size", + "type": "Long", + "value": "990836" + }, { + "name": "repository-id", + "type": "String", + "value": "d9e321fc-7e2d-a123-bc9f-f2ead3d5ac88" + }, { + "name": "confirmed", + "type": "Boolean", + "value": "true" + } + ] + }, { + "id": "sd6f8437-e321-4fa3-b033-46a21d231193", + "namespace": "osgi.wiring.bundle", + "attributes": [ + { + "name": "manifestversion", + "type": "String", + "value": "2" + }, { + "name": "symbolicname", + "type": "String", + "value": "cz.zcu.kiv.test-bundle" + }, { + "name": "presentationname", + "type": "String", + "value": "CRCE Testing Bundle" + }, { + "name": "version", + "type": "Version", + "value": "1.0.0" + } + ], + "directives": { + "directive1": "value1" + }, + "requirements": [ + { + "id": "asd213e2-e20a-4b21-w321-dsda3212d3fd", + "namespace": "nested.requirement", + "attributes": [ + { + "name": "nested", + "type": "String", + "value": "nested requirement value" + }, + { + "name": "version", + "type": "Version", + "operator": "equal", + "value": "1.2.3" + } + ], + "directives": { + "some-directive": "This is a directive" + } + } + ], + "children": [ + { + "id": "fasd23h8-0a73-a54e-b716-a0f55de847fa", + "namespace": "osgi.wiring.package", + "attributes": [ + { + "name": "name", + "type": "String", + "value": "cz.zcu.kiv.test" + }, { + "name": "version", + "type": "Version", + "value": "1.0.0" + } + ], + "directives": { + "uses": "javax.servlet" + } + }, { + "id": "e321r2d8-d843-447d-b524-47a3651f28cd", + "namespace": "osgi.wiring.package", + "attributes": [ + { + "name": "name", + "type": "String", + "value": "cz.zcu.kiv.test.helper" + }, { + "name": "version", + "type": "Version", + "value": "1.0.0" + } + ] + } + ] + }, { + "id": "ad6513g2-e20a-4b21-w321-d321f32s03fd", + "namespace": "osgi.identity", + "attributes": [ + { + "name": "description", + "type": "String", + "value": "This is a virtual bundle for integration tests purposes." + }, { + "name": "name", + "type": "String", + "value": "cz.zcu.kiv.test-bundle-1.0.0" + }, { + "name": "symbolicname", + "type": "String", + "value": "cz.zcu.kiv.test-bundle" + }, { + "name": "documentation", + "type": "String", + "value": "https://www.assembla.com/spaces/crce" + }, { + "name": "presentationname", + "type": "String", + "value": "CRCE Testing Bundle" + }, { + "name": "license", + "type": "String", + "value": "http://www.apache.org/licenses/LICENSE-2.0" + }, { + "name": "version", + "type": "String", + "value": "1.0.0" + } + ] + } + ], + "requirements": [ + { + "id": "dasd2e12-e20a-4b21-w321-dsd2f13203fd", + "namespace": "osgi.wiring.package", + "attributes": [ + { + "name": "name", + "type": "String", + "value": "org.osgi.util.tracker" + }, + { + "name": "version", + "type": "Version", + "operator": "greater-equal", + "value": "1.5.6" + }, + { + "name": "version", + "type": "Version", + "operator": "less", + "value": "3.0.0" + } + ], + "directives": { + "text": "Import package org.osgi.util.tracker;version=\"[1.5,2)\"" + }, + "children": [ + { + "id": "g2w13d12-a32a-w321-d321-z2w15532s1fd", + "namespace": "osgi.wiring.package.virtual", + "attributes": [ + { + "name": "some-name", + "type": "String", + "value": "some-value" + }, + { + "name": "some-other-name", + "type": "Long", + "value": 4 + } + ], + "directives": { + "dir1": "aa", + "dir2": "bb" + } + } + ] + }, { + "id": "asd213e2-e20a-4b21-w321-dsda3212d3fd", + "namespace": "osgi.wiring.package", + "attributes": [ + { + "name": "name", + "type": "String", + "value": "org.osgi.util.version" + }, + { + "name": "version", + "type": "Version", + "operator": "greater-equal", + "value": "3.0.1" + }, + { + "name": "version", + "type": "Version", + "operator": "less", + "value": "4.0.0" + } + ], + "directives": { + "text": "Import package org.osgi.util.version;version=\"[3.0.1,4)\"" + } + } + ], + "properties": [ + { + "id": "12313d12-465a-w321-d321-8462132373fd", + "namespace": "prop.ns1", + "attributes": [ + { + "name": "patr2", + "type": "Long", + "operator": "less", + "value": "123" + }, + { + "name": "patr1", + "type": "String", + "operator": "not-equal", + "value": "pval1" + } + ] + } + ] } \ No newline at end of file diff --git a/modules/crce-metadata-osgi-bundle/osgi.bnd b/modules/crce-metadata-osgi-bundle/osgi.bnd index f1b85d0f..5163c28e 100644 --- a/modules/crce-metadata-osgi-bundle/osgi.bnd +++ b/modules/crce-metadata-osgi-bundle/osgi.bnd @@ -1,7 +1,7 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Embed-Dependency: kxml2,org.apache.felix.utils +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Embed-Dependency: kxml2,org.apache.felix.utils diff --git a/modules/crce-metadata-osgi-bundle/pom.xml b/modules/crce-metadata-osgi-bundle/pom.xml index b7e57f99..4be2c58e 100644 --- a/modules/crce-metadata-osgi-bundle/pom.xml +++ b/modules/crce-metadata-osgi-bundle/pom.xml @@ -1,71 +1,78 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-metadata-osgi-bundle - bundle - - CRCE - Plugin - OSGi Support - - - ${namespace}.metadata.osgi - ${namespace}.metadata.osgi - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - org.apache.felix - org.apache.felix.bundlerepository - - - org.apache.felix.utils - org.apache.felix - - - - net.sf.kxml - kxml2 - 2.3.0 - - - - - - ${project.groupId} - crce-core - pom - - - - - - junit - junit - - - - cz.zcu.kiv.crce - crce-metadata-impl - 3.0.0 - test - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-metadata-osgi-bundle + bundle + + CRCE - Plugin - OSGi Support + + + ${namespace}.metadata.osgi + ${namespace}.metadata.osgi + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + org.apache.felix + org.apache.felix.bundlerepository + + + org.apache.felix.utils + org.apache.felix + + + + net.sf.kxml + kxml2 + 2.3.0 + + + + + + ${project.groupId} + crce-core + pom + + + + + + junit + junit + + + + cz.zcu.kiv.crce + crce-metadata-impl + 3.0.0 + test + + + + org.apache.maven + maven-model + 3.3.9 + + + + \ No newline at end of file diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Activator.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Activator.java index 4ead4355..babe703f 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Activator.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Activator.java @@ -1,32 +1,32 @@ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import cz.zcu.kiv.crce.plugin.Plugin; -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * Activator of this bundle. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase { - - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - manager.add(createComponent() - .setInterface(Plugin.class.getName(), null) - .setImplementation(OsgiManifestBundleIndexer.class) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - ); - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - - } - -} +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import cz.zcu.kiv.crce.plugin.Plugin; +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * Activator of this bundle. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase { + + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + manager.add(createComponent() + .setInterface(Plugin.class.getName(), null) + .setImplementation(OsgiManifestBundleIndexer.class) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + ); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + + } + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Base64Encoder.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Base64Encoder.java index b00422b8..c51da30b 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Base64Encoder.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/Base64Encoder.java @@ -1,137 +1,137 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - -@SuppressWarnings("PMD") -public class Base64Encoder -{ - private static final byte encTab[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, - 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, - 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, - 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, - 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, - 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f }; - - @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") - public static String base64Encode(String s) throws IOException - { - return encode(s.getBytes(), 0); - } - - /** - * Encode a raw byte array to a Base64 String. - * - * @param in Byte array to encode. - * @param len Length of Base64 lines. 0 means no line breaks. - **/ - @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") - public static String encode(byte[] in, int len) throws IOException - { - ByteArrayOutputStream baos = null; - ByteArrayInputStream bais = null; - try - { - baos = new ByteArrayOutputStream(); - bais = new ByteArrayInputStream(in); - encode(bais, baos, len); - // ASCII byte array to String - return (new String(baos.toByteArray())); - } - finally - { - if (baos != null) - { - baos.close(); - } - if (bais != null) - { - bais.close(); - } - } - } - - @SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Adopted 3rd party implementation.") - public static void encode(InputStream in, OutputStream out, int len) - throws IOException - { - - // Check that length is a multiple of 4 bytes - if (len % 4 != 0) - { - throw new IllegalArgumentException("Length must be a multiple of 4"); - } - - // Read input stream until end of file - int bits = 0; - int nbits = 0; - int nbytes = 0; - int b; - - while ((b = in.read()) != -1) - { - bits = (bits << 8) | b; - nbits += 8; - while (nbits >= 6) - { - nbits -= 6; - out.write(encTab[0x3f & (bits >> nbits)]); - nbytes++; - // New line - if (len != 0 && nbytes >= len) - { - out.write(0x0d); - out.write(0x0a); - nbytes -= len; - } - } - } - - switch (nbits) - { - case 2: - out.write(encTab[0x3f & (bits << 4)]); - out.write(0x3d); // 0x3d = '=' - out.write(0x3d); - break; - case 4: - out.write(encTab[0x3f & (bits << 2)]); - out.write(0x3d); - break; - } - - if (len != 0) - { - if (nbytes != 0) - { - out.write(0x0d); - out.write(0x0a); - } - out.write(0x0d); - out.write(0x0a); - } - } +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + +@SuppressWarnings("PMD") +public class Base64Encoder +{ + private static final byte encTab[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, + 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, + 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f }; + + @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") + public static String base64Encode(String s) throws IOException + { + return encode(s.getBytes(), 0); + } + + /** + * Encode a raw byte array to a Base64 String. + * + * @param in Byte array to encode. + * @param len Length of Base64 lines. 0 means no line breaks. + **/ + @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") + public static String encode(byte[] in, int len) throws IOException + { + ByteArrayOutputStream baos = null; + ByteArrayInputStream bais = null; + try + { + baos = new ByteArrayOutputStream(); + bais = new ByteArrayInputStream(in); + encode(bais, baos, len); + // ASCII byte array to String + return (new String(baos.toByteArray())); + } + finally + { + if (baos != null) + { + baos.close(); + } + if (bais != null) + { + bais.close(); + } + } + } + + @SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Adopted 3rd party implementation.") + public static void encode(InputStream in, OutputStream out, int len) + throws IOException + { + + // Check that length is a multiple of 4 bytes + if (len % 4 != 0) + { + throw new IllegalArgumentException("Length must be a multiple of 4"); + } + + // Read input stream until end of file + int bits = 0; + int nbits = 0; + int nbytes = 0; + int b; + + while ((b = in.read()) != -1) + { + bits = (bits << 8) | b; + nbits += 8; + while (nbits >= 6) + { + nbits -= 6; + out.write(encTab[0x3f & (bits >> nbits)]); + nbytes++; + // New line + if (len != 0 && nbytes >= len) + { + out.write(0x0d); + out.write(0x0a); + nbytes -= len; + } + } + } + + switch (nbits) + { + case 2: + out.write(encTab[0x3f & (bits << 4)]); + out.write(0x3d); // 0x3d = '=' + out.write(0x3d); + break; + case 4: + out.write(encTab[0x3f & (bits << 2)]); + out.write(0x3d); + break; + } + + if (len != 0) + { + if (nbytes != 0) + { + out.write(0x0d); + out.write(0x0a); + } + out.write(0x0d); + out.write(0x0a); + } + } } \ No newline at end of file diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserImpl.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserImpl.java index 9bdf1874..adc9c69a 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserImpl.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserImpl.java @@ -1,198 +1,198 @@ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import org.osgi.framework.InvalidSyntaxException; -import cz.zcu.kiv.crce.metadata.type.Version; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; -import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; - -/** - * Implementation is based on: - * http://www.ietf.org/rfc/rfc1960.txt - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = FilterParser.class) -public class FilterParserImpl implements FilterParser { - - private static final char OPERATOR_AND = '&'; - private static final char OPERATOR_OR = '|'; - private static final char OPERATOR_NOT = '!'; - - private static final char OPEN = '('; - private static final char CLOSE = ')'; - - @ServiceDependency private volatile MetadataFactory metadataFactory; - - @Override - public Requirement parse(String filter, String namespace) throws InvalidSyntaxException { - Requirement requirement = metadataFactory.createRequirement(namespace); - - filter = filter.trim(); - if (filter.isEmpty()) { - return requirement; - } - - parseFilter(filter, requirement, 0, false); - - return requirement; - } - - private void parseFilter(String filter, Requirement requirement, int level, boolean not) throws InvalidSyntaxException { - if (OPEN != filter.charAt(0)) { - throw new InvalidSyntaxException("Missing opening parenthesis: " + filter, filter); - } - if (CLOSE != filter.charAt(filter.length() - 1)) { - throw new InvalidSyntaxException("Missing closing parenthesis: " + filter, filter); - } - parseFilterComp(filter.substring(1, filter.length() - 1), requirement, level, not); - } - - @SuppressWarnings("unchecked") - private void parseFilterComp(String filterComp, Requirement requirement, int level, boolean not) throws InvalidSyntaxException { - switch (filterComp.charAt(0)) { - case OPERATOR_AND: - parseFilterList(filterComp.substring(1), nestRequirement(requirement, level), level + 1); - return; - - case OPERATOR_OR: { - Requirement nested = nestRequirement(requirement, level); - nested.setDirective("operator", "or"); // TODO constants - parseFilterList(filterComp.substring(1), nested, level + 1); - return; - } - - case OPERATOR_NOT: { - parseFilter(filterComp.substring(1), requirement, level + 1, !not); -// Requirement nested = nestRequirement(requirement, level); -// nested.setDirective("operator", "not"); // TODO constants -// parseFilter(filterComp.substring(1), nested, level + 1, false); - return; - } - - default: - parseItem(filterComp, requirement, not); - } - } - - private Requirement nestRequirement(Requirement parent, int level) { - if (level > 0) { - Requirement child = metadataFactory.createRequirement(parent.getNamespace()); - parent.addChild(child); - return child; - } - return parent; - } - - private void parseFilterList(String filterList, Requirement requirement, int level) throws InvalidSyntaxException { - int begin = 0; - int depth = 0; - for (int i = 0; i < filterList.length(); i++) { - if (filterList.charAt(i) == OPEN) { - depth++; - if (depth == 1) { - begin = i; - } - } else if (filterList.charAt(i) == CLOSE) { - depth--; - if (depth == 0) { - parseFilter(filterList.substring(begin, i + 1), requirement, level, false); - } - } - } - if (depth < 0) { - throw new InvalidSyntaxException("Superfluous closing parenthesis: " + filterList, filterList); - } - if (depth > 0) { - throw new InvalidSyntaxException("Missing closing parenthesis: " + filterList, filterList); - } - } - - private void parseItem(String item, Requirement requirement, boolean not) { - Operator operator; - String[] split; - op: { - // two characters operator - split = item.split(">="); - if (split.length == 2) { - operator = not ? Operator.LESS : Operator.GREATER_EQUAL; - break op; - } - split = item.split("<="); - if (split.length == 2) { - operator = not ? Operator.GREATER : Operator.LESS_EQUAL; - break op; - } - split = item.split("<\\*"); - if (split.length == 2) { - if (not) { - throw new IllegalArgumentException("Negation of SUBSET operator is not supported yet."); - } - operator = Operator.SUBSET; - break op; - } - split = item.split("\\*>"); - if (split.length == 2) { - if (not) { - throw new IllegalArgumentException("Negation of SUPERSET operator is not supported yet."); - } - operator = Operator.SUPERSET; - break op; - } - split = item.split("~="); - if (split.length == 2) { - if (not) { - throw new IllegalArgumentException("Negation of APPROX operator is not supported yet."); - } - operator = Operator.APPROX; - break op; - } - // one character operator - split = item.split("="); - if (split.length == 2) { - operator = not ? Operator.NOT_EQUAL : Operator.EQUAL; - break op; - } - split = item.split("<"); - if (split.length == 2) { - operator = not ? Operator.GREATER_EQUAL : Operator.LESS; - break op; - } - split = item.split(">"); - if (split.length == 2) { - operator = not ? Operator.LESS_EQUAL : Operator.GREATER; - break op; - } - throw new IllegalArgumentException("Missing or superfluous operator: " + item); - // TODO NOT_EQUAL("not-equal"), - } - - String name = split[0]; - String value = split[1]; - - if ("*".equals(value)) { - requirement.addAttribute(name, String.class, value, Operator.PRESENT); - } else if (NsOsgiPackage.NAMESPACE__OSGI_PACKAGE.equals(requirement.getNamespace())) { - switch (name) { - case "package": - case "osgi.wiring.package": - requirement.addAttribute(NsOsgiPackage.ATTRIBUTE__NAME, value, operator); - break; - case "version": - requirement.addAttribute(NsOsgiPackage.ATTRIBUTE__VERSION, new Version(value), operator); - break; - default: - requirement.addAttribute(name, String.class, value, operator); - break; - } - } else { - requirement.addAttribute(name, String.class, value, operator); - } - } -} +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import org.osgi.framework.InvalidSyntaxException; +import cz.zcu.kiv.crce.metadata.type.Version; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; +import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; + +/** + * Implementation is based on: + * http://www.ietf.org/rfc/rfc1960.txt + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = FilterParser.class) +public class FilterParserImpl implements FilterParser { + + private static final char OPERATOR_AND = '&'; + private static final char OPERATOR_OR = '|'; + private static final char OPERATOR_NOT = '!'; + + private static final char OPEN = '('; + private static final char CLOSE = ')'; + + @ServiceDependency private volatile MetadataFactory metadataFactory; + + @Override + public Requirement parse(String filter, String namespace) throws InvalidSyntaxException { + Requirement requirement = metadataFactory.createRequirement(namespace); + + filter = filter.trim(); + if (filter.isEmpty()) { + return requirement; + } + + parseFilter(filter, requirement, 0, false); + + return requirement; + } + + private void parseFilter(String filter, Requirement requirement, int level, boolean not) throws InvalidSyntaxException { + if (OPEN != filter.charAt(0)) { + throw new InvalidSyntaxException("Missing opening parenthesis: " + filter, filter); + } + if (CLOSE != filter.charAt(filter.length() - 1)) { + throw new InvalidSyntaxException("Missing closing parenthesis: " + filter, filter); + } + parseFilterComp(filter.substring(1, filter.length() - 1), requirement, level, not); + } + + @SuppressWarnings("unchecked") + private void parseFilterComp(String filterComp, Requirement requirement, int level, boolean not) throws InvalidSyntaxException { + switch (filterComp.charAt(0)) { + case OPERATOR_AND: + parseFilterList(filterComp.substring(1), nestRequirement(requirement, level), level + 1); + return; + + case OPERATOR_OR: { + Requirement nested = nestRequirement(requirement, level); + nested.setDirective("operator", "or"); // TODO constants + parseFilterList(filterComp.substring(1), nested, level + 1); + return; + } + + case OPERATOR_NOT: { + parseFilter(filterComp.substring(1), requirement, level + 1, !not); +// Requirement nested = nestRequirement(requirement, level); +// nested.setDirective("operator", "not"); // TODO constants +// parseFilter(filterComp.substring(1), nested, level + 1, false); + return; + } + + default: + parseItem(filterComp, requirement, not); + } + } + + private Requirement nestRequirement(Requirement parent, int level) { + if (level > 0) { + Requirement child = metadataFactory.createRequirement(parent.getNamespace()); + parent.addChild(child); + return child; + } + return parent; + } + + private void parseFilterList(String filterList, Requirement requirement, int level) throws InvalidSyntaxException { + int begin = 0; + int depth = 0; + for (int i = 0; i < filterList.length(); i++) { + if (filterList.charAt(i) == OPEN) { + depth++; + if (depth == 1) { + begin = i; + } + } else if (filterList.charAt(i) == CLOSE) { + depth--; + if (depth == 0) { + parseFilter(filterList.substring(begin, i + 1), requirement, level, false); + } + } + } + if (depth < 0) { + throw new InvalidSyntaxException("Superfluous closing parenthesis: " + filterList, filterList); + } + if (depth > 0) { + throw new InvalidSyntaxException("Missing closing parenthesis: " + filterList, filterList); + } + } + + private void parseItem(String item, Requirement requirement, boolean not) { + Operator operator; + String[] split; + op: { + // two characters operator + split = item.split(">="); + if (split.length == 2) { + operator = not ? Operator.LESS : Operator.GREATER_EQUAL; + break op; + } + split = item.split("<="); + if (split.length == 2) { + operator = not ? Operator.GREATER : Operator.LESS_EQUAL; + break op; + } + split = item.split("<\\*"); + if (split.length == 2) { + if (not) { + throw new IllegalArgumentException("Negation of SUBSET operator is not supported yet."); + } + operator = Operator.SUBSET; + break op; + } + split = item.split("\\*>"); + if (split.length == 2) { + if (not) { + throw new IllegalArgumentException("Negation of SUPERSET operator is not supported yet."); + } + operator = Operator.SUPERSET; + break op; + } + split = item.split("~="); + if (split.length == 2) { + if (not) { + throw new IllegalArgumentException("Negation of APPROX operator is not supported yet."); + } + operator = Operator.APPROX; + break op; + } + // one character operator + split = item.split("="); + if (split.length == 2) { + operator = not ? Operator.NOT_EQUAL : Operator.EQUAL; + break op; + } + split = item.split("<"); + if (split.length == 2) { + operator = not ? Operator.GREATER_EQUAL : Operator.LESS; + break op; + } + split = item.split(">"); + if (split.length == 2) { + operator = not ? Operator.LESS_EQUAL : Operator.GREATER; + break op; + } + throw new IllegalArgumentException("Missing or superfluous operator: " + item); + // TODO NOT_EQUAL("not-equal"), + } + + String name = split[0]; + String value = split[1]; + + if ("*".equals(value)) { + requirement.addAttribute(name, String.class, value, Operator.PRESENT); + } else if (NsOsgiPackage.NAMESPACE__OSGI_PACKAGE.equals(requirement.getNamespace())) { + switch (name) { + case "package": + case "osgi.wiring.package": + requirement.addAttribute(NsOsgiPackage.ATTRIBUTE__NAME, value, operator); + break; + case "version": + requirement.addAttribute(NsOsgiPackage.ATTRIBUTE__VERSION, new Version(value), operator); + break; + default: + requirement.addAttribute(name, String.class, value, operator); + break; + } + } else { + requirement.addAttribute(name, String.class, value, operator); + } + } +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/ObrType.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/ObrType.java index 6fa7e563..8c393d60 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/ObrType.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/ObrType.java @@ -1,78 +1,78 @@ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import java.util.Arrays; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Legacy OBR property types. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public enum ObrType { - - STRING("string", String.class), - VERSION("version", Version.class), - LONG("long", Long.class), - DOUBLE("double", Double.class), - URL("url", String.class), - URI("uri", String.class), - SET("set", List.class); -// LIST("List", List.class); - - private final String string; - private final Class clazz; - - ObrType(String string, Class clazz) { - this.string = string; - this.clazz = clazz; - } - - @Override - public String toString() { - return string; - } - - public Class getTypeClass() { - return clazz; - } - - /** - * Returns Type for given string value. - * @param value - * @return - */ - public static ObrType getValue(String value) { - if (value != null) { - return valueOf(value.toUpperCase()); - } - return STRING; - } - - public static Object propertyValueFromString(ObrType type, String value) { - if (value == null) { - return null; - } - - switch (type) { - case DOUBLE: - return Double.valueOf(value); - - case SET: - return Arrays.asList(value.split(",")); - - case LONG: - return Long.valueOf(value); - - case STRING: - return String.valueOf(type); - - case VERSION: - return new Version(value); - - default: - return null; - } - } -} +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import java.util.Arrays; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Legacy OBR property types. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public enum ObrType { + + STRING("string", String.class), + VERSION("version", Version.class), + LONG("long", Long.class), + DOUBLE("double", Double.class), + URL("url", String.class), + URI("uri", String.class), + SET("set", List.class); +// LIST("List", List.class); + + private final String string; + private final Class clazz; + + ObrType(String string, Class clazz) { + this.string = string; + this.clazz = clazz; + } + + @Override + public String toString() { + return string; + } + + public Class getTypeClass() { + return clazz; + } + + /** + * Returns Type for given string value. + * @param value + * @return + */ + public static ObrType getValue(String value) { + if (value != null) { + return valueOf(value.toUpperCase()); + } + return STRING; + } + + public static Object propertyValueFromString(ObrType type, String value) { + if (value == null) { + return null; + } + + switch (type) { + case DOUBLE: + return Double.valueOf(value); + + case SET: + return Arrays.asList(value.split(",")); + + case LONG: + return Long.valueOf(value); + + case STRING: + return String.valueOf(type); + + case VERSION: + return new Version(value); + + default: + return null; + } + } +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/OsgiManifestBundleIndexer.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/OsgiManifestBundleIndexer.java index 0e3e01c4..eb90d5e7 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/OsgiManifestBundleIndexer.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/internal/OsgiManifestBundleIndexer.java @@ -1,637 +1,637 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *//* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiFragment; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiExecutionEnvironment; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiService; - -import java.io.*; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.jar.JarFile; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipInputStream; - -import org.apache.felix.utils.manifest.Attribute; -import org.apache.felix.utils.manifest.Clause; -import org.apache.felix.utils.manifest.Directive; -import org.apache.felix.utils.manifest.Parser; -import org.apache.felix.utils.version.VersionCleaner; -import org.apache.felix.utils.version.VersionRange; - -import org.osgi.framework.Constants; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * This is original class DataModelHelperImpl adopted from org.apache.felix.bundlerepository. - * - */ -public class OsgiManifestBundleIndexer extends AbstractResourceIndexer { - - private static final Logger logger = LoggerFactory.getLogger(OsgiManifestBundleIndexer.class); - - public static final String MIME__APPLICATION_OSGI_BUNDLE = "application/vnd.osgi.bundle"; - public static final String BUNDLE_LICENSE = "Bundle-License"; - public static final String BUNDLE_SOURCE = "Bundle-Source"; - - private volatile MetadataFactory metadataFactory; - private volatile MetadataService metadataService; - - @Override - @SuppressWarnings("unchecked") - public List index(final InputStream input, Resource resource) { - - try { - URLStreamHandler handler = new URLStreamHandler() { - @Override - protected URLConnection openConnection(URL u) throws IOException { - return new URLConnection(null) { - @Override - public void connect() throws IOException { - } - - @Override - public InputStream getInputStream() throws IOException { - return input; - } - }; - - } - }; - fillResource(new URL("none", "none", 0, "none", handler), resource); - // fres = repositoryAdmin.getHelper().createResource(new URL("none", "none", 0, "none", handler)); - } catch (MalformedURLException e) { - throw new IllegalStateException("Unexpected MalformedURLException", e); - } catch (ZipException e) { - logger.warn("Zip file is corrupted: {}", resource.getId(), e); - metadataService.addCategory(resource, "corrupted"); - return Collections.singletonList("corrupted"); - } catch (IOException ex) { - logger.error("I/O error on indexing resource: {}", resource.getId(), ex); - return Collections.emptyList(); - } catch (IllegalArgumentException e) { - // not a bundle - return Collections.emptyList(); - } - - Capability osgiIdentity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - - if (osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME) == null) { - return Collections.emptyList(); - } - - cz.zcu.kiv.crce.metadata.Attribute pn = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__PRESENTATION_NAME); - if (pn != null) { - metadataService.setPresentationName(resource, pn.getValue()); - } - cz.zcu.kiv.crce.metadata.Attribute sn = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME); - if(sn != null) { - metadataService.setExternalId(resource, sn.getValue()); - } - - cz.zcu.kiv.crce.metadata.Attribute ver = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION); - if(ver != null) { - Capability identity = metadataService.getIdentity(resource); - identity.setAttribute(NsCrceIdentity.ATTRIBUTE__VERSION, ver.getValue()); - } - - metadataService.addCategory(resource, "osgi"); - - metadataService.getIdentity(resource).setAttribute("mime", String.class, MIME__APPLICATION_OSGI_BUNDLE); // TODO hardcoded - - return Collections.singletonList("osgi"); - } - - @Override - public List getProvidedCategories() { - List result = new ArrayList<>(); - Collections.addAll(result, "osgi", "corrupted"); - return result; - } - - public Resource fillResource(final URL bundleUrl, Resource resource) throws IOException { - fillResource(new Headers() { - private final Manifest manifest; - private Properties localization; - - { - // Do not use a JarInputStream so that we can read the manifest even if it's not - // the first entry in the JAR. - byte[] man = loadEntry(JarFile.MANIFEST_NAME); - if (man == null) { - throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + bundleUrl); - } - manifest = new Manifest(new ByteArrayInputStream(man)); - } - - @Override - public String getHeader(String name) throws IOException { - String value = manifest.getMainAttributes().getValue(name); - if (value != null && value.startsWith("%")) { - if (localization == null) { - localization = new Properties(); - String path = manifest.getMainAttributes().getValue(Constants.BUNDLE_LOCALIZATION); - if (path == null) { - path = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; - } - path += ".properties"; - byte[] loc = loadEntry(path); - if (loc != null) { - localization.load(new ByteArrayInputStream(loc)); - } - } - value = value.substring(1); - value = localization.getProperty(value, value); - } - return value; - } - - private byte[] loadEntry(String name) throws IOException { - try (InputStream is = FileUtil.openURL(bundleUrl); ZipInputStream jis = new ZipInputStream(is)) { - for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry()) { - if (name.equalsIgnoreCase(e.getName())) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buf = new byte[1024]; - int n; - while ((n = jis.read(buf, 0, buf.length)) > 0) { - baos.write(buf, 0, n); - } - return baos.toByteArray(); - } - } - } - return null; - } - }, resource); -// if (resource != null) -// { -// if ("file".equals(bundleUrl.getProtocol())) -// { -// try { -// File f = new File(bundleUrl.toURI()); -// metadataService.setSize(resource, f.length()); -// } catch (URISyntaxException e) { -// throw new RuntimeException(e); -// } -// } -// try { -// metadataService.setUri(resource, bundleUrl.toURI()); -// // resource.put(Resource.URI, bundleUrl.toExternalForm(), null); -// } catch (URISyntaxException e) { -// throw new RuntimeException(e); -// } -// } - return resource; - } - - private Resource fillResource(Headers headers, Resource resource) throws IOException { - String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); - if (bsn == null) { - return null; - } - populate(headers, resource); - return resource; - } - - private void populate(Headers headers, Resource resource) throws IOException { - String bsn = getSymbolicName(headers); - String v = getVersion(headers); - Capability identity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, bsn + "-" + v); - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, bsn); - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, new Version(v)); - if (headers.getHeader(Constants.BUNDLE_NAME) != null) { - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); - } - if (headers.getHeader(Constants.BUNDLE_DESCRIPTION) != null) { - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__DESCRIPTION, headers.getHeader(Constants.BUNDLE_DESCRIPTION)); - } - if (headers.getHeader(BUNDLE_LICENSE) != null) { - String[] licenses = headers.getHeader(BUNDLE_LICENSE).split("[,\\s]+"); - for (String license : licenses) { - List licenseAttributes = identity.getAttributeValue(NsOsgiIdentity.ATTRIBUTE__LICENSES); - if (licenseAttributes == null) { - licenseAttributes = new ArrayList<>(licenses.length); - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__LICENSES, licenseAttributes); - } - licenseAttributes.add(license); - } - } - if (headers.getHeader(Constants.BUNDLE_COPYRIGHT) != null) { - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__COPYRIGHT, headers.getHeader(Constants.BUNDLE_COPYRIGHT)); - } - if (headers.getHeader(Constants.BUNDLE_DOCURL) != null) { - try { - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__DOCUMENTATION_URI, new URI(headers.getHeader(Constants.BUNDLE_DOCURL))); - } catch (URISyntaxException e) { - logger.error("Invalid documentation URI of OSGi resource: {}", headers.getHeader(Constants.BUNDLE_DOCURL), e); - } - } - if (headers.getHeader(BUNDLE_SOURCE) != null) { - try { - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__SOURCE_URI, new URI(headers.getHeader(BUNDLE_SOURCE))); - } catch (URISyntaxException e) { - logger.error("Invalid sources URI of OSGi resource: {}", headers.getHeader(BUNDLE_SOURCE), e); - } - } - - doCategories(resource, headers); - - doBundle(resource, headers); - - doExportServices(resource, null, headers); - doExportPackages(resource, null, headers); - doImportPackages(resource, headers); - doImportServices(resource, headers); - doRequireBundles(resource, headers); - doFragmentsHosts(resource, null, headers); - doExecutionEnvironment(resource, headers); - } - - private void doCategories(Resource resource, Headers headers) throws IOException { - Capability identity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_CATEGORY)); - for (Clause clause : clauses) { - List categories = identity.getAttributeValue(NsOsgiIdentity.ATTRIBUTE__CATEGORY); - if (categories == null) { - categories = new ArrayList<>(clauses.length); - identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__CATEGORY, categories); - } - categories.add(clause.getName()); - } - } - - private void doImportServices(Resource resource, Headers headers) throws IOException { - @SuppressWarnings("deprecation") - Clause[] imports = Parser.parseHeader(headers.getHeader(Constants.IMPORT_SERVICE)); - for (int i = 0; imports != null && i < imports.length; i++) { -// RequirementImpl ri = new RequirementImpl(Capability.SERVICE); - Requirement ri = metadataFactory.createRequirement(NsOsgiService.NAMESPACE__OSGI_SERVICE); - createServiceFilter(ri, imports[i]); - ri.setDirective("text", "Import Service " + imports[i].getName()); // TODO constant - - String avail = imports[i].getDirective("availability"); - String mult = imports[i].getDirective("multiple"); - ri.setDirective("optional", Boolean.toString("optional".equalsIgnoreCase(avail))); // TODO constant - ri.setDirective("multiple", Boolean.toString(!"false".equalsIgnoreCase(mult))); // TODO constant - resource.addRequirement(ri); - } - } - - private void doExportServices(Resource resource, Capability root, Headers headers) throws IOException { - @SuppressWarnings("deprecation") - Clause[] exports = Parser.parseHeader(headers.getHeader(Constants.EXPORT_SERVICE)); - if (exports != null) { - for (Clause export : exports) { - Capability cap = createServiceCapability(export); - resource.addCapability(cap); - if (root != null) { - root.addChild(cap); - } else { - resource.addRootCapability(cap); - } - } - } - } - - private void createServiceFilter(Requirement ri, Clause clause) { - String f = clause.getAttribute("filter"); - ri.addAttribute(NsOsgiService.ATTRIBUTE__NAME, clause.getName()); - - if (f != null) { - ri.setDirective("filter", f); // TODO constant - } - } - - private Capability createServiceCapability(Clause clause) { - Capability capability = metadataFactory.createCapability(NsOsgiService.NAMESPACE__OSGI_SERVICE); - capability.setAttribute(NsOsgiService.ATTRIBUTE__NAME, clause.getName()); - Attribute[] attributes = clause.getAttributes(); - if (attributes != null) { - for (Attribute attribute : attributes) { - capability.setAttribute(new SimpleAttributeType<>(attribute.getName(), String.class), attribute.getValue()); - } - } - return capability; - } - - private void doFragmentsHosts(Resource resource, Capability root, Headers headers) throws IOException { - // Check if we are a fragment - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.FRAGMENT_HOST)); - if (clauses != null && clauses.length == 1) { - // We are a fragment, create a requirement - // to our host. - Requirement r = metadataFactory.createRequirement(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); - r.addAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, clauses[0].getName()); - appendVersion(r, NsOsgiBundle.ATTRIBUTE__VERSION, VersionRange.parseVersionRange(clauses[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE))); - r.setDirective("text", "Required Host " + clauses[0].getName()); // TODO constant - r.setDirective("extend", "true"); // TODO constant - r.setDirective("optional", "false"); // TODO constant - r.setDirective("multiple", "false"); // TODO constant - resource.addRequirement(r); - - // And insert a capability that we are available - // as a fragment. ### Do we need that with extend? - Capability capability = metadataFactory.createCapability(NsOsgiFragment.NAMESPACE__OSGI_FRAGMENT); - capability.setAttribute(NsOsgiFragment.ATTRIBUTE__HOST, clauses[0].getName()); - capability.setAttribute(NsOsgiFragment.ATTRIBUTE__VERSION, new Version(getVersion(clauses[0]))); - resource.addCapability(capability); - if (root != null) { - root.addChild(capability); - } else { - resource.addRootCapability(capability); - } - - } - } - - private void doRequireBundles(Resource resource, Headers headers) throws IOException { - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.REQUIRE_BUNDLE)); - for (int i = 0; clauses != null && i < clauses.length; i++) { - Requirement r = metadataFactory.createRequirement(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); - - VersionRange v = VersionRange.parseVersionRange(clauses[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)); - - r.addAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, clauses[i].getName()); - - appendVersion(r, NsOsgiBundle.ATTRIBUTE__VERSION, v); - - r.setDirective("text", "Require Bundle " + clauses[i].getName() + "; " + v); // TODO constant - r.setDirective("optional", Boolean.toString( // TODO constant - Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE)))); - resource.addRequirement(r); - } - } - - private Capability doBundle(Resource resource, Headers headers) throws IOException { - Capability capability = metadataFactory.createCapability(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); - capability.setAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, getSymbolicName(headers)); - if (headers.getHeader(Constants.BUNDLE_NAME) != null) { - capability.setAttribute(NsOsgiBundle.ATTRIBUTE__PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); - } - capability.setAttribute(NsOsgiBundle.ATTRIBUTE__VERSION, new Version(getVersion(headers))); - capability.setAttribute(NsOsgiBundle.ATTRIBUTE__MANIFEST_VERSION, getManifestVersion(headers)); - resource.addCapability(capability); - resource.addRootCapability(capability); - return capability; - } - - private void doExportPackages(Resource resource, Capability root, Headers headers) throws IOException { - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.EXPORT_PACKAGE)); - if (clauses != null) { - for (Clause clause : clauses) { - Capability capability = createCapability(clause); // Capability.PACKAGE, - resource.addCapability(capability); - if (root != null) { - root.addChild(capability); - } else { - resource.addRootCapability(capability); - } - } - } - } - - @SuppressWarnings("deprecation") - private Capability createCapability(Clause clause) { - Capability capability = metadataFactory.createCapability(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); - capability.setAttribute(NsOsgiPackage.ATTRIBUTE__NAME, clause.getName()); - capability.setAttribute(NsOsgiPackage.ATTRIBUTE__VERSION, new Version(getVersion(clause))); - Attribute[] attributes = clause.getAttributes(); - for (int i = 0; attributes != null && i < attributes.length; i++) { - String key = attributes[i].getName(); - if (!key.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) && !key.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE)) { - String value = attributes[i].getValue(); - capability.setAttribute(new SimpleAttributeType<>(key, String.class), value); - } - } - Directive[] directives = clause.getDirectives(); - for (int i = 0; directives != null && i < directives.length; i++) { - String key = directives[i].getName(); - String value = directives[i].getValue(); - capability.setDirective(key, value); - } - return capability; - } - - private void doImportPackages(Resource resource, Headers headers) throws IOException { - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.IMPORT_PACKAGE)); - for (int i = 0; clauses != null && i < clauses.length; i++) { - Requirement requirement = metadataFactory.createRequirement(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); - - createImportFilter(requirement, NsOsgiPackage.ATTRIBUTE__NAME, clauses[i]); - requirement.setDirective("text", "Import package " + clauses[i]); // TODO constant - if (Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))) { - requirement.setDirective("optional", Boolean.toString(true)); // TODO constant - } - resource.addRequirement(requirement); - } - } - - private void createImportFilter(Requirement requirement, AttributeType name, Clause clause) { - requirement.addAttribute(name, clause.getName()); - appendVersion(requirement, NsOsgiPackage.ATTRIBUTE__VERSION, getVersionRange(clause)); - Attribute[] attributes = clause.getAttributes(); - Set attrs = doImportPackageAttributes(requirement, attributes); - - // The next code is using the subset operator - // to check mandatory attributes, it seems to be - // impossible to rewrite. It must assert that whateber - // is in mandatory: must be in any of the attributes. - // This is a fundamental shortcoming of the filter language. - if (!attrs.isEmpty()) { - logger.warn("'mandatory:<*' part of OSGi import filter is not implemented for CRCE. Mandatory attributes: {}", attrs); - // TODO - is 'mandatory:<*' necessary for CRCE? -// String del = ""; -// filter.append("(mandatory:<*"); -// for (Iterator i = attrs.iterator(); i.hasNext();) -// { -// filter.append(del); -// filter.append(i.next()); -// del = ", "; -// } -// filter.append(")"); - } - } - - @SuppressWarnings("deprecation") - private Set doImportPackageAttributes(Requirement requirement, Attribute[] attributes) { - HashSet set = new HashSet<>(); - for (int i = 0; attributes != null && i < attributes.length; i++) { - String name = attributes[i].getName(); - String value = attributes[i].getValue(); - if (name.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || name.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE)) { - continue; - } else if (name.equalsIgnoreCase(Constants.RESOLUTION_DIRECTIVE + ":")) { - requirement.setDirective("optional", Boolean.toString(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(value))); // TODO constant - } - if (!name.endsWith(":")) { - requirement.setDirective(name, value); - set.add(name); - } - } - return set; - } - - private void doExecutionEnvironment(Resource resource, Headers headers) throws IOException { - @SuppressWarnings("deprecation") - Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); - if (clauses != null && clauses.length > 0) { - Requirement req = metadataFactory.createRequirement(NsOsgiExecutionEnvironment.NAMESPACE__OSGI_EXECUTION_ENVIRONMENT); - req.setDirective("operation", "or"); // TODO constant - - StringBuilder sb = new StringBuilder(); - sb.append("(|"); - for (Clause clause : clauses) { - req.addAttribute(NsOsgiExecutionEnvironment.ATTRIBUTE__EXECUTION_ENVIRONMENT, clause.getName()); - sb.append("("); - sb.append(NsOsgiExecutionEnvironment.ATTRIBUTE__EXECUTION_ENVIRONMENT.getName()); - sb.append("="); - sb.append(clause.getName()); - sb.append(")"); - } - sb.append(")"); - - req.setDirective("text", "Execution Environment " + sb.toString()); - resource.addRequirement(req); - } - } - - @SuppressWarnings("deprecation") - private static String getVersion(Clause clause) { - String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); - if (v == null) { - v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); - } - if (v == null) { - v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); - } - return VersionCleaner.clean(v); - } - - @SuppressWarnings("deprecation") - private VersionRange getVersionRange(Clause clause) { - String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); - if (v == null) { - v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); - } - if (v == null) { - v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); - } - return VersionRange.parseVersionRange(v); - } - - private static String getSymbolicName(Headers headers) throws IOException { - String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); - if (bsn == null) { - bsn = headers.getHeader(Constants.BUNDLE_NAME); - if (bsn == null) { - bsn = "Untitled-" + headers.hashCode(); - } - } - Clause[] clauses = Parser.parseHeader(bsn); - return clauses[0].getName(); - } - - private static String getVersion(Headers headers) throws IOException { - String v = headers.getHeader(Constants.BUNDLE_VERSION); - return VersionCleaner.clean(v); - } - - private static String getManifestVersion(Headers headers) throws IOException { - String v = headers.getHeader(Constants.BUNDLE_MANIFESTVERSION); - if (v == null) { - v = "1"; - } - return v; - } - - private static void appendVersion(Requirement requirement, AttributeType type, VersionRange version) { - if (version != null) { - if (!version.isOpenFloor()) { - if (!Version.emptyVersion.equals(new Version(version.getFloor().toString()))) { - requirement.addAttribute(type, new Version(version.getFloor().toString()), Operator.GREATER_EQUAL); - } - } else { - requirement.addAttribute(type, new Version(version.getFloor().toString()), Operator.GREATER); - } - - if (!VersionRange.INFINITE_VERSION.equals(version.getCeiling())) { - if (!version.isOpenCeiling()) { - requirement.addAttribute(type, new Version(version.getCeiling().toString()), Operator.LESS_EQUAL); - } else { - requirement.addAttribute(type, new Version(version.getCeiling().toString()), Operator.LESS); - } - } - } - } - - private interface Headers { - - String getHeader(String name) throws IOException; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *//* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiFragment; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiExecutionEnvironment; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiService; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipInputStream; + +import org.apache.felix.utils.manifest.Attribute; +import org.apache.felix.utils.manifest.Clause; +import org.apache.felix.utils.manifest.Directive; +import org.apache.felix.utils.manifest.Parser; +import org.apache.felix.utils.version.VersionCleaner; +import org.apache.felix.utils.version.VersionRange; + +import org.osgi.framework.Constants; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * This is original class DataModelHelperImpl adopted from org.apache.felix.bundlerepository. + * + */ +public class OsgiManifestBundleIndexer extends AbstractResourceIndexer { + + private static final Logger logger = LoggerFactory.getLogger(OsgiManifestBundleIndexer.class); + + public static final String MIME__APPLICATION_OSGI_BUNDLE = "application/vnd.osgi.bundle"; + public static final String BUNDLE_LICENSE = "Bundle-License"; + public static final String BUNDLE_SOURCE = "Bundle-Source"; + + private volatile MetadataFactory metadataFactory; + private volatile MetadataService metadataService; + + @Override + @SuppressWarnings("unchecked") + public List index(final InputStream input, Resource resource) { + + try { + URLStreamHandler handler = new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL u) throws IOException { + return new URLConnection(null) { + @Override + public void connect() throws IOException { + } + + @Override + public InputStream getInputStream() throws IOException { + return input; + } + }; + + } + }; + fillResource(new URL("none", "none", 0, "none", handler), resource); + // fres = repositoryAdmin.getHelper().createResource(new URL("none", "none", 0, "none", handler)); + } catch (MalformedURLException e) { + throw new IllegalStateException("Unexpected MalformedURLException", e); + } catch (ZipException e) { + logger.warn("Zip file is corrupted: {}", resource.getId(), e); + metadataService.addCategory(resource, "corrupted"); + return Collections.singletonList("corrupted"); + } catch (IOException ex) { + logger.error("I/O error on indexing resource: {}", resource.getId(), ex); + return Collections.emptyList(); + } catch (IllegalArgumentException e) { + // not a bundle + return Collections.emptyList(); + } + + Capability osgiIdentity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + + if (osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME) == null) { + return Collections.emptyList(); + } + + cz.zcu.kiv.crce.metadata.Attribute pn = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__PRESENTATION_NAME); + if (pn != null) { + metadataService.setPresentationName(resource, pn.getValue()); + } + cz.zcu.kiv.crce.metadata.Attribute sn = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME); + if(sn != null) { + metadataService.setExternalId(resource, sn.getValue()); + } + + cz.zcu.kiv.crce.metadata.Attribute ver = osgiIdentity.getAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION); + if(ver != null) { + Capability identity = metadataService.getIdentity(resource); + identity.setAttribute(NsCrceIdentity.ATTRIBUTE__VERSION, ver.getValue()); + } + + metadataService.addCategory(resource, "osgi"); + + metadataService.getIdentity(resource).setAttribute("mime", String.class, MIME__APPLICATION_OSGI_BUNDLE); // TODO hardcoded + + return Collections.singletonList("osgi"); + } + + @Override + public List getProvidedCategories() { + List result = new ArrayList<>(); + Collections.addAll(result, "osgi", "corrupted"); + return result; + } + + public Resource fillResource(final URL bundleUrl, Resource resource) throws IOException { + fillResource(new Headers() { + private final Manifest manifest; + private Properties localization; + + { + // Do not use a JarInputStream so that we can read the manifest even if it's not + // the first entry in the JAR. + byte[] man = loadEntry(JarFile.MANIFEST_NAME); + if (man == null) { + throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + bundleUrl); + } + manifest = new Manifest(new ByteArrayInputStream(man)); + } + + @Override + public String getHeader(String name) throws IOException { + String value = manifest.getMainAttributes().getValue(name); + if (value != null && value.startsWith("%")) { + if (localization == null) { + localization = new Properties(); + String path = manifest.getMainAttributes().getValue(Constants.BUNDLE_LOCALIZATION); + if (path == null) { + path = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; + } + path += ".properties"; + byte[] loc = loadEntry(path); + if (loc != null) { + localization.load(new ByteArrayInputStream(loc)); + } + } + value = value.substring(1); + value = localization.getProperty(value, value); + } + return value; + } + + private byte[] loadEntry(String name) throws IOException { + try (InputStream is = FileUtil.openURL(bundleUrl); ZipInputStream jis = new ZipInputStream(is)) { + for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry()) { + if (name.equalsIgnoreCase(e.getName())) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int n; + while ((n = jis.read(buf, 0, buf.length)) > 0) { + baos.write(buf, 0, n); + } + return baos.toByteArray(); + } + } + } + return null; + } + }, resource); +// if (resource != null) +// { +// if ("file".equals(bundleUrl.getProtocol())) +// { +// try { +// File f = new File(bundleUrl.toURI()); +// metadataService.setSize(resource, f.length()); +// } catch (URISyntaxException e) { +// throw new RuntimeException(e); +// } +// } +// try { +// metadataService.setUri(resource, bundleUrl.toURI()); +// // resource.put(Resource.URI, bundleUrl.toExternalForm(), null); +// } catch (URISyntaxException e) { +// throw new RuntimeException(e); +// } +// } + return resource; + } + + private Resource fillResource(Headers headers, Resource resource) throws IOException { + String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); + if (bsn == null) { + return null; + } + populate(headers, resource); + return resource; + } + + private void populate(Headers headers, Resource resource) throws IOException { + String bsn = getSymbolicName(headers); + String v = getVersion(headers); + Capability identity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, bsn + "-" + v); + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, bsn); + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, new Version(v)); + if (headers.getHeader(Constants.BUNDLE_NAME) != null) { + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); + } + if (headers.getHeader(Constants.BUNDLE_DESCRIPTION) != null) { + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__DESCRIPTION, headers.getHeader(Constants.BUNDLE_DESCRIPTION)); + } + if (headers.getHeader(BUNDLE_LICENSE) != null) { + String[] licenses = headers.getHeader(BUNDLE_LICENSE).split("[,\\s]+"); + for (String license : licenses) { + List licenseAttributes = identity.getAttributeValue(NsOsgiIdentity.ATTRIBUTE__LICENSES); + if (licenseAttributes == null) { + licenseAttributes = new ArrayList<>(licenses.length); + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__LICENSES, licenseAttributes); + } + licenseAttributes.add(license); + } + } + if (headers.getHeader(Constants.BUNDLE_COPYRIGHT) != null) { + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__COPYRIGHT, headers.getHeader(Constants.BUNDLE_COPYRIGHT)); + } + if (headers.getHeader(Constants.BUNDLE_DOCURL) != null) { + try { + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__DOCUMENTATION_URI, new URI(headers.getHeader(Constants.BUNDLE_DOCURL))); + } catch (URISyntaxException e) { + logger.error("Invalid documentation URI of OSGi resource: {}", headers.getHeader(Constants.BUNDLE_DOCURL), e); + } + } + if (headers.getHeader(BUNDLE_SOURCE) != null) { + try { + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__SOURCE_URI, new URI(headers.getHeader(BUNDLE_SOURCE))); + } catch (URISyntaxException e) { + logger.error("Invalid sources URI of OSGi resource: {}", headers.getHeader(BUNDLE_SOURCE), e); + } + } + + doCategories(resource, headers); + + doBundle(resource, headers); + + doExportServices(resource, null, headers); + doExportPackages(resource, null, headers); + doImportPackages(resource, headers); + doImportServices(resource, headers); + doRequireBundles(resource, headers); + doFragmentsHosts(resource, null, headers); + doExecutionEnvironment(resource, headers); + } + + private void doCategories(Resource resource, Headers headers) throws IOException { + Capability identity = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_CATEGORY)); + for (Clause clause : clauses) { + List categories = identity.getAttributeValue(NsOsgiIdentity.ATTRIBUTE__CATEGORY); + if (categories == null) { + categories = new ArrayList<>(clauses.length); + identity.setAttribute(NsOsgiIdentity.ATTRIBUTE__CATEGORY, categories); + } + categories.add(clause.getName()); + } + } + + private void doImportServices(Resource resource, Headers headers) throws IOException { + @SuppressWarnings("deprecation") + Clause[] imports = Parser.parseHeader(headers.getHeader(Constants.IMPORT_SERVICE)); + for (int i = 0; imports != null && i < imports.length; i++) { +// RequirementImpl ri = new RequirementImpl(Capability.SERVICE); + Requirement ri = metadataFactory.createRequirement(NsOsgiService.NAMESPACE__OSGI_SERVICE); + createServiceFilter(ri, imports[i]); + ri.setDirective("text", "Import Service " + imports[i].getName()); // TODO constant + + String avail = imports[i].getDirective("availability"); + String mult = imports[i].getDirective("multiple"); + ri.setDirective("optional", Boolean.toString("optional".equalsIgnoreCase(avail))); // TODO constant + ri.setDirective("multiple", Boolean.toString(!"false".equalsIgnoreCase(mult))); // TODO constant + resource.addRequirement(ri); + } + } + + private void doExportServices(Resource resource, Capability root, Headers headers) throws IOException { + @SuppressWarnings("deprecation") + Clause[] exports = Parser.parseHeader(headers.getHeader(Constants.EXPORT_SERVICE)); + if (exports != null) { + for (Clause export : exports) { + Capability cap = createServiceCapability(export); + resource.addCapability(cap); + if (root != null) { + root.addChild(cap); + } else { + resource.addRootCapability(cap); + } + } + } + } + + private void createServiceFilter(Requirement ri, Clause clause) { + String f = clause.getAttribute("filter"); + ri.addAttribute(NsOsgiService.ATTRIBUTE__NAME, clause.getName()); + + if (f != null) { + ri.setDirective("filter", f); // TODO constant + } + } + + private Capability createServiceCapability(Clause clause) { + Capability capability = metadataFactory.createCapability(NsOsgiService.NAMESPACE__OSGI_SERVICE); + capability.setAttribute(NsOsgiService.ATTRIBUTE__NAME, clause.getName()); + Attribute[] attributes = clause.getAttributes(); + if (attributes != null) { + for (Attribute attribute : attributes) { + capability.setAttribute(new SimpleAttributeType<>(attribute.getName(), String.class), attribute.getValue()); + } + } + return capability; + } + + private void doFragmentsHosts(Resource resource, Capability root, Headers headers) throws IOException { + // Check if we are a fragment + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.FRAGMENT_HOST)); + if (clauses != null && clauses.length == 1) { + // We are a fragment, create a requirement + // to our host. + Requirement r = metadataFactory.createRequirement(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); + r.addAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, clauses[0].getName()); + appendVersion(r, NsOsgiBundle.ATTRIBUTE__VERSION, VersionRange.parseVersionRange(clauses[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE))); + r.setDirective("text", "Required Host " + clauses[0].getName()); // TODO constant + r.setDirective("extend", "true"); // TODO constant + r.setDirective("optional", "false"); // TODO constant + r.setDirective("multiple", "false"); // TODO constant + resource.addRequirement(r); + + // And insert a capability that we are available + // as a fragment. ### Do we need that with extend? + Capability capability = metadataFactory.createCapability(NsOsgiFragment.NAMESPACE__OSGI_FRAGMENT); + capability.setAttribute(NsOsgiFragment.ATTRIBUTE__HOST, clauses[0].getName()); + capability.setAttribute(NsOsgiFragment.ATTRIBUTE__VERSION, new Version(getVersion(clauses[0]))); + resource.addCapability(capability); + if (root != null) { + root.addChild(capability); + } else { + resource.addRootCapability(capability); + } + + } + } + + private void doRequireBundles(Resource resource, Headers headers) throws IOException { + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.REQUIRE_BUNDLE)); + for (int i = 0; clauses != null && i < clauses.length; i++) { + Requirement r = metadataFactory.createRequirement(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); + + VersionRange v = VersionRange.parseVersionRange(clauses[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)); + + r.addAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, clauses[i].getName()); + + appendVersion(r, NsOsgiBundle.ATTRIBUTE__VERSION, v); + + r.setDirective("text", "Require Bundle " + clauses[i].getName() + "; " + v); // TODO constant + r.setDirective("optional", Boolean.toString( // TODO constant + Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE)))); + resource.addRequirement(r); + } + } + + private Capability doBundle(Resource resource, Headers headers) throws IOException { + Capability capability = metadataFactory.createCapability(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); + capability.setAttribute(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME, getSymbolicName(headers)); + if (headers.getHeader(Constants.BUNDLE_NAME) != null) { + capability.setAttribute(NsOsgiBundle.ATTRIBUTE__PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); + } + capability.setAttribute(NsOsgiBundle.ATTRIBUTE__VERSION, new Version(getVersion(headers))); + capability.setAttribute(NsOsgiBundle.ATTRIBUTE__MANIFEST_VERSION, getManifestVersion(headers)); + resource.addCapability(capability); + resource.addRootCapability(capability); + return capability; + } + + private void doExportPackages(Resource resource, Capability root, Headers headers) throws IOException { + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.EXPORT_PACKAGE)); + if (clauses != null) { + for (Clause clause : clauses) { + Capability capability = createCapability(clause); // Capability.PACKAGE, + resource.addCapability(capability); + if (root != null) { + root.addChild(capability); + } else { + resource.addRootCapability(capability); + } + } + } + } + + @SuppressWarnings("deprecation") + private Capability createCapability(Clause clause) { + Capability capability = metadataFactory.createCapability(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); + capability.setAttribute(NsOsgiPackage.ATTRIBUTE__NAME, clause.getName()); + capability.setAttribute(NsOsgiPackage.ATTRIBUTE__VERSION, new Version(getVersion(clause))); + Attribute[] attributes = clause.getAttributes(); + for (int i = 0; attributes != null && i < attributes.length; i++) { + String key = attributes[i].getName(); + if (!key.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) && !key.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE)) { + String value = attributes[i].getValue(); + capability.setAttribute(new SimpleAttributeType<>(key, String.class), value); + } + } + Directive[] directives = clause.getDirectives(); + for (int i = 0; directives != null && i < directives.length; i++) { + String key = directives[i].getName(); + String value = directives[i].getValue(); + capability.setDirective(key, value); + } + return capability; + } + + private void doImportPackages(Resource resource, Headers headers) throws IOException { + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.IMPORT_PACKAGE)); + for (int i = 0; clauses != null && i < clauses.length; i++) { + Requirement requirement = metadataFactory.createRequirement(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); + + createImportFilter(requirement, NsOsgiPackage.ATTRIBUTE__NAME, clauses[i]); + requirement.setDirective("text", "Import package " + clauses[i]); // TODO constant + if (Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))) { + requirement.setDirective("optional", Boolean.toString(true)); // TODO constant + } + resource.addRequirement(requirement); + } + } + + private void createImportFilter(Requirement requirement, AttributeType name, Clause clause) { + requirement.addAttribute(name, clause.getName()); + appendVersion(requirement, NsOsgiPackage.ATTRIBUTE__VERSION, getVersionRange(clause)); + Attribute[] attributes = clause.getAttributes(); + Set attrs = doImportPackageAttributes(requirement, attributes); + + // The next code is using the subset operator + // to check mandatory attributes, it seems to be + // impossible to rewrite. It must assert that whateber + // is in mandatory: must be in any of the attributes. + // This is a fundamental shortcoming of the filter language. + if (!attrs.isEmpty()) { + logger.warn("'mandatory:<*' part of OSGi import filter is not implemented for CRCE. Mandatory attributes: {}", attrs); + // TODO - is 'mandatory:<*' necessary for CRCE? +// String del = ""; +// filter.append("(mandatory:<*"); +// for (Iterator i = attrs.iterator(); i.hasNext();) +// { +// filter.append(del); +// filter.append(i.next()); +// del = ", "; +// } +// filter.append(")"); + } + } + + @SuppressWarnings("deprecation") + private Set doImportPackageAttributes(Requirement requirement, Attribute[] attributes) { + HashSet set = new HashSet<>(); + for (int i = 0; attributes != null && i < attributes.length; i++) { + String name = attributes[i].getName(); + String value = attributes[i].getValue(); + if (name.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || name.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE)) { + continue; + } else if (name.equalsIgnoreCase(Constants.RESOLUTION_DIRECTIVE + ":")) { + requirement.setDirective("optional", Boolean.toString(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(value))); // TODO constant + } + if (!name.endsWith(":")) { + requirement.setDirective(name, value); + set.add(name); + } + } + return set; + } + + private void doExecutionEnvironment(Resource resource, Headers headers) throws IOException { + @SuppressWarnings("deprecation") + Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); + if (clauses != null && clauses.length > 0) { + Requirement req = metadataFactory.createRequirement(NsOsgiExecutionEnvironment.NAMESPACE__OSGI_EXECUTION_ENVIRONMENT); + req.setDirective("operation", "or"); // TODO constant + + StringBuilder sb = new StringBuilder(); + sb.append("(|"); + for (Clause clause : clauses) { + req.addAttribute(NsOsgiExecutionEnvironment.ATTRIBUTE__EXECUTION_ENVIRONMENT, clause.getName()); + sb.append("("); + sb.append(NsOsgiExecutionEnvironment.ATTRIBUTE__EXECUTION_ENVIRONMENT.getName()); + sb.append("="); + sb.append(clause.getName()); + sb.append(")"); + } + sb.append(")"); + + req.setDirective("text", "Execution Environment " + sb.toString()); + resource.addRequirement(req); + } + } + + @SuppressWarnings("deprecation") + private static String getVersion(Clause clause) { + String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); + if (v == null) { + v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); + } + if (v == null) { + v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); + } + return VersionCleaner.clean(v); + } + + @SuppressWarnings("deprecation") + private VersionRange getVersionRange(Clause clause) { + String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); + if (v == null) { + v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); + } + if (v == null) { + v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); + } + return VersionRange.parseVersionRange(v); + } + + private static String getSymbolicName(Headers headers) throws IOException { + String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); + if (bsn == null) { + bsn = headers.getHeader(Constants.BUNDLE_NAME); + if (bsn == null) { + bsn = "Untitled-" + headers.hashCode(); + } + } + Clause[] clauses = Parser.parseHeader(bsn); + return clauses[0].getName(); + } + + private static String getVersion(Headers headers) throws IOException { + String v = headers.getHeader(Constants.BUNDLE_VERSION); + return VersionCleaner.clean(v); + } + + private static String getManifestVersion(Headers headers) throws IOException { + String v = headers.getHeader(Constants.BUNDLE_MANIFESTVERSION); + if (v == null) { + v = "1"; + } + return v; + } + + private static void appendVersion(Requirement requirement, AttributeType type, VersionRange version) { + if (version != null) { + if (!version.isOpenFloor()) { + if (!Version.emptyVersion.equals(new Version(version.getFloor().toString()))) { + requirement.addAttribute(type, new Version(version.getFloor().toString()), Operator.GREATER_EQUAL); + } + } else { + requirement.addAttribute(type, new Version(version.getFloor().toString()), Operator.GREATER); + } + + if (!VersionRange.INFINITE_VERSION.equals(version.getCeiling())) { + if (!version.isOpenCeiling()) { + requirement.addAttribute(type, new Version(version.getCeiling().toString()), Operator.LESS_EQUAL); + } else { + requirement.addAttribute(type, new Version(version.getCeiling().toString()), Operator.LESS); + } + } + } + } + + private interface Headers { + + String getHeader(String name) throws IOException; + } + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiBundle.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiBundle.java index d80db29c..021a13f9 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiBundle.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiBundle.java @@ -1,24 +1,24 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiBundle { - - String NAMESPACE__OSGI_BUNDLE = "osgi.wiring.bundle"; - - AttributeType ATTRIBUTE__SYMBOLIC_NAME = new SimpleAttributeType<>("symbolic-name", String.class); - - AttributeType ATTRIBUTE__PRESENTATION_NAME = new SimpleAttributeType<>("presentation-name", String.class); - - AttributeType ATTRIBUTE__VERSION = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); - - AttributeType ATTRIBUTE__MANIFEST_VERSION = new SimpleAttributeType<>("manifest-version", String.class); - -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiBundle { + + String NAMESPACE__OSGI_BUNDLE = "osgi.wiring.bundle"; + + AttributeType ATTRIBUTE__SYMBOLIC_NAME = new SimpleAttributeType<>("symbolic-name", String.class); + + AttributeType ATTRIBUTE__PRESENTATION_NAME = new SimpleAttributeType<>("presentation-name", String.class); + + AttributeType ATTRIBUTE__VERSION = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); + + AttributeType ATTRIBUTE__MANIFEST_VERSION = new SimpleAttributeType<>("manifest-version", String.class); + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiExecutionEnvironment.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiExecutionEnvironment.java index c3c4690e..372c605e 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiExecutionEnvironment.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiExecutionEnvironment.java @@ -1,17 +1,17 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiExecutionEnvironment { - - String NAMESPACE__OSGI_EXECUTION_ENVIRONMENT = "osgi.ee"; - - AttributeType ATTRIBUTE__EXECUTION_ENVIRONMENT = - new SimpleAttributeType<>("ee", String.class); - -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiExecutionEnvironment { + + String NAMESPACE__OSGI_EXECUTION_ENVIRONMENT = "osgi.ee"; + + AttributeType ATTRIBUTE__EXECUTION_ENVIRONMENT = + new SimpleAttributeType<>("ee", String.class); + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiFragment.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiFragment.java index d6c4a3ba..10d499af 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiFragment.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiFragment.java @@ -1,21 +1,21 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import cz.zcu.kiv.crce.metadata.type.Version; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiFragment { - - String NAMESPACE__OSGI_FRAGMENT = "osgi.fragment"; - - AttributeType ATTRIBUTE__HOST = - new SimpleAttributeType<>("host", String.class); - - AttributeType ATTRIBUTE__VERSION = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import cz.zcu.kiv.crce.metadata.type.Version; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiFragment { + + String NAMESPACE__OSGI_FRAGMENT = "osgi.fragment"; + + AttributeType ATTRIBUTE__HOST = + new SimpleAttributeType<>("host", String.class); + + AttributeType ATTRIBUTE__VERSION = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiIdentity.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiIdentity.java index 0216839d..3fea62a2 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiIdentity.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiIdentity.java @@ -1,54 +1,54 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import java.net.URI; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiIdentity { - String NAMESPACE__OSGI_IDENTITY = "osgi.identity"; - - AttributeType ATTRIBUTE__NAME = - new SimpleAttributeType<>("name", String.class); - - AttributeType ATTRIBUTE__SYMBOLIC_NAME = - new SimpleAttributeType<>("symbolic-name", String.class); - - AttributeType ATTRIBUTE__VERSION = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); - - AttributeType ATTRIBUTE__PRESENTATION_NAME = - new SimpleAttributeType<>("presentation-name", String.class); - - AttributeType ATTRIBUTE__DESCRIPTION = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.DESCRIPTION, String.class); - - /** - * @deprecated The attribute is no more used, use {@link NsOsgiIdentity#ATTRIBUTE__LICENSES} instead. - */ - @Deprecated - AttributeType ATTRIBUTE__LICENSE_URI = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.LICENSE_URI, URI.class); - - AttributeType> ATTRIBUTE__LICENSES = - new ListAttributeType("licenses"); - - AttributeType ATTRIBUTE__COPYRIGHT = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.COPYRIGHT, String.class); - - AttributeType ATTRIBUTE__DOCUMENTATION_URI = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.DOCUMENTATION_URI, URI.class); - - AttributeType ATTRIBUTE__SOURCE_URI = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.SOURCE_URI, URI.class); - - AttributeType> ATTRIBUTE__CATEGORY = - new ListAttributeType(org.apache.felix.bundlerepository.Resource.CATEGORY); -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import java.net.URI; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.ListAttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiIdentity { + String NAMESPACE__OSGI_IDENTITY = "osgi.identity"; + + AttributeType ATTRIBUTE__NAME = + new SimpleAttributeType<>("name", String.class); + + AttributeType ATTRIBUTE__SYMBOLIC_NAME = + new SimpleAttributeType<>("symbolic-name", String.class); + + AttributeType ATTRIBUTE__VERSION = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); + + AttributeType ATTRIBUTE__PRESENTATION_NAME = + new SimpleAttributeType<>("presentation-name", String.class); + + AttributeType ATTRIBUTE__DESCRIPTION = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.DESCRIPTION, String.class); + + /** + * @deprecated The attribute is no more used, use {@link NsOsgiIdentity#ATTRIBUTE__LICENSES} instead. + */ + @Deprecated + AttributeType ATTRIBUTE__LICENSE_URI = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.LICENSE_URI, URI.class); + + AttributeType> ATTRIBUTE__LICENSES = + new ListAttributeType("licenses"); + + AttributeType ATTRIBUTE__COPYRIGHT = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.COPYRIGHT, String.class); + + AttributeType ATTRIBUTE__DOCUMENTATION_URI = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.DOCUMENTATION_URI, URI.class); + + AttributeType ATTRIBUTE__SOURCE_URI = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.SOURCE_URI, URI.class); + + AttributeType> ATTRIBUTE__CATEGORY = + new ListAttributeType(org.apache.felix.bundlerepository.Resource.CATEGORY); +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiPackage.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiPackage.java index 2c6a2c58..816d221e 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiPackage.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiPackage.java @@ -1,20 +1,20 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiPackage { - - String NAMESPACE__OSGI_PACKAGE = "osgi.wiring.package"; - - AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); - - AttributeType ATTRIBUTE__VERSION = - new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); - -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiPackage { + + String NAMESPACE__OSGI_PACKAGE = "osgi.wiring.package"; + + AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); + + AttributeType ATTRIBUTE__VERSION = + new SimpleAttributeType<>(org.apache.felix.bundlerepository.Resource.VERSION, Version.class); + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiService.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiService.java index 1edad60d..45b4aa2a 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiService.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/namespace/NsOsgiService.java @@ -1,16 +1,16 @@ -package cz.zcu.kiv.crce.metadata.osgi.namespace; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface NsOsgiService { - - String NAMESPACE__OSGI_SERVICE = "osgi.wiring.service"; - - AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); - -} +package cz.zcu.kiv.crce.metadata.osgi.namespace; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface NsOsgiService { + + String NAMESPACE__OSGI_SERVICE = "osgi.wiring.service"; + + AttributeType ATTRIBUTE__NAME = new SimpleAttributeType<>("name", String.class); + +} diff --git a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/util/FilterParser.java b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/util/FilterParser.java index b6382f55..4e3d5739 100644 --- a/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/util/FilterParser.java +++ b/modules/crce-metadata-osgi-bundle/src/main/java/cz/zcu/kiv/crce/metadata/osgi/util/FilterParser.java @@ -1,16 +1,16 @@ -package cz.zcu.kiv.crce.metadata.osgi.util; - -import javax.annotation.Nonnull; - -import org.osgi.framework.InvalidSyntaxException; -import cz.zcu.kiv.crce.metadata.Requirement; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface FilterParser { - - @Nonnull - Requirement parse(@Nonnull String filter, @Nonnull String namespace) throws InvalidSyntaxException; -} +package cz.zcu.kiv.crce.metadata.osgi.util; + +import javax.annotation.Nonnull; + +import org.osgi.framework.InvalidSyntaxException; +import cz.zcu.kiv.crce.metadata.Requirement; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface FilterParser { + + @Nonnull + Requirement parse(@Nonnull String filter, @Nonnull String namespace) throws InvalidSyntaxException; +} diff --git a/modules/crce-metadata-osgi-bundle/src/test/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserTest.java b/modules/crce-metadata-osgi-bundle/src/test/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserTest.java index a68f8ddf..ebdaf998 100644 --- a/modules/crce-metadata-osgi-bundle/src/test/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserTest.java +++ b/modules/crce-metadata-osgi-bundle/src/test/java/cz/zcu/kiv/crce/metadata/osgi/internal/FilterParserTest.java @@ -1,448 +1,448 @@ -package cz.zcu.kiv.crce.metadata.osgi.internal; - -import static org.junit.Assert.*; - -import java.lang.reflect.Field; -import java.util.List; -import org.osgi.framework.InvalidSyntaxException; -import cz.zcu.kiv.crce.metadata.type.Version; - -import org.junit.BeforeClass; -import org.junit.Test; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; -import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class FilterParserTest { - - private static MetadataFactory metadataFactory; - private static FilterParser filterParser; - - @BeforeClass - public static void beforeClass() throws NoSuchFieldException, IllegalAccessException { - metadataFactory = new MetadataFactoryImpl(); - filterParser = new FilterParserImpl(); - Field field = FilterParserImpl.class.getDeclaredField("metadataFactory"); - field.setAccessible(true); - field.set(filterParser, metadataFactory); - } - - @Test - public void testEmptyFilter() throws InvalidSyntaxException { - String filter = ""; - String namespace = "empty"; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - assertTrue(requirement.getAttributes().isEmpty()); - } - - @Test - public void testSingleGenericExpression() throws InvalidSyntaxException { - String filter = "(a=b)"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(1, requirement.getAttributes().size()); - - SimpleAttributeType type = new SimpleAttributeType<>("a", String.class); - - List> attributes = requirement.getAttributes(type); - assertEquals(1, attributes.size()); - - Attribute attribute = attributes.get(0); - - assertEquals(type, attribute.getAttributeType()); - assertEquals(Operator.EQUAL, attribute.getOperator()); - assertEquals("b", attribute.getValue()); - assertEquals("b", attribute.getStringValue()); - } - - @Test - public void testSinglePackageExpression() throws InvalidSyntaxException { - String filter = "(package=cz.zcu.kiv.crce)"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(1, requirement.getAttributes().size()); - - List> attributes = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, attributes.size()); - - Attribute attribute = attributes.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, attribute.getAttributeType()); - assertEquals(Operator.EQUAL, attribute.getOperator()); - assertEquals("cz.zcu.kiv.crce", attribute.getValue()); - assertEquals("cz.zcu.kiv.crce", attribute.getStringValue()); - } - - @Test - public void testPackageAndVersionConjunction() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(version=1.0.0))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(2, requirement.getAttributes().size()); - - // package (name) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // version - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(1, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.EQUAL, version.getOperator()); - assertEquals(new Version("1.0.0"), version.getValue()); - assertEquals("1.0.0", version.getStringValue()); - } - - @Test - public void testPackageAndTwoVersionsConjunction() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(version>=1.0.0)(version<2.0.0))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(3, requirement.getAttributes().size()); - - // package (name) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // versions - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(2, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.GREATER_EQUAL, version.getOperator()); - assertEquals(new Version("1.0.0"), version.getValue()); - assertEquals("1.0.0", version.getStringValue()); - - version = versions.get(1); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.LESS, version.getOperator()); - assertEquals(new Version("2.0.0"), version.getValue()); - assertEquals("2.0.0", version.getStringValue()); - } - - @Test - public void testPackageAndTwoVersionsDisjunction() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(|(version=1.4.0)(version=1.6.0)))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(1, requirement.getAttributes().size()); - - // package (name) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // versions - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertTrue(versions.isEmpty()); - - assertEquals(1, requirement.getChildren().size()); - - Requirement parent = requirement; - requirement = parent.getChildren().get(0); - - assertEquals("or", requirement.getDirectives().get("operator")); - - versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(2, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.EQUAL, version.getOperator()); - assertEquals(new Version("1.4.0"), version.getValue()); - assertEquals("1.4.0", version.getStringValue()); - - version = versions.get(1); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.EQUAL, version.getOperator()); - assertEquals(new Version("1.6.0"), version.getValue()); - assertEquals("1.6.0", version.getStringValue()); - } - - @Test - public void testNestedRequirement() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(|(&(version>=1.0.0)(version<1.5.0))(&(version>=1.6.0)(version<2.0.0))))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertFalse(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(1, requirement.getAttributes().size()); - - assertEquals(1, requirement.getChildren().size()); - - // package (name) - (package=cz.zcu.kiv.crce) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // versions - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertTrue(versions.isEmpty()); - - - // --- 1. level nested requirement --- - (|(&(version>=1.0.0)(version<1.5.0))(&(version>=1.6.0)(version<2.0.0))) - - Requirement parent = requirement; - requirement = parent.getChildren().get(0); - - assertEquals(namespace, requirement.getNamespace()); - - assertTrue(requirement.getAttributes().isEmpty()); - assertEquals("or", requirement.getDirectives().get("operator")); - - assertEquals(2, requirement.getChildren().size()); - - // package (name) - - names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertTrue(names.isEmpty()); - - // versions - - versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertTrue(versions.isEmpty()); - - - // --- 2. level 1. nested requirement --- - (&(version>=1.0.0)(version<1.5.0)) - - parent = requirement; - requirement = parent.getChildren().get(0); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(2, requirement.getAttributes().size()); - - // package (name) - - names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertTrue(names.isEmpty()); - - // versions - - versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(2, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.GREATER_EQUAL, version.getOperator()); - assertEquals(new Version("1.0.0"), version.getValue()); - assertEquals("1.0.0", version.getStringValue()); - - version = versions.get(1); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.LESS, version.getOperator()); - assertEquals(new Version("1.5.0"), version.getValue()); - assertEquals("1.5.0", version.getStringValue()); - - - // --- 2. level 2. nested requirement --- - (&(version>=1.6.0)(version<2.0.0)) - - requirement = parent.getChildren().get(1); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(2, requirement.getAttributes().size()); - - // package (name) - - names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertTrue(names.isEmpty()); - - // versions - - versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(2, versions.size()); - - version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.GREATER_EQUAL, version.getOperator()); - assertEquals(new Version("1.6.0"), version.getValue()); - assertEquals("1.6.0", version.getStringValue()); - - version = versions.get(1); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.LESS, version.getOperator()); - assertEquals(new Version("2.0.0"), version.getValue()); - assertEquals("2.0.0", version.getStringValue()); - } - - @Test - public void testPackageAndVersionNegationConjunction() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(!(version=1.0.0)))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(2, requirement.getAttributes().size()); - - // package (name) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // version - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(1, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.NOT_EQUAL, version.getOperator()); - assertEquals(new Version("1.0.0"), version.getValue()); - assertEquals("1.0.0", version.getStringValue()); - } - - @Test - public void testPackageAndNegationStyleVersionRangeConjunction() throws InvalidSyntaxException { - String filter = "(&(package=cz.zcu.kiv.crce)(version>=1.3.0)(!(version>=2.0.0)))"; - String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; - - Requirement requirement = filterParser.parse(filter, namespace); - - assertEquals(namespace, requirement.getNamespace()); - assertTrue(requirement.getChildren().isEmpty()); - - assertFalse(requirement.getAttributes().isEmpty()); - assertEquals(3, requirement.getAttributes().size()); - - // package (name) - - List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); - assertEquals(1, names.size()); - - Attribute name = names.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); - assertEquals(Operator.EQUAL, name.getOperator()); - assertEquals("cz.zcu.kiv.crce", name.getValue()); - assertEquals("cz.zcu.kiv.crce", name.getStringValue()); - - // versions - - List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); - assertEquals(2, versions.size()); - - Attribute version = versions.get(0); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.GREATER_EQUAL, version.getOperator()); - assertEquals(new Version("1.3.0"), version.getValue()); - assertEquals("1.3.0", version.getStringValue()); - - version = versions.get(1); - - assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); - assertEquals(Operator.LESS, version.getOperator()); - assertEquals(new Version("2.0.0"), version.getValue()); - assertEquals("2.0.0", version.getStringValue()); - } -} +package cz.zcu.kiv.crce.metadata.osgi.internal; + +import static org.junit.Assert.*; + +import java.lang.reflect.Field; +import java.util.List; +import org.osgi.framework.InvalidSyntaxException; +import cz.zcu.kiv.crce.metadata.type.Version; + +import org.junit.BeforeClass; +import org.junit.Test; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; +import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class FilterParserTest { + + private static MetadataFactory metadataFactory; + private static FilterParser filterParser; + + @BeforeClass + public static void beforeClass() throws NoSuchFieldException, IllegalAccessException { + metadataFactory = new MetadataFactoryImpl(); + filterParser = new FilterParserImpl(); + Field field = FilterParserImpl.class.getDeclaredField("metadataFactory"); + field.setAccessible(true); + field.set(filterParser, metadataFactory); + } + + @Test + public void testEmptyFilter() throws InvalidSyntaxException { + String filter = ""; + String namespace = "empty"; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + assertTrue(requirement.getAttributes().isEmpty()); + } + + @Test + public void testSingleGenericExpression() throws InvalidSyntaxException { + String filter = "(a=b)"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(1, requirement.getAttributes().size()); + + SimpleAttributeType type = new SimpleAttributeType<>("a", String.class); + + List> attributes = requirement.getAttributes(type); + assertEquals(1, attributes.size()); + + Attribute attribute = attributes.get(0); + + assertEquals(type, attribute.getAttributeType()); + assertEquals(Operator.EQUAL, attribute.getOperator()); + assertEquals("b", attribute.getValue()); + assertEquals("b", attribute.getStringValue()); + } + + @Test + public void testSinglePackageExpression() throws InvalidSyntaxException { + String filter = "(package=cz.zcu.kiv.crce)"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(1, requirement.getAttributes().size()); + + List> attributes = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, attributes.size()); + + Attribute attribute = attributes.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, attribute.getAttributeType()); + assertEquals(Operator.EQUAL, attribute.getOperator()); + assertEquals("cz.zcu.kiv.crce", attribute.getValue()); + assertEquals("cz.zcu.kiv.crce", attribute.getStringValue()); + } + + @Test + public void testPackageAndVersionConjunction() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(version=1.0.0))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(2, requirement.getAttributes().size()); + + // package (name) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // version + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(1, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.EQUAL, version.getOperator()); + assertEquals(new Version("1.0.0"), version.getValue()); + assertEquals("1.0.0", version.getStringValue()); + } + + @Test + public void testPackageAndTwoVersionsConjunction() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(version>=1.0.0)(version<2.0.0))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(3, requirement.getAttributes().size()); + + // package (name) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // versions + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(2, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.GREATER_EQUAL, version.getOperator()); + assertEquals(new Version("1.0.0"), version.getValue()); + assertEquals("1.0.0", version.getStringValue()); + + version = versions.get(1); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.LESS, version.getOperator()); + assertEquals(new Version("2.0.0"), version.getValue()); + assertEquals("2.0.0", version.getStringValue()); + } + + @Test + public void testPackageAndTwoVersionsDisjunction() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(|(version=1.4.0)(version=1.6.0)))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(1, requirement.getAttributes().size()); + + // package (name) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // versions + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertTrue(versions.isEmpty()); + + assertEquals(1, requirement.getChildren().size()); + + Requirement parent = requirement; + requirement = parent.getChildren().get(0); + + assertEquals("or", requirement.getDirectives().get("operator")); + + versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(2, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.EQUAL, version.getOperator()); + assertEquals(new Version("1.4.0"), version.getValue()); + assertEquals("1.4.0", version.getStringValue()); + + version = versions.get(1); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.EQUAL, version.getOperator()); + assertEquals(new Version("1.6.0"), version.getValue()); + assertEquals("1.6.0", version.getStringValue()); + } + + @Test + public void testNestedRequirement() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(|(&(version>=1.0.0)(version<1.5.0))(&(version>=1.6.0)(version<2.0.0))))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertFalse(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(1, requirement.getAttributes().size()); + + assertEquals(1, requirement.getChildren().size()); + + // package (name) - (package=cz.zcu.kiv.crce) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // versions + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertTrue(versions.isEmpty()); + + + // --- 1. level nested requirement --- - (|(&(version>=1.0.0)(version<1.5.0))(&(version>=1.6.0)(version<2.0.0))) + + Requirement parent = requirement; + requirement = parent.getChildren().get(0); + + assertEquals(namespace, requirement.getNamespace()); + + assertTrue(requirement.getAttributes().isEmpty()); + assertEquals("or", requirement.getDirectives().get("operator")); + + assertEquals(2, requirement.getChildren().size()); + + // package (name) + + names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertTrue(names.isEmpty()); + + // versions + + versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertTrue(versions.isEmpty()); + + + // --- 2. level 1. nested requirement --- - (&(version>=1.0.0)(version<1.5.0)) + + parent = requirement; + requirement = parent.getChildren().get(0); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(2, requirement.getAttributes().size()); + + // package (name) + + names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertTrue(names.isEmpty()); + + // versions + + versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(2, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.GREATER_EQUAL, version.getOperator()); + assertEquals(new Version("1.0.0"), version.getValue()); + assertEquals("1.0.0", version.getStringValue()); + + version = versions.get(1); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.LESS, version.getOperator()); + assertEquals(new Version("1.5.0"), version.getValue()); + assertEquals("1.5.0", version.getStringValue()); + + + // --- 2. level 2. nested requirement --- - (&(version>=1.6.0)(version<2.0.0)) + + requirement = parent.getChildren().get(1); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(2, requirement.getAttributes().size()); + + // package (name) + + names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertTrue(names.isEmpty()); + + // versions + + versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(2, versions.size()); + + version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.GREATER_EQUAL, version.getOperator()); + assertEquals(new Version("1.6.0"), version.getValue()); + assertEquals("1.6.0", version.getStringValue()); + + version = versions.get(1); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.LESS, version.getOperator()); + assertEquals(new Version("2.0.0"), version.getValue()); + assertEquals("2.0.0", version.getStringValue()); + } + + @Test + public void testPackageAndVersionNegationConjunction() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(!(version=1.0.0)))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(2, requirement.getAttributes().size()); + + // package (name) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // version + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(1, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.NOT_EQUAL, version.getOperator()); + assertEquals(new Version("1.0.0"), version.getValue()); + assertEquals("1.0.0", version.getStringValue()); + } + + @Test + public void testPackageAndNegationStyleVersionRangeConjunction() throws InvalidSyntaxException { + String filter = "(&(package=cz.zcu.kiv.crce)(version>=1.3.0)(!(version>=2.0.0)))"; + String namespace = NsOsgiPackage.NAMESPACE__OSGI_PACKAGE; + + Requirement requirement = filterParser.parse(filter, namespace); + + assertEquals(namespace, requirement.getNamespace()); + assertTrue(requirement.getChildren().isEmpty()); + + assertFalse(requirement.getAttributes().isEmpty()); + assertEquals(3, requirement.getAttributes().size()); + + // package (name) + + List> names = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__NAME); + assertEquals(1, names.size()); + + Attribute name = names.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__NAME, name.getAttributeType()); + assertEquals(Operator.EQUAL, name.getOperator()); + assertEquals("cz.zcu.kiv.crce", name.getValue()); + assertEquals("cz.zcu.kiv.crce", name.getStringValue()); + + // versions + + List> versions = requirement.getAttributes(NsOsgiPackage.ATTRIBUTE__VERSION); + assertEquals(2, versions.size()); + + Attribute version = versions.get(0); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.GREATER_EQUAL, version.getOperator()); + assertEquals(new Version("1.3.0"), version.getValue()); + assertEquals("1.3.0", version.getStringValue()); + + version = versions.get(1); + + assertEquals(NsOsgiPackage.ATTRIBUTE__VERSION, version.getAttributeType()); + assertEquals(Operator.LESS, version.getOperator()); + assertEquals(new Version("2.0.0"), version.getValue()); + assertEquals("2.0.0", version.getStringValue()); + } +} diff --git a/modules/crce-mvn-plugin/osgi.bnd b/modules/crce-mvn-plugin/osgi.bnd new file mode 100644 index 00000000..9e645d88 --- /dev/null +++ b/modules/crce-mvn-plugin/osgi.bnd @@ -0,0 +1,28 @@ +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Import-Package:\ + !org.eclipse.sisu,\ + #!org.apache.http.*,\ + org.eclipse.persistence.internal.jaxb.many,\ + * + +Embed-Dependency:\ + #aether-api,\ + aether-util,\ + aether-impl, \ + maven-artifact,\ + maven-model,\ + maven-model-builder,\ + maven-builder-support,\ + maven-aether-provider,\ + maven-repository-metadata,\ + aether-transport-http + + + + + diff --git a/modules/crce-mvn-plugin/pom.xml b/modules/crce-mvn-plugin/pom.xml new file mode 100644 index 00000000..620d132d --- /dev/null +++ b/modules/crce-mvn-plugin/pom.xml @@ -0,0 +1,233 @@ + + + crce-modules-parent + cz.zcu.kiv.crce + 2.1.1-SNAPSHOT + ../pom/pom.xml + + 4.0.0 + + crce-mvn-plugin + bundle + + http://maven.apache.org + + + CRCE - maven plugin + + + UTF-8 + ${namespace}.mvn.plugin + ${namespace}.mvn.plugin + 1.1.0 + 3.3.9 + 1.0 + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + org.apache.felix + org.osgi.service.obr + + + com.google.inject + guice + 4.0 + + + cz.zcu.kiv.crce.wrapper + org.apache.httpcomponents.httpclient + 4.2.6 + + + cz.zcu.kiv.crce.wrapper + org.apache.httpcomponents.httpcore + 4.2.5 + + + + org.apache.felix + org.apache.felix.dependencymanager + + + + + + + + + + + + + ${project.groupId} + crce-core + pom + + + cz.zcu.kiv.crce + crce-plugin-api + 2.1.1-SNAPSHOT + + + cz.zcu.kiv.crce + crce-metadata-service-api + 3.0.1-SNAPSHOT + + + cz.zcu.kiv.crce + crce-repository-api + 2.2.0-SNAPSHOT + + + junit + junit + 4.11 + test + + + + + org.glassfish.jersey.core + jersey-client + + + + + org.glassfish.jersey.media + jersey-media-moxy + + + + + + org.eclipse.persistence + org.eclipse.persistence.moxy + 2.6.4 + + + + + org.apache.maven + maven-model + ${maven.version} + + + org.apache.maven + maven-artifact + ${maven.version} + + + org.apache.maven + maven-repository-metadata + ${maven.version} + + + org.apache.maven + maven-model-builder + ${maven.version} + + + org.apache.maven + maven-builder-support + ${maven.version} + + + org.apache.maven + maven-aether-provider + ${maven.version} + + + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-interpolation + 1.19 + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-component-annotations + 1.5.5 + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-utils + 3.0.17 + + + + + org.eclipse.aether + aether-spi + ${aether.version} + + + org.eclipse.aether + aether-api + ${aether.version} + + + org.eclipse.aether + aether-util + ${aether.version} + + + org.eclipse.aether + aether-impl + ${aether.version} + + + org.eclipse.aether + aether-connector-basic + ${aether.version} + + + org.eclipse.aether + aether-transport-file + ${aether.version} + + + org.eclipse.aether + aether-transport-http + ${aether.version} + provided + + + org.apache.httpcomponents + httpclient + 4.3.5 + + + org.apache.httpcomponents + httpcore + 4.3.2 + + + + + + + + + + + + + + + + diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Activator.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Activator.java new file mode 100644 index 00000000..b571a3f5 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Activator.java @@ -0,0 +1,29 @@ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.plugin.Plugin; +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +/** + * Activator class required by crce. + */ +public class Activator extends DependencyActivatorBase { + + @Override + public void init(BundleContext bundleContext, DependencyManager dependencyManager) throws Exception { + dependencyManager.add(createComponent() + .setInterface(Plugin.class.getName(), null) + .setImplementation(MavenPlugin.class) + .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceDAO.class)) + ); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { +// super.destroy(context, manager); + } +} \ No newline at end of file diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Base64Encoder.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Base64Encoder.java new file mode 100644 index 00000000..b5556d9c --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/Base64Encoder.java @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + +import java.io.*; + +/** + * This class is used by FileUtil. + */ +@SuppressWarnings("PMD") +public class Base64Encoder +{ + private static final byte encTab[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, + 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, + 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f }; + + @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") + public static String base64Encode(String s) throws IOException + { + return encode(s.getBytes(), 0); + } + + /** + * Encode a raw byte array to a Base64 String. + * + * @param in Byte array to encode. + * @param len Length of Base64 lines. 0 means no line breaks. + **/ + @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "Adopted 3rd party implementation.") + public static String encode(byte[] in, int len) throws IOException + { + ByteArrayOutputStream baos = null; + ByteArrayInputStream bais = null; + try + { + baos = new ByteArrayOutputStream(); + bais = new ByteArrayInputStream(in); + encode(bais, baos, len); + // ASCII byte array to String + return (new String(baos.toByteArray())); + } + finally + { + if (baos != null) + { + baos.close(); + } + if (bais != null) + { + bais.close(); + } + } + } + + @SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Adopted 3rd party implementation.") + public static void encode(InputStream in, OutputStream out, int len) + throws IOException + { + + // Check that length is a multiple of 4 bytes + if (len % 4 != 0) + { + throw new IllegalArgumentException("Length must be a multiple of 4"); + } + + // Read input stream until end of file + int bits = 0; + int nbits = 0; + int nbytes = 0; + int b; + + while ((b = in.read()) != -1) + { + bits = (bits << 8) | b; + nbits += 8; + while (nbits >= 6) + { + nbits -= 6; + out.write(encTab[0x3f & (bits >> nbits)]); + nbytes++; + // New line + if (len != 0 && nbytes >= len) + { + out.write(0x0d); + out.write(0x0a); + nbytes -= len; + } + } + } + + switch (nbits) + { + case 2: + out.write(encTab[0x3f & (bits << 4)]); + out.write(0x3d); // 0x3d = '=' + out.write(0x3d); + break; + case 4: + out.write(encTab[0x3f & (bits << 2)]); + out.write(0x3d); + break; + } + + if (len != 0) + { + if (nbytes != 0) + { + out.write(0x0d); + out.write(0x0a); + } + out.write(0x0d); + out.write(0x0a); + } + } +} \ No newline at end of file diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtil.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtil.java new file mode 100644 index 00000000..757b94de --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtil.java @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.util.Enumeration; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; + +/** + * This class is used instead of FileUtil from felix bundlerepository which somehow causes errors when running crce. + */ +@SuppressWarnings("PMD") +public class FileUtil +{ + + + /** + * Checks whether a file is present in existing jar archive. + * + * @param pathToJar Path to an existing jar archive. + * @param filename Full name of the file (without the initial '/') to be checked. + * @return True or false. + * + * @throws IOException + */ + public static boolean isFilePresentInJar(String pathToJar, String filename) throws IOException { + JarFile jar = new JarFile(pathToJar); + JarEntry entry = jar.getJarEntry(filename); + boolean res = entry != null; + jar.close(); + return res; + } + + /** + * This method adds a pom file to the root of existing jar archive. If there's already a pom in the archive, + * it will be overwritten. + * + * @param pathToJar Path to an existing jar archive. + * @param pomInputStrem Stream containing the pom.xml file. + * @throws IOException Thrown when bad stuff happens. + */ + public static void addPomToJar(String pathToJar, InputStream pomInputStrem) throws IOException { + // apparently this method shown here: http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html + // doesn't work at all, but the solution below works just fine + + // open jar file + FileOutputStream out = new FileOutputStream(pathToJar); + JarOutputStream jarOut = new JarOutputStream(out); + + // create new entry + JarEntry pomEntry = new JarEntry("pom.xml"); + jarOut.putNextEntry(pomEntry); + + // write pom file to archive + while(pomInputStrem.available() > 0) { + jarOut.write(pomInputStrem.read()); + } + jarOut.close(); + out.close(); + } + + /** + * Extracts the contents of jar file to the targetDir. If the targetDir doesn't exist + * it will be created. + * + * @param jarFileName Name of the jar file. + * @param targetDir Target directory. + */ + public static void unJar(String jarFileName, String targetDir) throws IOException, FileUtilOperationException { + JarFile jar = new JarFile(jarFileName); + Enumeration enumEntries = jar.entries(); + + // check the target dir + File target = new File(targetDir); + if(!target.exists()) { + // not really necessary at all, but findbugs made me + if(!target.mkdir()) { + throw new FileUtilOperationException("Failed to create target directory for extracting a jar archive."); + } + } + + while(enumEntries.hasMoreElements()) { + JarEntry entry = enumEntries.nextElement(); + File f = new File(targetDir + File.separator + entry.getName()); + if(entry.isDirectory()) { + if(!f.mkdir()) { + throw new FileUtilOperationException("Failed to create an extracted directory."); + } + continue; + } + + InputStream is = jar.getInputStream(entry); + try (OutputStream out = new FileOutputStream(f)) { + while(is.available() > 0) { + out.write(is.read()); + } + } + is.close(); + } + jar.close(); + } + + public static void copy( + InputStream is, File dir, String destName, String destDir, byte[] buffer) + throws IOException + { + if (destDir == null) + { + destDir = ""; + } + + // Make sure the target directory exists and + // that is actually a directory. + File targetDir = new File(dir, destDir); + if (!targetDir.exists()) + { + if (!targetDir.mkdirs()) + { + throw new IOException("Unable to create target directory: " + + targetDir); + } + } + else if (!targetDir.isDirectory()) + { + throw new IOException("Target is not a directory: " + + targetDir); + } + + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(new File(targetDir, destName))); + int count = 0; + while ((count = is.read(buffer)) > 0) + { + bos.write(buffer, 0, count); + } + bos.close(); + } + + public static void setProxyAuth(URLConnection conn) throws IOException + { + // Support for http proxy authentication + String auth = System.getProperty("http.proxyAuth"); + if ((auth != null) && (auth.length() > 0)) + { + if ("http".equals(conn.getURL().getProtocol()) + || "https".equals(conn.getURL().getProtocol())) + { + String base64 = Base64Encoder.base64Encode(auth); + conn.setRequestProperty("Proxy-Authorization", "Basic " + base64); + } + } + + } + + public static InputStream openURL(final URL url) throws IOException + { + // Do it the manual way to have a chance to + // set request properties as proxy auth (EW). + return openURL(url.openConnection()); + } + + public static InputStream openURL(final URLConnection conn) throws IOException + { + // Do it the manual way to have a chance to + // set request properties as proxy auth (EW). + setProxyAuth(conn); + try + { + return conn.getInputStream(); + } + catch (IOException e) + { + // Rather than just throwing the original exception, we wrap it + // because in some cases the original exception doesn't include + // the full URL (see FELIX-2912). + URL url = conn.getURL(); + IOException newException = new IOException("Error accessing " + url); + newException.initCause(e); + throw newException; + } + } +} \ No newline at end of file diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilOperationException.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilOperationException.java new file mode 100644 index 00000000..2642a98d --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilOperationException.java @@ -0,0 +1,11 @@ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +/** + * Thrown when method in FileUtil fails. + * Created by Zdenek Vales on 19.6.2017. + */ +public class FileUtilOperationException extends Exception { + public FileUtilOperationException(String message) { + super(message); + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/MavenPlugin.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/MavenPlugin.java new file mode 100644 index 00000000..b7475f51 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/internal/MavenPlugin.java @@ -0,0 +1,244 @@ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.mvn.plugin.namespace.NsMavenArtifact; +import cz.zcu.kiv.crce.mvn.plugin.namespace.NsMvnArtifactIdentity; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.repository.plugins.AbstractActionHandler; +import org.apache.maven.model.Model; +import org.apache.maven.model.io.xpp3.MavenXpp3Reader; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + + +/** + * An Example plugin2 for CRCE. + * + * Created by Zdenek Vales on 27.12.2016. + */ +public class MavenPlugin extends AbstractActionHandler { + + // todo: use slf4j + private static final Logger logger = LoggerFactory.getLogger(MavenPlugin.class.getName()); + + public static final String POM_NAME = "pom.xml"; + + private volatile MetadataService metadataService; + private volatile ResourceDAO resourceDAO; + + public Resource loadMavenIdentity(Resource resource){ + logger.debug("Using maven plugin"); + URL url = null; + + try { + url = getUrl(resource); + fillResource(url, resource); + addCategories(resource); + } catch (MalformedURLException ex) { + logger.error("Exception occurred while obtaining resource url: " + ex.getMessage()); + throw new IllegalStateException("Unexpected malformed url exception!", ex); + } catch (XmlPullParserException ex) { + logger.error("Exception occurred while parsing artifact pom: " + ex.getMessage()); + metadataService.addCategory(resource, NsMavenArtifact.CATEGORY__MAVEN_CORRUPTED); + } catch (IOException ex) { + logger.error("I/O exception occurred while loading maven artifact: " + ex.getMessage()); + } catch (Exception ex) { + logger.error("Exception occurred: "+ex.getMessage()); + } + + return resource; + } + + + /** + * Adds categories for mvn artifact. + * @param resource + */ + public void addCategories(Resource resource) { + metadataService.addCategory(resource, NsMavenArtifact.CATEGORY__MAVEN_ARTIFACT); + } + + /** + * Returns the URI taken from the resource identity capability. + * @param resource + * @return + */ + public URL getUrl(Resource resource) throws MalformedURLException { + URI uri = metadataService.getUri(resource); + return uri.toURL(); + } + + /** + * Tries to read pom.xml file from jar specified by artifactUrl. + * If the pom is found it will be used to fill provided resource, which + * will be returned. + * + * @param artifactUrl Url to maven artifact (jar or zip). + * @param resource Resource to be filled. + * @return Filled resource. + */ + public Resource fillResource(final URL artifactUrl, Resource resource) throws /*IOException, XmlPullParserException*/Exception { + // try to load the pom + Model pomModel = loadPom(artifactUrl); + + // populate the resource + populate(pomModel, resource); + + return resource; + } + + /** + * Will try to load pom.xml file from provided maven artifact. + * If the <version> or <groupId> of artifact aren't specified, + * the parent ones (if <parent> exists) will be used. + * + * @param artifactUrl Url to maven artifact (jar or zip). + * @return Model of pom file. + * @throws IOException + */ + public Model loadPom(final URL artifactUrl) throws IOException, XmlPullParserException { + byte[] pom = loadEntry(artifactUrl, POM_NAME); + if (pom == null) { + throw new IllegalArgumentException("The specified url is not a valid maven artifact (can't read pom.xml): " + artifactUrl); + } + + // create a model object for pom file + MavenXpp3Reader reader = new MavenXpp3Reader(); + Model pomModel = reader.read(new InputStreamReader(new ByteArrayInputStream(pom), Charset.defaultCharset())); + + return adjustModel(pomModel); + } + + /** + * If some tags are not specified, this method will try to find them in <parent> tag. + * @param model Model to be adjusted. + * @return Adjusted model. + */ + public Model adjustModel(Model model) { + boolean parentNull = model.getParent() == null; + + // artifact id tag + if(model.getArtifactId() == null && !parentNull) { + model.setArtifactId(model.getParent().getArtifactId()); + } + + // version tag + if(model.getVersion() == null && !parentNull) { + model.setVersion(model.getParent().getVersion()); + } + + // group id tag + if(model.getGroupId() == null && !parentNull) { + model.setGroupId(model.getParent().getGroupId()); + } + + return model; + } + + /** + * Taken from OsgiManigestBundleIndexer. + * + * Loads a file as an array of bytes from maven artifact (jar). + * @param artifactUrl Url to maven artifact. + * @param name Name of the file in jar. + * @return Bytes from file. + */ + private byte[] loadEntry(final URL artifactUrl, String name) { + InputStream is = null; + ZipInputStream jis = null; + try { + is = FileUtil.openURL(artifactUrl); + jis = new ZipInputStream(is); + for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry()) { + if (name.equalsIgnoreCase(e.getName())) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int n; + while ((n = jis.read(buf, 0, buf.length)) > 0) { + baos.write(buf, 0, n); + } + return baos.toByteArray(); + } + } + } catch (IOException e) { + logger.error("Exception while loading entry: "+e.getMessage()); + } finally { + if (jis != null) { + try { + jis.close(); + } catch (IOException e) { + logger.error("Exception while closing the zip stream: "+e.getMessage()); + } + } else if (is != null) { + try { + is.close(); + } catch (IOException e) { + logger.error("Exception while closing the stream: "+e.getMessage()); + } + } + } + return null; + } + + /** + * Will load the identity capability of resource and populate it with the data + * taken from pomModel. + * @param pomModel Model of pom file. + * @param resource Resource to be filled with data. + */ + private void populate(Model pomModel, Resource resource) { + + // todo: external id to the crce identity + + // get root capability for maven artifact + Capability rootCap = metadataService.getSingletonCapability(resource, NsMvnArtifactIdentity.NAMESPACE__MVN_ARTIFACT_IDENTITY); + + // add stuff to that capability + // TODO: null checking + rootCap.setAttribute(NsMvnArtifactIdentity.ATTRIBUTE__ARTIFACT_ID, pomModel.getArtifactId()); + rootCap.setAttribute(NsMvnArtifactIdentity.ATTRIBUTE__GROUP_ID, pomModel.getGroupId()); + rootCap.setAttribute(NsMvnArtifactIdentity.ATTRIBUTE__VERSION, pomModel.getVersion()); + + metadataService.addRootCapability(resource, rootCap); + } + + @Override + public List afterBufferCommit(List resources, Buffer buffer, Store store) { + logger.info("After buffer commit."); + for (Resource r : resources) { + logger.info("Loading crce identity for resource "+metadataService.getFileName(r)); + loadMavenIdentity(r); + logger.info("Capabilities added: "+metadataService.getSingletonCapability(r, NsMvnArtifactIdentity.NAMESPACE__MVN_ARTIFACT_IDENTITY)); + logger.info("All capabilities: "+r.getCapabilities()); + + saveToDB(r); + } + return super.afterBufferCommit(resources, buffer, store); + } + + private void saveToDB(Resource resource) { + try { + resourceDAO.saveResource(resource); + } catch (IOException e) { + logger.error("Could not save indexed resource {}. Exception: {}", resource, e); + } + } + + public void setMetadataService(MetadataService metadataService) { + this.metadataService = metadataService; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMavenArtifact.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMavenArtifact.java new file mode 100644 index 00000000..ebb84524 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMavenArtifact.java @@ -0,0 +1,19 @@ +package cz.zcu.kiv.crce.mvn.plugin.namespace; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * A namespace for resource's capabilities. + * + * @author Zdenek Vales + */ +public interface NsMavenArtifact { + + String NAMESPACE__MAVEN_ARTIFACT = "mvn.artifact"; + + String CATEGORY__MAVEN_ARTIFACT = "mvn"; + String CATEGORY__MAVEN_CORRUPTED = "corrupted"; + + AttributeType ATTRIBUTE__MODEL_VERSION = new SimpleAttributeType<>("modelVersion",String.class); +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMvnArtifactIdentity.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMvnArtifactIdentity.java new file mode 100644 index 00000000..bd7af872 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/namespace/NsMvnArtifactIdentity.java @@ -0,0 +1,18 @@ +package cz.zcu.kiv.crce.mvn.plugin.namespace; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; + +/** + * A namespace for resource's capabilities. + * + * @author Zdenek Vales + */ +public interface NsMvnArtifactIdentity { + + String NAMESPACE__MVN_ARTIFACT_IDENTITY = "mvn.identity"; + + AttributeType ATTRIBUTE__GROUP_ID = new SimpleAttributeType<>("groupId", String.class); + AttributeType ATTRIBUTE__ARTIFACT_ID = new SimpleAttributeType<>("artifactId", String.class); + AttributeType ATTRIBUTE__VERSION = new SimpleAttributeType<>("version", String.class); +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/Configurable.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/Configurable.java new file mode 100644 index 00000000..a966c07b --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/Configurable.java @@ -0,0 +1,34 @@ +package cz.zcu.kiv.crce.mvn.plugin.search; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; + +/** + * Interface for classes with changeable configuration. + * + * Created by Zdenek Vales on 13.6.2017. + */ +public interface Configurable { + + /** + * Reload configuration from sourceFileName file. + * Format of the file is up to the implementation class. + * All possible configuration should be overwritten by this method. + * + * @param sourceFile Source file containing new values to be used. Can be null and it's up to implementation + * class to handle null values. + */ + void reconfigure(File sourceFile) throws FileNotFoundException; + + /** + * Reload configuration from sourceStream. + * Format of the file is up to the implementation class. + * All possible configuration should be overwritten by this method. + * Stream is not closed by this method. + * + * @param sourceStream Source stream which should contain file with configuration. Cant' be null. + */ + void reconfigure(InputStream sourceStream); + +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/FoundArtifact.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/FoundArtifact.java new file mode 100644 index 00000000..ac438b1d --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/FoundArtifact.java @@ -0,0 +1,46 @@ +package cz.zcu.kiv.crce.mvn.plugin.search; + +/** + * Interface for artifact found in a maven repo. + * Class implementing this interface is not an artifact at all. It's + * actually just it's description and the artifact itself can be downloaded + * from links the implementing class will provide. + * + * Created by Zdenek Vales on 30.1.2017. + */ +public interface FoundArtifact { + + /** + * Returns the group id of the artifact. + * @return String containing group id. + */ + String getGroupId(); + + /** + * Returns the artifact id of the artifact. + * @return String containing artifact id. + */ + String getArtifactId(); + + /** + * Returns the version of artifact. + * @return String containing version. + */ + String getVersion(); + + /** + * Returns the download link for pom.xml of this artifact + * Note that not every repo may specify this link. + * + * @return Link to the pom.xml or null. + */ + String getPomDownloadLink(); + + /** + * Returns the download link to jar containing the artifact. + * + * @return Link to the jar or null (that really shouldn't happen). + */ + String getJarDownloadLink(); + +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenLocator.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenLocator.java new file mode 100644 index 00000000..2e8e7dfd --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenLocator.java @@ -0,0 +1,78 @@ +package cz.zcu.kiv.crce.mvn.plugin.search; + +import cz.zcu.kiv.crce.mvn.plugin.search.impl.VersionFilter; + +import java.util.Collection; + +/** + * Interface for locating artifacts in a maven repo. + * + * Created by Zdenek Vales on 30.1.2017. + */ +public interface MavenLocator { + + /** + * Locates the artifact in the repo and returns it. + * + * @param groupId Artifact group id. + * @param artifactId Artifact id. + * @param version Artifact version. + * @return Found artifact or null. + */ + FoundArtifact locate(String groupId, String artifactId, String version); + + /** + * Locates the artifacts in the repo and returns them. + * @param groupId Artifact group id. + * @param artifactId Artifact id. + * @return Collection of found artifacts (with different versions) or empty collection if nothing is found. + */ + Collection locate(String groupId, String artifactId); + + /** + * Locates the artifacts in the repo with version in range [from,to] (inclusive). + * @param groupId Artifact group id. + * @param artifactId Artifact id. + * @param fromVersion The oldest version to be located. + * @param toVersion The newest version to be located. + * @return Collection of found artifacts or empty collection if nothing is found. + */ + Collection locate(String groupId, String artifactId, String fromVersion, String toVersion); + + /** + * + * Locates artifacts in the repo which contain includedPackage. + * + * @param includedPackage Name of the package included in the artifact. + * @param groupIdFilter GroupId filter which will be used. + * @param highestGroupIdMatch If true, only artifacts with groupId same as the longest possible part of groupIdFilter will be returned. + * @return + */ + Collection locate(String includedPackage, String groupIdFilter, boolean highestGroupIdMatch); + + /** + * Locates artifacts in the repo which contain includedPackage. Uses includedPackage as a groupIdFilter. + * + * @param includedPackage Name of the package included in the artifact. + * @param highestGroupIdMatch If true, only artifacts with groupId same as the longest possible part of includedPackage will be returned. + * @return Collection of artifacts containing this package or empty collection if nothing is found. + */ + Collection locate(String includedPackage, boolean highestGroupIdMatch); + + /** + * Locates the artifacts in the repo if they're containing includedPackage. + * @param includedPackage Name of the package included in the artifact. + * @return Collection of artifacts containing this package or empty collection if nothing is found. + */ + Collection locate(String includedPackage); + + /** + * Filters the found artifacts by version. + * + * @param foundArtifacts Collection to be filtered. + * @param versionFilter Version filter. + * @return Filtered collection. + */ + Collection filter(Collection foundArtifacts, VersionFilter versionFilter); + +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenResolver.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenResolver.java new file mode 100644 index 00000000..746dcc15 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/MavenResolver.java @@ -0,0 +1,26 @@ +package cz.zcu.kiv.crce.mvn.plugin.search; + +import java.io.File; +import java.util.Collection; + +/** + * Interface for resolving artifacts from a maven repo. + * + * Created by Zdenek Vales on 9.4.2017. + */ +public interface MavenResolver { + + /** + * Resolves the artifact from repository. + * @param foundArtifact Artifact to be resolved. + * @return Resolved artifact or null if the artifact cannot be resolved. + */ + File resolve(FoundArtifact foundArtifact); + + /** + * Resolves the collection of artifacts from repository. + * @param foundArtifacts Artifacts to be resolved. + * @return Resolved artifacts or empty list if artifacts cannot be resolved. + */ + Collection resolveArtifacts(Collection foundArtifacts); +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/SimpleFoundArtifact.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/SimpleFoundArtifact.java new file mode 100644 index 00000000..cf311dd2 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/SimpleFoundArtifact.java @@ -0,0 +1,97 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl; + + +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import org.eclipse.aether.artifact.Artifact; + +/** + * A simple implementation of FoundArtifact. + * + * Messenger design pattern. + * + * Created by Zdenek Vales on 1.2.2017. + */ +public class SimpleFoundArtifact implements FoundArtifact { + + private final String groupId; + private final String artifactId; + private final String version; + private final String jarDownload; + private final String pomDownload; + + /** + * Creates a new artifact from aether artifact. + * @param artifact + */ + public SimpleFoundArtifact(Artifact artifact) { + this.groupId = artifact.getGroupId(); + this.artifactId = artifact.getArtifactId(); + this.version = artifact.getVersion(); + this.jarDownload = ""; + this.pomDownload = ""; + } + + public SimpleFoundArtifact(String groupId, String artifactId, String version, String jarDownload, String pomDownload) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + this.jarDownload = jarDownload; + this.pomDownload = pomDownload; + } + + @Override + public String getGroupId() { + return groupId; + } + + @Override + public String getArtifactId() { + return artifactId; + } + + @Override + public String getVersion() { + return version; + } + + @Override + public String getPomDownloadLink() { + return pomDownload; + } + + @Override + public String getJarDownloadLink() { + return jarDownload; + } + + @Override + public String toString() { + return "SimpleFoundArtifact{" + + "groupId='" + groupId + '\'' + + ", artifactId='" + artifactId + '\'' + + ", version='" + version + '\'' + + ", jarDownload='" + jarDownload + '\'' + + ", pomDownload='" + pomDownload + '\'' + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + SimpleFoundArtifact that = (SimpleFoundArtifact) o; + + if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; + if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false; + return version != null ? version.equals(that.version) : that.version == null; + } + + @Override + public int hashCode() { + int result = groupId != null ? groupId.hashCode() : 0; + result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/VersionFilter.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/VersionFilter.java new file mode 100644 index 00000000..62baee2f --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/VersionFilter.java @@ -0,0 +1,12 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl; + +/** + * Possible ways of filtering found artifacts by version. + * + * Created by Zdenek Vales on 23.5.2017. + */ +public enum VersionFilter { + + LOWEST_ONLY, + HIGHEST_ONLY +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/AdditionalQueryParam.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/AdditionalQueryParam.java new file mode 100644 index 00000000..e372a3c1 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/AdditionalQueryParam.java @@ -0,0 +1,38 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +/** + * Additional query parameters. Sucha as number of returned rows and service specification. + * + * @author Zdenek Vales + */ +public enum AdditionalQueryParam { + + /** + * Basically only working value is 'gav' + */ + CORE("core"), + + /** + * Number of returned rows. If the specified value is not a number, server will return error 500. + * If this param is specified, but empty, only few artifacts are returned. + */ + ROWS("rows"), + + /** + * Starting index of the returned artifact array. + * If the row parameter is specified, this can be used for pagination. + */ + START("start"), + + /** + * Service specification. + * Use 'json' for JSON and 'xml' for XML format. + */ + SERVICE("wt"); + + public final String paramName; + + AdditionalQueryParam(String paramName) { + this.paramName = paramName; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenRestLocator.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenRestLocator.java new file mode 100644 index 00000000..3e220ea7 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenRestLocator.java @@ -0,0 +1,283 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.VersionFilter; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.CentralRepoJsonResponse; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +/** + * This locator uses the central maven repo to search for artifacts - http://search.maven.org/. + * This repo provides rest api (described here http://search.maven.org/#api) which will be used to + * locate the artifacts. + * + * @author Zdenek Vales + */ +public class CentralMavenRestLocator implements MavenLocator { + + private static final Logger logger = LoggerFactory.getLogger(CentralMavenRestLocator.class); + + /** + * Maximum number of found artifacts returned by one query. + */ + public static final int MAX_ARTIFACTS_PER_QUERY = 50; + + private CentralRepoRestConsumer restConsumer; + + public CentralMavenRestLocator() { + this(new CentralRepoRestConsumer()); + } + + public CentralMavenRestLocator(CentralRepoRestConsumer restConsumer) { + this.restConsumer = restConsumer; + } + + @Override + public FoundArtifact locate(String groupId, String artifactId, String version) { + logger.debug("Locating artifact."); + QueryBuilder qb = QueryBuilder.createStandard(groupId, artifactId, version); + int foundArtifactCount = getResultsCounts(qb); + + if(foundArtifactCount == 0) { + return null; + } + + return fetchResults(qb, foundArtifactCount).iterator().next(); + } + + @Override + public Collection locate(String groupId, String artifactId) { + + List foundArtifacts = new ArrayList<>(); + + QueryBuilder qb = new QueryBuilder() + .addParameter(QueryParam.GROUP_ID, groupId) + .addParameter(QueryParam.ARTIFACT_ID, artifactId) + .addStandardAdditionalParameters(); + int foundArtifactsCount = getResultsCounts(qb); + if(foundArtifactsCount == 0) { + return foundArtifacts; + } + + return fetchResults(qb, foundArtifactsCount); + } + + @Override + public Collection locate(String groupId, String artifactId, String fromVersion, String toVersion) { + throw new UnsupportedOperationException("Sorry, not implemented yet."); + } + + @Override + public Collection locate(String includedPackage, String groupIdFilter, boolean highestGroupIdMatch) { + List foundArtifacts = new ArrayList<>(); + int foundArtifactsCount = 0; + + // perform the first query to get the number of total results found + QueryBuilder qb = new QueryBuilder(); + if(highestGroupIdMatch && groupIdFilter != null && !groupIdFilter.isEmpty()) { + // add 'AND g:....' to query and get first set of results with the longest groupId possible + String groupId = groupIdFilter; + while (foundArtifactsCount == 0) { + qb = new QueryBuilder() + .addParameter(QueryParam.CLASS_NAME, includedPackage) + .addParameter(QueryParam.GROUP_ID, groupId) + .addStandardAdditionalParameters(); + foundArtifactsCount = getResultsCounts(qb); + + String[] tmp = groupId.split("\\."); + + // groupId can't be any shorter + if(tmp.length <= 1) { + break; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < tmp.length-1; i++) { + sb.append(tmp[i]).append("."); + } + groupId = sb.toString(); + groupId = groupId.substring(0, groupId.length()-1); + } + } else if (groupIdFilter != null && !groupIdFilter.isEmpty()) { + // use manual groupId filter + qb = new QueryBuilder() + .addParameter(QueryParam.CLASS_NAME, includedPackage) + .addParameter(QueryParam.GROUP_ID, groupIdFilter) + .addStandardAdditionalParameters(); + foundArtifactsCount = getResultsCounts(qb); + if(foundArtifactsCount == 0) { + return foundArtifacts; + } + } else { + // no groupId filter + qb = new QueryBuilder() + .addParameter(QueryParam.CLASS_NAME, includedPackage) + .addStandardAdditionalParameters(); + foundArtifactsCount = getResultsCounts(qb); + if(foundArtifactsCount == 0) { + return foundArtifacts; + } + } + + + // fetch found artifacts + return fetchResults(qb, foundArtifactsCount); + } + + @Override + public Collection locate(String includedPackage, boolean highestGroupIdMatch) { + return locate(includedPackage, includedPackage, highestGroupIdMatch); + } + + @Override + public Collection locate(String includedPackage) { + return locate(includedPackage, "", false); + } + + @Override + public Collection filter(Collection foundArtifacts, VersionFilter versionFilter) { + switch (versionFilter) { + case HIGHEST_ONLY: + return getHighestVersions(foundArtifacts); + case LOWEST_ONLY: + return getLowestVersions(foundArtifacts); + default: + return foundArtifacts; + } + } + + /** + * Performs the query with ROWS=0 parameter to get the total number of found results. + * + * @param qb QueryBuilder with prepared search criteria. + * @return Total number of found results. + */ + private int getResultsCounts(QueryBuilder qb) { + + qb.addAdditionalParameter(AdditionalQueryParam.ROWS,"0"); + CentralRepoJsonResponse jsonResponse = null; + try { + jsonResponse = restConsumer.getJson(qb); + } catch (ServerErrorException e) { + return 0; + } + int foundArtifactsCount = jsonResponse.getResponse().getNumFound(); + return foundArtifactsCount; + } + + /** + * Fetch results in download threads. + * + * @param qb QueryBuilder with prepared search criteria. + * @param foundArtifactsCount Number of found results to be downloaded. + * @return Downloaded results. + */ + private Collection fetchResults(QueryBuilder qb, int foundArtifactsCount) { + int start = 0; + int threadCount = Math.max(1, (int)Math.ceil((double)foundArtifactsCount / MAX_ARTIFACTS_PER_QUERY)); + List threadPool = new ArrayList<>(threadCount); + List foundArtifacts = new ArrayList<>(); + + // start downloading threads + for (int i = 0; i < threadCount; i++) { + logger.debug("Starting result downloading thread for "+MAX_ARTIFACTS_PER_QUERY+" results starting at "+start); + FetchResultSetThread t = new FetchResultSetThread(qb.clone(), start, MAX_ARTIFACTS_PER_QUERY); + threadPool.add(t); + t.start(); + start += MAX_ARTIFACTS_PER_QUERY; + } + + // join threads and get found artifacts + for (FetchResultSetThread t : threadPool) { + try { + t.join(); + foundArtifacts.addAll(t.getFoundArtifacts()); + } catch (InterruptedException e) { + logger.error("Error while joining result downloading thread: "+e.getMessage()); + } + } + + return foundArtifacts; + } + + /** + * Return the highest versions of all found artifacts. + * @param foundArtifacts Collection to be filtered. + * @return Highest versions of all artifacts from foundArtifacts collection. + */ + private Collection getHighestVersions(Collection foundArtifacts) { + // group artifacts by their groupId and artifactId + Map> artifacts = new HashMap<>(); + for(FoundArtifact foundArtifact : foundArtifacts) { + String name = foundArtifact.getGroupId()+":"+foundArtifact.getArtifactId(); + if(artifacts.containsKey(name)) { + artifacts.get(name).add(foundArtifact); + } else { + artifacts.put(name, new ArrayList()); + artifacts.get(name).add(foundArtifact); + } + } + + // select the highest version for each artifact list + List highestVersions = new ArrayList<>(); + for(List tmp : artifacts.values()) { + FoundArtifact highestVersionArt = null; + DefaultArtifactVersion highestVersion = null; + for(FoundArtifact fa : tmp) { + DefaultArtifactVersion dav = new DefaultArtifactVersion(fa.getVersion()); + if(highestVersion == null) { + highestVersionArt = fa; + highestVersion = new DefaultArtifactVersion(fa.getVersion()); + } else if (highestVersion.compareTo(dav) <= 0) { + highestVersionArt = fa; + highestVersion = dav; + } + } + highestVersions.add(highestVersionArt); + } + + return highestVersions; + } + + /** + * Return the lowest versions of all found artifacts. + * @param foundArtifacts Collection to be filtered. + * @return Lowest versions of all artifacts from foundArtifacts collection. + */ + private Collection getLowestVersions(Collection foundArtifacts) { + // group artifacts by their groupId and artifactId + Map> artifacts = new HashMap<>(); + for(FoundArtifact foundArtifact : foundArtifacts) { + String name = foundArtifact.getGroupId()+":"+foundArtifact.getArtifactId(); + if(artifacts.containsKey(name)) { + artifacts.get(name).add(foundArtifact); + } else { + artifacts.put(name, new ArrayList()); + artifacts.get(name).add(foundArtifact); + } + } + + // select the lowest version for each artifact list + List lowestVersions = new ArrayList<>(); + for(List tmp : artifacts.values()) { + FoundArtifact lowestVersionArt = null; + DefaultArtifactVersion lowestVersion = null; + for(FoundArtifact fa : tmp) { + DefaultArtifactVersion dav = new DefaultArtifactVersion(fa.getVersion()); + if(lowestVersion == null) { + lowestVersionArt = fa; + lowestVersion = new DefaultArtifactVersion(fa.getVersion()); + } else if (lowestVersion.compareTo(dav) >= 0) { + lowestVersionArt = fa; + lowestVersion = dav; + } + } + lowestVersions.add(lowestVersionArt); + } + + return lowestVersions; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumer.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumer.java new file mode 100644 index 00000000..72464003 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumer.java @@ -0,0 +1,92 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.CentralRepoJsonResponse; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.JsonArtifactDescriptor; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.JsonResponseBody; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.JsonResponseHeader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.ProcessingException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * This class will fetch actual calls to rest api. + * + * @author Zdenek Vales + */ +public class CentralRepoRestConsumer { + + private static final Logger logger = LoggerFactory.getLogger(CentralRepoRestConsumer.class); + + /** + * Base url for query and additional parameters to be appended. + */ + public static final String REPO_URL = "http://search.maven.org/solrsearch/select"; + + public CentralRepoRestConsumer() { + System.setProperty("javax.xml.bind.context.factory","org.eclipse.persistence.jaxb.JAXBContextFactory"); + } + + /** + * Calls a REST API of the mvn repo and if the response is OK and json is successfully parsed, + * returns the parsed object. + * @param queryBuilder Query specifiaction. + * @return Parsed json or null. + */ + public CentralRepoJsonResponse getJson(QueryBuilder queryBuilder) throws ServerErrorException { + // get response + Response response = sendRequest(queryBuilder); + if(response == null ) { + logger.error("Response is null!"); +// System.out.println("Response is null!"); + return null; + } else if(response.getStatus() != Response.Status.OK.getStatusCode()) { + logger.error("Response not OK! Status code: "+response.getStatus()); +// System.out.println("Response not OK! Status code: "+response.getStatus()+"\nQuery: "+queryBuilder.toString()); + throw new ServerErrorException(response.getStatus()); + } + + // get parsed json + CentralRepoJsonResponse jsonResponse = null; + try { + jsonResponse = response.readEntity(CentralRepoJsonResponse.class); + } catch (ProcessingException ex) { + logger.error("Error while processing the data from response! "+ex.getMessage()); +// System.out.println("Error while processing the data from response! "+ex.getMessage()); + return null; + } catch (IllegalStateException ex) { + logger.error("Error while trying to read the data from response! "+ex.getMessage()); +// System.out.println("Error while trying to read the data from response! "+ex.getMessage()); + return null; + } catch (Exception ex) { + logger.error("Unexpected exception: "+ex.getMessage()); +// System.out.println("Unexpected exception: "+ex.getMessage()); + return null; + } + + return jsonResponse; + } + + /** + * Calls a REST service and returns the response. + * @param queryBuilder Query to be appended to the url. + * @return Response + */ + public Response sendRequest(QueryBuilder queryBuilder) { + + Client client = ClientBuilder.newClient() + .register(CentralRepoJsonResponse.class) + .register(JsonResponseHeader.class) + .register(JsonResponseBody.class) + .register(JsonArtifactDescriptor.class); + + logger.debug("Sending request to: "+REPO_URL+"?"+queryBuilder.toString()); + WebTarget resource = client.target(queryBuilder.getUrlTemplate(REPO_URL)).resolveTemplatesFromEncoded(queryBuilder.asUrlParameters()); + return resource.request(MediaType.APPLICATION_JSON_TYPE).get(); + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/FetchResultSetThread.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/FetchResultSetThread.java new file mode 100644 index 00000000..da564a5d --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/FetchResultSetThread.java @@ -0,0 +1,85 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.SimpleFoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.CentralRepoJsonResponse; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.JsonArtifactDescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Downloads and parses a set of search results. + * + * @author Zdenek Vales + */ +public class FetchResultSetThread extends Thread { + + private static final Logger logger = LoggerFactory.getLogger(FetchResultSetThread.class.getName()); + + private QueryBuilder queryBuilder; + + private List foundArtifacts; + + /** + * Constructor. + * @param queryBuilder Query builder containing the original query. The object will be changed in constructor. Use the clone() method. + * @param start Number of the starting result. + * @param rows How many results should be fetched. + */ + public FetchResultSetThread(QueryBuilder queryBuilder, int start, int rows) { + this.queryBuilder = queryBuilder; + foundArtifacts = new ArrayList<>(); + this.queryBuilder = this.queryBuilder.addAdditionalParameter(AdditionalQueryParam.ROWS, Integer.toString(rows)); + this.queryBuilder = this.queryBuilder.addAdditionalParameter(AdditionalQueryParam.START, Integer.toString(start)); + } + + /** + * Constructor. + * Query builder is not modified (start and rows parameters are expected to be already set). + * + * @param queryBuilder + */ + public FetchResultSetThread(QueryBuilder queryBuilder) { + this.queryBuilder = queryBuilder; + } + + @Override + public void run() { + // download results + List jsonArtifactDescriptors = new ArrayList<>(); + List foundArtifactsTmp = new ArrayList<>(); + CentralRepoRestConsumer restConsumer = new CentralRepoRestConsumer(); + CentralRepoJsonResponse jsonResponse = null; + try { + jsonResponse = restConsumer.getJson(queryBuilder); + if(jsonResponse.getResponse().getNumFound() > 0) { + jsonArtifactDescriptors.addAll(Arrays.asList(jsonResponse.getResponse().getDocs())); + } + } catch (ServerErrorException e) { + // error + logger.error("Exception while downloading a json response: {}.", e.getMessage()); + } + + // parse results + for(JsonArtifactDescriptor ad : jsonArtifactDescriptors) { + foundArtifactsTmp.add(new SimpleFoundArtifact(ad.getG(), + ad.getA(), + ad.getV(), + ad.jarDownloadLink(), + ad.pomDownloadLink())); + } + setFoundArtifacts(foundArtifactsTmp); + } + + public synchronized void setFoundArtifacts(List foundArtifacts) { + this.foundArtifacts = foundArtifacts; + } + + public synchronized List getFoundArtifacts() { + return foundArtifacts; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilder.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilder.java new file mode 100644 index 00000000..1d05ebea --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilder.java @@ -0,0 +1,256 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A simple builder for creating queries for searching the central maven repo. + * The queries are really simple: g:"groupId" AND a:"artifactId" .... + * + * Also adds additional parameters after the query - the query itself is just an url parameter. + * + * @author Zdenek Vales + */ +//todo: delete unused methods +public class QueryBuilder implements Cloneable { + + public static final String AND_CONCAT = "+AND+"; + + /** + * Name of the query parameter in the url. + */ + public static final String QUERY_PARAM_NAME = "q"; + + /** + * Prepares a quer builder with specified artifact parameters and standard additional parameters. + * @param groupId Group id. + * @param artifactId Artifact id. + * @param version Version. + * @return Standard query builder. + */ + public static QueryBuilder createStandard(String groupId, String artifactId, String version) { + return new QueryBuilder() + .addParameter(QueryParam.GROUP_ID, groupId) + .addParameter(QueryParam.ARTIFACT_ID, artifactId) + .addParameter(QueryParam.VERSION, version) + .addStandardAdditionalParameters(); + } + + /** + * A map which will hold the query. + * Key represents the param name, the value is param value. + */ + private Map query; + + /** + * A map wth additional params. Those will be added after the query. + */ + private Map additionalParams; + + public QueryBuilder() { + this.query = new LinkedHashMap<>(); + this.additionalParams = new LinkedHashMap<>(); + } + + /** + * Clones this query builder. + * @return + */ + public QueryBuilder clone() { + QueryBuilder qb; + + try { + super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } finally { + qb = new QueryBuilder(); + qb.setAdditionalParams(new LinkedHashMap<>(additionalParams)); + qb.setQuery(new LinkedHashMap<>(query)); + } + + return qb; + } + + protected void setQuery(Map query) { + this.query = query; + } + + protected void setAdditionalParams(Map additionalParams) { + this.additionalParams = additionalParams; + } + + /** + * Adds a parameter to the query. If the same parameter is already in the query, + * it will be overwritten. The parameters in the generated query will be insertion-ordered. + * @param parameter Parameter. + * @param value Actual value. If null, just returns the query builder. + * @return This query builder. + */ + public QueryBuilder addParameter(QueryParam parameter, String value) { + if(value == null) { + return this; + } + query.put(parameter.paramName, value); + return this; + } + + /** + * Adds an additional parameter. If the same parameter is already in the query, + * it will be overwritten. The parameters in the generated query will be insertion-ordered. + * @param parameter Parameter. + * @param value Actual value. If null, just returns the query builder. + * @return This query builder. + */ + public QueryBuilder addAdditionalParameter(AdditionalQueryParam parameter, String value) { + if(value == null) { + return this; + } + additionalParams.put(parameter.paramName, value); + return this; + } + + /** + * Adds core=gav and wt=json parameters. + * @return This query builder. + */ + public QueryBuilder addStandardAdditionalParameters() { + return addAdditionalParameter(AdditionalQueryParam.CORE, "gav").addAdditionalParameter(AdditionalQueryParam.SERVICE,"json"); + } + + /** + * Returns the query as a string. + * @return Query with format param:"param-value"+AND+param:"param-value"... + */ + public String queryToString() { + if(this.query == null || this.query.isEmpty()) { + return ""; + } + // build the query + StringBuilder sb = new StringBuilder(); + for (String paramName : query.keySet()) { + sb.append(paramName); + sb.append(":\""); + sb.append(query.get(paramName)); + sb.append("\""); + sb.append(AND_CONCAT); + } + + // remove the last AND_CONCAT + sb.delete(sb.length()-AND_CONCAT.length(),sb.length()); + return sb.toString(); + } + + /** + * Returns the query which can be append to the url. + * paramName:"paramValue"+AND+paramName:"paramValue"... + * + * Additional parameters will be appended to the query so that the whole + * string will be formatted as: + * q=[query]&[additionalParam1]&[additionalParam2]... + */ + @Override + public String toString() { + // build the query + StringBuilder sb = new StringBuilder(); + String q = queryToString(); + if(!q.isEmpty()) { + sb.append(QUERY_PARAM_NAME); + sb.append("="); + sb.append(q); + } + + // append additional parameters + if(additionalParams == null) { + return sb.toString(); + } + for(String paramName : additionalParams.keySet()) { + sb.append("&"); + sb.append(paramName); + sb.append("="); + sb.append(additionalParams.get(paramName)); + } + + return sb.toString(); + } + + /** + * Returns query and additional parameters as a map of parameters + * suitable for http client. + * @return + */ + public Map asUrlParameters() { + Map tmp = new HashMap<>(); + + if(query != null) { +// tmp.put(QUERY_PARAM_NAME, queryToString()); + for(String paramName : query.keySet()) { + tmp.put(paramName, query.get(paramName)); + } + } + + if(additionalParams != null) { + for(String paramName : additionalParams.keySet()) { + tmp.put(paramName, additionalParams.get(paramName)); + } + } + + return tmp; + } + + /** + * Converts the query to template. The format is + * paramName:{paramName}+AND+paramName:{paramName}... + * + * To be filled with values from asUrlParameters() method. + * + * @return A template for query. + */ + public String getQueryTemplate() { + StringBuilder sb = new StringBuilder(); + + if(query == null || query.isEmpty()) { + return sb.toString(); + } + + for (String paramName : query.keySet()) { + sb.append(paramName); + + //todo: figure out how to properly use quotes + sb.append(":{"); + sb.append(paramName); + sb.append("}"); + sb.append(AND_CONCAT); + } + // remove the last AND_CONCAT + sb.delete(sb.length()-AND_CONCAT.length(),sb.length()); + + return sb.toString(); + } + + /** + * Creates a template for the whole url. This will be filled with values from + * asUrlParameters() method. The format is: + * + * rootUrl?q=qParamName:{qParamName}+AND+...&additionalParamName={additionalParamName}&additionalParamName={additionalParamName}.... + * + * @param rootUrl Root url. + * @return Query template + */ + public String getUrlTemplate(String rootUrl) { + StringBuilder sb = new StringBuilder(rootUrl); + sb.append("?"); + if(query != null && !query.isEmpty()) { + sb.append(QUERY_PARAM_NAME).append("=").append(getQueryTemplate()); + } + + if(additionalParams != null && !additionalParams.isEmpty()) { + for(String paramName : additionalParams.keySet()) { + sb.append("&").append(paramName).append("={").append(paramName).append("}"); + } + } + + return sb.toString(); + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryParam.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryParam.java new file mode 100644 index 00000000..d041a75e --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryParam.java @@ -0,0 +1,21 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +/** + * Parameter names for query builder. + * + * @author Zdenek Vales + */ +public enum QueryParam { + + CLASS_NAME("fc"), + ARTIFACT_ID("a"), + GROUP_ID("g"), + VERSION("v"); + + + public final String paramName; + + QueryParam(String paramName) { + this.paramName = paramName; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/ServerErrorException.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/ServerErrorException.java new file mode 100644 index 00000000..c9daca58 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/ServerErrorException.java @@ -0,0 +1,17 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +/** + * Thrown when the search server returns html error instead of + * json response. + * + * Created by Zdenek Vales on 15.6.2017. + */ +public class ServerErrorException extends Exception { + + public final int htmlCode; + + public ServerErrorException(int htmlCode) { + super("Server returned response: "+htmlCode+"!"); + this.htmlCode = htmlCode; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/CentralRepoJsonResponse.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/CentralRepoJsonResponse.java new file mode 100644 index 00000000..c0851de2 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/CentralRepoJsonResponse.java @@ -0,0 +1,36 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * Json obtained from the central maven repo will have this structure. + * + * @author Zdenek Vales + */ +@XmlRootElement +public class CentralRepoJsonResponse implements Serializable { + + @XmlElement + private JsonResponseHeader responseHeader; + + @XmlElement + private JsonResponseBody response; + + public JsonResponseHeader getResponseHeader() { + return responseHeader; + } + + public void setResponseHeader(JsonResponseHeader responseHeader) { + this.responseHeader = responseHeader; + } + + public JsonResponseBody getResponse() { + return response; + } + + public void setResponse(JsonResponseBody response) { + this.response = response; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonArtifactDescriptor.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonArtifactDescriptor.java new file mode 100644 index 00000000..d1e5bd36 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonArtifactDescriptor.java @@ -0,0 +1,152 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * This class represents an object which describes the artifact. + * In the json returned by the maven repo, this object is used in + * response.doc array. + * + * @author Zdenek Vales + */ +@XmlRootElement +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value="EI_EXPOSE_REP", + justification="Getters/setters to arrays") +public class JsonArtifactDescriptor implements Serializable{ + + /** + * Use these values to fill the template: + * group id with '/' as separator + * artifact id + * version + * artifact id + * version + * extension - either jar or pom + */ + public static final String DOWNLOAD_URL_TEMPLATE = "http://search.maven.org/remotecontent?filepath=%s/%s/%s/%s-%s.%s"; + + /** + * Artifact id in format: + * GroupId:ArtifactId:Version + */ + @XmlElement + private String id; + + /** + * Group id. + */ + @XmlElement + private String g; + + /** + * Artifact id. + */ + @XmlElement + private String a; + + /** + * Version. + */ + @XmlElement + private String v; + + /** + * Packaging. + */ + @XmlElement + private String p; + + /** + * Artifact timestamp. + */ + @XmlElement + private long timestamp; + + /** + * Tags assigned to this artifact. + */ + @XmlElement + private String[] tags; + + /** + * Possible downloads. + */ + @XmlElement + private String[] ec; + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getG() { + return g; + } + + public void setG(String g) { + this.g = g; + } + + public String getA() { + return a; + } + + public void setA(String a) { + this.a = a; + } + + public String getV() { + return v; + } + + public void setV(String v) { + this.v = v; + } + + public String getP() { + return p; + } + + public void setP(String p) { + this.p = p; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String[] getTags() { + return tags; + } + + public void setTags(String[] tags) { + this.tags = tags; + } + + public String[] getEc() { + return ec; + } + + public void setEc(String[] ec) { + this.ec = ec; + } + + public String jarDownloadLink() { + return String.format(DOWNLOAD_URL_TEMPLATE, getG().replace('.','/'), getA(), getV(), getA(), getV(), "jar"); + } + + public String pomDownloadLink() { + return String.format(DOWNLOAD_URL_TEMPLATE, getG().replace('.','/'), getA(), getV(), getA(), getV(), "pom"); + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseBody.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseBody.java new file mode 100644 index 00000000..06394bcb --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseBody.java @@ -0,0 +1,56 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * This class represents the response element in the json returned by the + * maven repo. + * + * @author Zdenek Vales + */ +@XmlRootElement +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value="EI_EXPOSE_REP", + justification="Getters/setters to arrays") +public class JsonResponseBody implements Serializable{ + + /** + * Number of records found in the repository. + */ + @XmlElement + private int numFound; + @XmlElement + private int start; + + /** + * Found artifacts. + */ + @XmlElement + private JsonArtifactDescriptor[] docs; + + public int getNumFound() { + return numFound; + } + + public void setNumFound(int numFound) { + this.numFound = numFound; + } + + public int getStart() { + return start; + } + + public void setStart(int start) { + this.start = start; + } + + public JsonArtifactDescriptor[] getDocs() { + return docs; + } + + public void setDocs(JsonArtifactDescriptor[] docs) { + this.docs = docs; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseHeader.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseHeader.java new file mode 100644 index 00000000..f5d2481c --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/json/JsonResponseHeader.java @@ -0,0 +1,47 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.Map; + +/** + * This class represents responseHeader element in the json returned by + * maven repo. + * + * @author Zdenek Vales + */ +@XmlRootElement +public class JsonResponseHeader implements Serializable{ + + @XmlElement + private int status; + @XmlElement + private int QTime; + @XmlElement + private Map params; + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public int getQTime() { + return QTime; + } + + public void setQTime(int QTime) { + this.QTime = QTime; + } + + public Map getParams() { + return params; + } + + public void setParams(Map params) { + this.params = params; + } +} diff --git a/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolver.java b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolver.java new file mode 100644 index 00000000..ab87d204 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolver.java @@ -0,0 +1,300 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.resolver; + +import cz.zcu.kiv.crce.mvn.plugin.internal.FileUtil; +import cz.zcu.kiv.crce.mvn.plugin.search.Configurable; +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenResolver; +import org.apache.maven.repository.internal.MavenRepositorySystemUtils; +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; +import org.eclipse.aether.impl.DefaultServiceLocator; +import org.eclipse.aether.repository.LocalRepository; +import org.eclipse.aether.repository.RemoteRepository; +import org.eclipse.aether.resolution.ArtifactRequest; +import org.eclipse.aether.resolution.ArtifactResolutionException; +import org.eclipse.aether.resolution.ArtifactResult; +import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; +import org.eclipse.aether.spi.connector.transport.TransporterFactory; +import org.eclipse.aether.transport.file.FileTransporterFactory; +import org.eclipse.aether.transport.http.HttpTransporterFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Properties; + +/** + * This implementation uses the Aether library to resolve artifacts from maven repositories. + * + * A list of repositories can be configured in property file like this: + * reposityN.id= + * repositoryN.type= + * repositoryN.url= + * + * where N is the number of repository. N needs to start at 0 and always increase by 1. + * If N is 0,1,3 only respositories 0 and 1 would be used. + * + * + * Created by Zdenek Vales on 9.4.2017. + */ +public class MavenAetherResolver implements MavenResolver, Configurable { + + private static final Logger logger = LoggerFactory.getLogger(MavenAetherResolver.class); + + public static final String REPOSITORY_ID_DEF = "central"; + public static final String REPOSITORY_TYPE_DEF = "default"; + public static final String REPOSITORY_URL_DEF = "http://repo1.maven.org/maven2/"; + public static final String LOCAL_REPOSITORY_PATH_DEF = "target/local-repo"; + + private static final String CONFIG_FILE_NAME = "/search/mavenAetherLocator.properties"; + public static final String LOCAL_REPOSITORY_PATH_PROPERTY_NAME = "repository.local.path"; + public static final String REPOSITORY_N_ID_PROPERTY_NAME = "repository%d.id"; + public static final String REPOSITORY_N_TYPE_PROPERTY_NAME = "repository%d.type"; + public static final String REPOSITORY_N_URL_PROPERTY_NAME = "repository%d.url"; + + /** + * Creates a repository object with values loaded in init() method. + * @return + */ + private static RemoteRepository newRepository(String repositoryId, String repositoryType, String repositoryUrl) + { + return new RemoteRepository.Builder(repositoryId, repositoryType, repositoryUrl).build(); + } + + /** + * Initializes a new repository system for aether. + * @return Repository system. + */ + private static RepositorySystem newRepositorySystem() { + DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); + locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); + locator.addService( TransporterFactory.class, HttpTransporterFactory.class ); + locator.addService( TransporterFactory.class, FileTransporterFactory.class ); + + return locator.getService(RepositorySystem.class); + } + + /** + * Initializes a new repository session for aether. This is used to keep common settings for artifact + * resolutions. + * @param system Initialized repository system. + * @return Repository session. + */ + private static RepositorySystemSession newSession(RepositorySystem system, String localRepoPath) + { + DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); + LocalRepository localRepo = new LocalRepository( localRepoPath ); + session.setLocalRepositoryManager( system.newLocalRepositoryManager( session, localRepo ) ); + + return session; + } + + private static String getNRepoId(int n) { + return String.format(REPOSITORY_N_ID_PROPERTY_NAME, n); + } + + private static String getNRepoType(int n) { + return String.format(REPOSITORY_N_TYPE_PROPERTY_NAME, n); + } + + private static String getNRepoUrl(int n) { + return String.format(REPOSITORY_N_URL_PROPERTY_NAME, n); + } + + private String localRepoPath; + + private List repositories; + private RepositorySystem repositorySystem; + private RepositorySystemSession repositorySystemSession; + + + public MavenAetherResolver() { + init(); + } + + /** + * Initializes repository id, type and url from resource config file. If no file or values are found, + * default ones are used. + */ + private void init() { + try { + reconfigure((File)null); + } catch (FileNotFoundException e) { + // this really shouldn't happen + logger.error("Error while loading configuration from default file: "+e.getMessage()); + } + } + + public List getRepositories() { + return repositories; + } + + public String getLocalRepoPath() { + return localRepoPath; + } + + @Override + public void reconfigure(InputStream sourceStream) { + // load properties + repositories = new ArrayList<>(); + Properties properties = new Properties(); + localRepoPath = null; + try { + properties.load(sourceStream); + + // load single properties first + localRepoPath = properties.getProperty(LOCAL_REPOSITORY_PATH_PROPERTY_NAME, LOCAL_REPOSITORY_PATH_DEF); + + // load N repositories + int n = 0; + while(properties.getProperty(getNRepoId(n)) != null) { + String repositoryId = properties.getProperty(getNRepoId(n), REPOSITORY_ID_DEF); + String repositoryType = properties.getProperty(getNRepoType(n), REPOSITORY_TYPE_DEF); + String repositoryUrl = properties.getProperty(getNRepoUrl(n), REPOSITORY_URL_DEF); + + repositories.add(newRepository(repositoryId, repositoryType, repositoryUrl)); + n++; + } + + // no repositories configured + if(repositories.isEmpty()) { + repositories.add(newRepository(REPOSITORY_ID_DEF, REPOSITORY_TYPE_DEF, REPOSITORY_URL_DEF)); + } + + } catch (IOException e) { + logger.error("Exception while configuring "+MavenAetherResolver.class.getSimpleName()+". "+e.getMessage()+", using default values."); + if(repositories.isEmpty()) { + repositories.add(newRepository(REPOSITORY_ID_DEF, REPOSITORY_TYPE_DEF, REPOSITORY_URL_DEF)); + } + + if(localRepoPath == null) { + localRepoPath = LOCAL_REPOSITORY_PATH_DEF; + } + } + + repositorySystem = newRepositorySystem(); + repositorySystemSession = newSession(repositorySystem, localRepoPath); + } + + @Override + public void reconfigure(File sourceFile) throws FileNotFoundException { + InputStream is; + + // bad file => use the default one + if(sourceFile == null) { + logger.debug("No configuration file, using the default one."); + is = this.getClass().getResourceAsStream(CONFIG_FILE_NAME); + } else { + is = new FileInputStream(sourceFile); + } + + reconfigure(is); + + try { + is.close(); + } catch (IOException e) { + logger.error("Exception while closing the stream: "+e.getMessage()); + } + + } + + /** + * Downloads pom file for found artifact. + * @param foundArtifact + * @return + */ + private File downloadPom(FoundArtifact foundArtifact) { + Artifact artifact = new DefaultArtifact(foundArtifact.getGroupId(), + foundArtifact.getArtifactId(), + "pom", + foundArtifact.getVersion()); + ArtifactRequest artifactRequest = new ArtifactRequest(); + artifactRequest.setArtifact(artifact); + artifactRequest.setRepositories(repositories); + + ArtifactResult artifactResult; + try { + artifactResult = repositorySystem.resolveArtifact(repositorySystemSession, artifactRequest); + } catch (ArtifactResolutionException e) { + logger.error("Unexpected error occurred while resolving pom for artifact: "+e.getMessage()); + return null; + } + + if(artifactResult.isResolved()) { + return artifactResult.getArtifact().getFile(); + } else { + return null; + } + } + + @Override + public File resolve(FoundArtifact foundArtifact) { + + // download jar + Artifact artifact = new DefaultArtifact(foundArtifact.getGroupId(), + foundArtifact.getArtifactId(), + "jar", + foundArtifact.getVersion()); + ArtifactRequest artifactRequest = new ArtifactRequest(); + artifactRequest.setArtifact(artifact); + artifactRequest.setRepositories(repositories); + + ArtifactResult artifactResult; + try { + artifactResult = repositorySystem.resolveArtifact(repositorySystemSession, artifactRequest); + } catch (ArtifactResolutionException e) { + logger.error("Unexpected error occurred while resolving artifact: "+e.getMessage()); + return null; + } + + if(artifactResult.isResolved()) { + File art = artifactResult.getArtifact().getFile(); + logger.trace("Checking file "+art+" for pom..."); + try { + if(FileUtil.isFilePresentInJar(art.getPath(), "pom.xml")) { + logger.trace("Pom.xml file is present."); + } else { + logger.trace("Pom.xml file is not present!"); + + File pom = downloadPom(foundArtifact); + if(pom == null) { + logger.error("Pom is null!"); + return null; + } else { + InputStream in = new FileInputStream(new File(pom.getPath())); + FileUtil.addPomToJar(art.getPath(), in); + in.close(); + } + } + } catch (IOException e) { + logger.error("Exception while checking if artifact contains pom file!"); + return null; + } + + return art; + } else { + return null; + } + } + + @Override + public Collection resolveArtifacts(Collection foundArtifacts) { + List res = new ArrayList<>(); + for(FoundArtifact foundArtifact : foundArtifacts) { + File f = resolve(foundArtifact); + if(f != null) { + res.add(f); + } + } + + return res; + } + +} diff --git a/modules/crce-mvn-plugin/src/main/resources/search/mavenAetherLocator.properties b/modules/crce-mvn-plugin/src/main/resources/search/mavenAetherLocator.properties new file mode 100644 index 00000000..2037b2f0 --- /dev/null +++ b/modules/crce-mvn-plugin/src/main/resources/search/mavenAetherLocator.properties @@ -0,0 +1,8 @@ +# configuration of maven aether resolver +repository.local.path=target/local-repo +repository0.id=central +repository0.type=default +repository0.url=http://repo1.maven.org/maven2/ + + + diff --git a/modules/crce-mvn-plugin/src/main/resources/test-jar.jar b/modules/crce-mvn-plugin/src/main/resources/test-jar.jar new file mode 100644 index 00000000..bbcf4421 Binary files /dev/null and b/modules/crce-mvn-plugin/src/main/resources/test-jar.jar differ diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/NexusIndexerTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/NexusIndexerTest.java new file mode 100644 index 00000000..00106b24 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/NexusIndexerTest.java @@ -0,0 +1,137 @@ +package cz.zcu.kiv.crce.mvn.plugin; + +import org.codehaus.plexus.PlexusContainerException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; + +/** + * Created by Zdenek Vales on 2.4.2017. + */ +public class NexusIndexerTest { + + @Test + @Ignore + public void testNexusIndexer() throws IOException, ComponentLookupException, PlexusContainerException { + +// String artifactId = "hibernate-core"; +// String groupId = "org.hibernate"; +// String version = "5.2.0.Final"; +// String repoId = "central"; +// +// final DefaultContainerConfiguration config = new DefaultContainerConfiguration(); +// config.setClassPathScanning( PlexusConstants.SCANNING_INDEX ); +// PlexusContainer plexusContainer = new DefaultPlexusContainer( config ); +// +// // lookup the indexer components from plexus +// Indexer nexusIndexer = plexusContainer.lookup( Indexer.class ); +// IndexUpdater indexUpdater = plexusContainer.lookup( IndexUpdater.class ); +// // lookup wagon used to remotely fetch index +// Wagon httpWagon = plexusContainer.lookup( Wagon.class, "http" ); +// +// File centralLocalCache = new File( "target/central-cache" ); +// File centralIndexDir = new File( "target/central-index" ); +// +// // Creators we want to use (search for fields it defines) +// List indexers = new ArrayList(); +// indexers.add( plexusContainer.lookup( IndexCreator.class, "min" ) ); +// indexers.add( plexusContainer.lookup( IndexCreator.class, "jarContent" ) ); +// indexers.add( plexusContainer.lookup( IndexCreator.class, "maven-plugin" ) ); +// +// // Create context for central repository index +// IndexingContext centralContext = +// nexusIndexer.createIndexingContext( "central-context", "central", centralLocalCache, centralIndexDir, +// "http://central.maven.org/maven2/", null, true, true, indexers ); +// +// updateIndex(centralContext, httpWagon, indexUpdater); +// +// System.out.println("Searching for artifact with gav coordinates."); +// +// BooleanQuery bq = new BooleanQuery(); +// bq.add(nexusIndexer.constructQuery(MAVEN.ARTIFACT_ID, new SourcedSearchExpression(artifactId )), BooleanClause.Occur.MUST); +// bq.add(nexusIndexer.constructQuery(MAVEN.GROUP_ID, new SourcedSearchExpression(groupId )), BooleanClause.Occur.MUST); +// bq.add(nexusIndexer.constructQuery(MAVEN.VERSION, new SourcedSearchExpression(version )), BooleanClause.Occur.MUST); +// bq.add(nexusIndexer.constructQuery(MAVEN.PACKAGING, new SourcedSearchExpression("jar" )), BooleanClause.Occur.MUST); +// +// FlatSearchRequest request = new FlatSearchRequest(bq, centralContext); +// FlatSearchResponse response = nexusIndexer.searchFlat(request); +// +// Set artifactInfos = response.getResults(); +// System.out.println("Checking..."); +// assertFalse("No artifacts found!", artifactInfos.isEmpty()); +// +// ArtifactInfo ai = artifactInfos.iterator().next(); +// FoundArtifact result = new SimpleFoundArtifact(ai.groupId, ai.artifactId, ai.version, "", ""); +// +// assertEquals("Wrong artifactId!", artifactId, result.getArtifactId()); +// assertEquals("Wrong groupId!", groupId, result.getGroupId()); +// assertEquals("Wrong version!", version, result.getVersion()); +// System.out.println("Done"); +// +// +// System.out.println("Searching for artifact by classname."); +// String packageName = "SQLiteDialect"; +// +// bq = new BooleanQuery(); +// bq.add(nexusIndexer.constructQuery(MAVEN.CLASSNAMES, new SourcedSearchExpression(packageName)), BooleanClause.Occur.SHOULD); +// +// request = new FlatSearchRequest(bq, centralContext); +// response = nexusIndexer.searchFlat(request); +// +// artifactInfos = response.getResults(); +// System.out.println("Checking..."); +// assertFalse("No artifacts found!", artifactInfos.isEmpty()); +// +// for(ArtifactInfo artifactInfo : artifactInfos) { +// assertTrue("Wrong artifact!", artifactInfo.classNames.contains(packageName)); +// } +// System.out.println("Done"); + } + +// private void updateIndex(IndexingContext context, Wagon wagon, IndexUpdater indexUpdater) throws IOException { +// System.out.println( "Updating Index..." ); +// System.out.println( "This might take a while on first run, so please be patient!" ); +// // Create ResourceFetcher implementation to be used with IndexUpdateRequest +// // Here, we use Wagon based one as shorthand, but all we need is a ResourceFetcher implementation +// TransferListener listener = new AbstractTransferListener() +// { +// public void transferStarted( TransferEvent transferEvent ) +// { +// System.out.print( " Downloading " + transferEvent.getResource().getName() ); +// } +// +// public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length ) +// { +// } +// +// public void transferCompleted( TransferEvent transferEvent ) +// { +// System.out.println( " - Done" ); +// } +// }; +// +// ResourceFetcher resourceFetcher = new WagonHelper.WagonFetcher( wagon, listener, null, null ); +// +// Date centralContextCurrentTimestamp = context.getTimestamp(); +// IndexUpdateRequest updateRequest = new IndexUpdateRequest(context, resourceFetcher); +// IndexUpdateResult updateResult = indexUpdater.fetchAndUpdateIndex( updateRequest ); +// if ( updateResult.isFullUpdate() ) +// { +// System.out.println( "Full update happened!" ); +// } +// else if ( updateResult.getTimestamp().equals( centralContextCurrentTimestamp ) ) +// { +// System.out.println( "No update needed, index is up to date!" ); +// } +// else +// { +// System.out.println( +// "Incremental update happened, change covered " + centralContextCurrentTimestamp + " - " +// + updateResult.getTimestamp() + " period." ); +// } +// +// System.out.println(); +// } +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/PerformanceTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/PerformanceTest.java new file mode 100644 index 00000000..59176e2e --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/PerformanceTest.java @@ -0,0 +1,139 @@ +package cz.zcu.kiv.crce.mvn.plugin; + +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.*; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.CentralRepoJsonResponse; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Created by Zdenek Vales on 15.6.2017. + */ +public class PerformanceTest { + + /** + * Server returns 500 or 504 everytime. + */ + @Test + @Ignore + public void testSearchErrors() { + String fc = "org.hibernate.dialect"; + int rows = 800; + int queryCount = 100; + double avgTime = 0; + long timeSum = 0; + Map results = new TreeMap<>(); + CentralRepoRestConsumer consumer = new CentralRepoRestConsumer(); + + QueryBuilder qb = new QueryBuilder() + .addParameter(QueryParam.CLASS_NAME, fc) + .addStandardAdditionalParameters() + .addAdditionalParameter(AdditionalQueryParam.ROWS,Integer.toString(rows)); + + for (int i = 0; i < queryCount; i++) { + if(i % 10 == 0) { + System.out.println(String.format("%d iteration.",i)); + avgTime = timeSum / queryCount; + System.out.println("Average time: "+avgTime+" ms"); + System.out.println(" HTML CODE | COUNT "); + for(Integer c : results.keySet()) { + System.out.println(String.format("%10d | %5d", c, results.get(c))); + } + System.out.println(""); + } + + long now = System.currentTimeMillis(); + + int code = 0; + try { + CentralRepoJsonResponse response = consumer.getJson(qb); + code = 400; + } catch (ServerErrorException e) { + code = e.htmlCode; + } + + if(!results.containsKey(code)) { + results.put(code, 1); + } else { + results.put(code, results.get(code) +1); + } + + timeSum += (System.currentTimeMillis() - now); + } + + avgTime = timeSum / queryCount; + + System.out.println("Average time: "+avgTime+" ms"); + System.out.println(" HTML CODE | COUNT "); + for(Integer code : results.keySet()) { + System.out.println(String.format("%10d | %5d", code, results.get(code))); + } + } + + /** + * Test differences in times needed to download set of results with and without paralelization. + */ + @Test + @Ignore + public void testThreadVsNonThreadPerformance() throws ServerErrorException { + long nonParalelTime = 0L; + long paralelTime = 0L; + int rows = 800; + String fc = "org.hibernate.dialect"; + CentralRepoRestConsumer consumer = new CentralRepoRestConsumer(); + int maxArt = CentralMavenRestLocator.MAX_ARTIFACTS_PER_QUERY; + int queryCount = rows / maxArt; + + // prepare queries + QueryBuilder qb = new QueryBuilder() + .addParameter(QueryParam.CLASS_NAME, fc) + .addStandardAdditionalParameters() + .addAdditionalParameter(AdditionalQueryParam.ROWS,Integer.toString(maxArt)); + List queries = new ArrayList<>(); + for (int i = 0; i < queryCount; i++) { + QueryBuilder q = qb.clone(); + q.addAdditionalParameter(AdditionalQueryParam.START, Integer.toString(maxArt*i)); + queries.add(q); + } + + + // non paralel download + nonParalelTime = System.nanoTime(); + // download results + for (int i = 0; i < queryCount; i++) { + QueryBuilder q = queries.get(i); + consumer.getJson(q); + } + nonParalelTime = System.nanoTime() - nonParalelTime; + + // paralel download + paralelTime = System.nanoTime(); + List threadPool = new ArrayList<>(queryCount); + // start downloading threads + for (int i = 0; i < queryCount; i++) { +// logger.debug("Starting result downloading thread for "+maxArt+" results starting at "+start); + FetchResultSetThread t = new FetchResultSetThread(queries.get(i)); + threadPool.add(t); + t.start(); + } + + // join threads and get found artifacts + for (FetchResultSetThread t : threadPool) { + try { + t.join(); +// foundArtifacts.addAll(t.getFoundArtifacts()); + } catch (InterruptedException e) { +// logger.error("Error while joining result downloading thread: "+e.getMessage()); + } + } + paralelTime = System.nanoTime() - paralelTime; + + System.out.println("Time to download "+rows+" in "+queryCount+" parts without threads: "+nonParalelTime / 1000000000); + System.out.println("Time to download "+rows+" in "+queryCount+" parts with threads: "+paralelTime / 1000000000); + } + +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilTest.java new file mode 100644 index 00000000..89e45048 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/FileUtilTest.java @@ -0,0 +1,105 @@ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import org.junit.Ignore; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Created by Zdenek Vales on 18.6.2017. + */ +public class FileUtilTest { + + @Test + public void testIsFilePresentInJar() throws IOException { + String jarWithFile = "/test-jar.jar"; + String jarWithoutFile = "/hibernate-core-5.2.7.Final-orig.jar"; + String filename = "pom.xml"; + + assertTrue("Jar "+jarWithFile+" should contain pom.xml!", FileUtil.isFilePresentInJar(getResource(jarWithFile).getPath(), filename)); + assertFalse("Jar "+jarWithoutFile+" should not contain pom.xml!", FileUtil.isFilePresentInJar(getResource(jarWithoutFile).getPath(), filename)); + } + + /** + * Take jar without file, check that it doesn't contain pom.xml, add pom.xml to that file + * and verify it contains the pom. + */ + @Test + public void testAddPomToJar() throws IOException, URISyntaxException { + String jarWithoutFile = "D:/tmp/bp/test/hibernate-core-5.2.7.Final.jar"; + String jarWithoutFileCopy = "D:/tmp/bp/test/jar-without-pom.jar"; + String pathToPom = "D:/tmp/bp/test/pom.xml"; + String filename = "pom.xml"; + + // create a working copy of jarWithoutFile + Path p = Paths.get(jarWithoutFile); + Path p2 = Paths.get(jarWithoutFileCopy); + Files.copy(p, p2, StandardCopyOption.REPLACE_EXISTING); + + // check that the copy doesn't contain pom.xml + assertFalse("Working copy should not contain pom.xml!", FileUtil.isFilePresentInJar(p2.toString(), filename)); + + // add pom file + InputStream in = new FileInputStream(new File(pathToPom)); + FileUtil.addPomToJar(jarWithoutFileCopy, in); + in.close(); + + // check that the copy now contains pom.xml + assertTrue("Working copy should now contain pom.xml!", FileUtil.isFilePresentInJar(jarWithoutFileCopy, filename)); + + // check that the original pom still exists + File pomFile = new File(pathToPom); + assertTrue("Original pom file should still exist!", pomFile.exists()); + + // delete working copy + File f = new File(jarWithoutFileCopy); + f.delete(); + } + + @Test + @Ignore + public void testUnjar() throws FileUtilOperationException, IOException { + // test jar contains only pom.xml and META-INF/MANIFEST.MF files + String testJar = "/test-jar.jar"; + String dir = "D:/tmp/bp/test/test-jar-dir"; + String expectedFile = dir+"/pom.xml"; + String expectedFile2 = dir+"/META-INF/MANIFEST.MF"; + + // delete the target dir if it exists + File targetDir = new File(dir); + if(targetDir.exists()) { + targetDir.delete(); + } + + // unjar + FileUtil.unJar(getResource(testJar).getPath(), dir); + + File f = new File(expectedFile); + File f2 = new File(expectedFile2); + assertTrue("Target dir should exist!", targetDir.exists()); + assertTrue("Pom.xml should exist in unzipped archive!", f.exists()); + assertTrue("Manifest file should exist in unzipped archive!", f2.exists()); + } + + /** + * Returns URL to files from the resources folder. + * @param resourceName Name of the resource file. + * @return URL to the resour ce file. + */ + private URL getResource(String resourceName) { + return getClass().getResource(resourceName); + } + +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/PluginTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/PluginTest.java new file mode 100644 index 00000000..4cd0dbf7 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/internal/PluginTest.java @@ -0,0 +1,134 @@ +package cz.zcu.kiv.crce.mvn.plugin.internal; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.internal.MetadataFactoryImpl; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.internal.MetadataServiceImpl; +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenResolver; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.CentralMavenRestLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.resolver.MavenAetherResolver; +import org.apache.maven.model.Model; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +import static org.junit.Assert.*; + +/** + * @author Zdenek Vales + */ +public class PluginTest { + + public static final String TEST_JAR_NAME = "/test-jar.jar"; + public static final String TEST_ARTIFACT_ID = "crce-target"; + public static final String TEST_VERSION = "2.1.1-SNAPSHOT"; + + private static MetadataFactory metadataFactory; + private static MetadataService metadataService; + + @BeforeClass + public static void before() { + metadataFactory = new MetadataFactoryImpl(); + metadataService = new MetadataServiceImpl(); + } + + @Test + public void testLoadPom() throws /*IOException, XmlPullParserException*/ Exception { + URL artifactUrl = getResource(TEST_JAR_NAME); + MavenPlugin mp = new MavenPlugin(); + + assertNotNull("Test jar doesn't exists!",artifactUrl); + Model pomModel = mp.loadPom(artifactUrl); + assertNotNull("Null returned!", pomModel); + assertEquals("Wrong artifact id!", TEST_ARTIFACT_ID, pomModel.getArtifactId()); + // version should be taken from tag + assertEquals("Wrong version!", TEST_VERSION, pomModel.getVersion()); + } + + /** + * Try to load pom from jar without pom, then add pom and try it again. + */ + @Test + public void testLoadPom2() throws IOException, XmlPullParserException, URISyntaxException { + // both files contain same artifact + String origName = "/hibernate-core-5.2.7.Final-orig.jar"; + String name1="/hibernate-core-5.2.7.Final.jar"; + String pomPath = "/hibernate-core-pom.xml"; + String gid = "org.hibernate"; + String aId = "hibernate-core"; + String v = "5.2.7.Final"; + MavenPlugin mp = new MavenPlugin(); + + // copy orig jar to test jar so that test jar won't contain pom.xml + Path p = Paths.get(getResource(origName).toURI()); + Path p2 = Paths.get(getResource(name1).toURI()); + Files.copy(p, p2, StandardCopyOption.REPLACE_EXISTING); + + // try to load model without pom + assertFalse("Jar shouldn't contain pom.xml file yet!", FileUtil.isFilePresentInJar(p2.toString(), "pom.xml")); + Model model = null; + try { + model = mp.loadPom(getResource(name1)); + } catch (IllegalArgumentException e) { + // ok + } catch (Exception e) { + fail("Unexpected exception while load pom model: "+e.getMessage()); + } + + // add pom to the jar and load model again + InputStream in = new FileInputStream(new File(getResource(pomPath).getPath())); + FileUtil.addPomToJar(p2.toString(), in); + in.close(); + assertTrue("Jar should now contain pom.xml file!", FileUtil.isFilePresentInJar(p2.toString(), "pom.xml")); + model = mp.loadPom(getResource(name1)); + assertEquals("Wrong groupId!", gid, model.getGroupId()); + assertEquals("Wrong artifactId!", aId, model.getArtifactId()); + assertEquals("Wrong version!", v, model.getVersion()); + } + + /** + * Test complete functionality. + */ + @Test + public void testLocateResolveLoadPom() throws IOException, XmlPullParserException { + MavenLocator locator = new CentralMavenRestLocator(); + MavenResolver resolver = new MavenAetherResolver(); + MavenPlugin mp = new MavenPlugin(); + String groupId = "org.hibernate"; + String artifactId = "hibernate-core"; + String version = "5.2.7.Final"; + + FoundArtifact artifact = locator.locate(groupId, artifactId, version); + assertNotNull("Null returned by locate() method!", artifact); + File file = resolver.resolve(artifact); + assertNotNull("Null returned by resolve() method!", file); + Model model = mp.loadPom(file.toURI().toURL()); + assertNotNull("Null returned by loadPom() method!", model); + + assertEquals("Wrong groupId!", groupId, model.getGroupId()); + assertEquals("Wrong artifactId!", artifactId, model.getArtifactId()); + assertEquals("Wrong version!", version, model.getVersion()); + } + + /** + * Returns URL to files from the resources folder. + * @param resourceName Name of the resource file. + * @return URL to the resour ce file. + */ + private URL getResource(String resourceName) { + return getClass().getResource(resourceName); + } +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenLocatorTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenLocatorTest.java new file mode 100644 index 00000000..844c7aca --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralMavenLocatorTest.java @@ -0,0 +1,284 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.VersionFilter; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.Collection; +import java.util.Iterator; + +import static org.junit.Assert.*; + +public class CentralMavenLocatorTest { + + @Test + public void testLocateArtifact() { + String groupId = "org.hibernate"; + String artifactId = "hibernate-core"; + String version = "5.2.7.Final"; + String jarDownload = "http://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.2.7.Final/hibernate-core-5.2.7.Final.jar"; + String pomDownload = "http://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.2.7.Final/hibernate-core-5.2.7.Final.pom"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + FoundArtifact artifact = locator.locate(groupId, artifactId, version); + assertNotNull("Returned artifact is null!", artifact); + assertEquals("Wrong group id!", groupId, artifact.getGroupId()); + assertEquals("Wrong artifact id!", artifactId, artifact.getArtifactId()); + assertEquals("Wrong version!", version, artifact.getVersion()); + assertNotNull("Jar download link is null!", artifact.getJarDownloadLink()); + assertEquals("Wrong jar download link!", jarDownload, artifact.getJarDownloadLink()); + assertNotNull("Pom download link is null!", artifact.getPomDownloadLink()); + assertEquals("Wrong pom download link!", pomDownload, artifact.getPomDownloadLink()); + } + + @Test + public void testLocateArtifacts() { + String groupId = "org.hibernate"; + String artifactId = "hibernate-core"; + String jarDownloadTmplt = "http://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/%s/hibernate-core-%s.jar"; + String pomDownloadTmplt = "http://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/%s/hibernate-core-%s.pom"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(groupId, artifactId); + for(FoundArtifact artifact : artifacts) { + assertEquals("Wrong group id!", groupId, artifact.getGroupId()); + assertEquals("Wrong artifact id!", artifactId, artifact.getArtifactId()); + assertNotNull("Null version!", artifact.getVersion()); + + String jd = String.format(jarDownloadTmplt, artifact.getVersion(), artifact.getVersion()), + pd = String.format(pomDownloadTmplt, artifact.getVersion(), artifact.getVersion()); + + assertNotNull("Jar download link is null!", artifact.getJarDownloadLink()); + assertEquals("Wrong jar download link!", jd, artifact.getJarDownloadLink()); + assertNotNull("Pom download link is null!", artifact.getPomDownloadLink()); + assertEquals("Wrong pom download link!", pd, artifact.getPomDownloadLink()); + } + } + + @Test + public void testLocateArtifactByGroupId() { + String groupId = "org.hibernate"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(groupId, null); + assertNotNull("Null returned!", artifacts); + assertFalse("No artifacts found for group id "+groupId, artifacts.isEmpty()); + for(FoundArtifact artifact : artifacts) { + assertEquals("Wrong group id!", groupId, artifact.getGroupId()); + assertNotNull("Null artifact id!", artifact.getArtifactId()); + assertNotNull("Null version!", artifact.getVersion()); + } + } + + @Test + @Ignore + public void testLocateArtifactByIncludedPackage() { + String packageName = "org.hibernate.dialect.function"; + // update this number as needed... + int expCount = 880; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(packageName); + assertNotNull("Null returned!", artifacts); + assertFalse("No artifacts containing package " + packageName + " found!", artifacts.isEmpty()); + assertEquals("Wrong number of artifacts located!", expCount, artifacts.size()); + } + + @Test + @Ignore + public void testLocatArtifactByIncludedPackageVersionFilter() { + String packageName = "org.hibernate.dialect.function"; + int expCount = 880; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(packageName); + artifacts = locator.filter(artifacts, VersionFilter.HIGHEST_ONLY); + + assertNotNull("Null returned!",artifacts); + assertFalse("No artifacts containing package "+packageName+" found!", artifacts.isEmpty()); + assertTrue("Wrong number of artifacts ("+artifacts.size()+"!", artifacts.size() < expCount); + } + + @Test + public void testLocateArtifactByIncludedPackageBad() { + String badPackageName = "asdasdasdagasd"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(badPackageName); + assertNotNull("Null returned!", artifacts); + assertTrue("Artifacts containing package "+badPackageName+" found!", artifacts.isEmpty()); + } + + @Test + public void testLocateArtifactByIncludedPackageBad2() { + String badPackageName = "asdasdasdagasd"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(badPackageName, true); + assertNotNull("Null returned!", artifacts); + assertTrue("Artifacts containing package "+badPackageName+" found!", artifacts.isEmpty()); + } + + @Test + public void testFilterVersion() { + String packageName = "org.hibernate.dialect.MimerSQLDialect"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + + Collection artifacts = locator.locate(packageName); + assertFalse("No artifacts found!", artifacts.isEmpty()); + int count = artifacts.size(); + + Collection highest = locator.filter(artifacts, VersionFilter.HIGHEST_ONLY); + int hSize = highest.size(); + Collection lowest = locator.filter(artifacts, VersionFilter.LOWEST_ONLY); + int lSize = lowest.size(); + + assertTrue("Highest versions count "+(hSize)+" should be lower than total count "+(count)+"!", hSize < count ); + assertTrue("Lowest versions count "+(lSize)+" should be lower than total count "+(count)+"!", lSize < count ); + assertEquals("Lowest version count sohuld be the same as the highest version count!", lSize, hSize); + } + + @Test + public void testLocateArtifacts2() { + String fc = "org.specs.runner.Junit"; + int expCount = 54; + + CentralMavenRestLocator cmrl = new CentralMavenRestLocator(); + Collection foundArtifacts = cmrl.locate(fc); + + assertNotNull("Null returned!", foundArtifacts); + assertEquals("Wrong number of found artifacts!", expCount, foundArtifacts.size()); + } + + @Test + public void testLocateArtifactByIncludedPackageHighestGMatch() { + String fc = "org.hibernate.dialect.MimerSQLDialect"; + String expectedGid = "org.hibernate"; + int expCount = 175; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection foundArtifacts = locator.locate(fc, true); + + assertNotNull("Null returned!", foundArtifacts); + assertEquals("Wrong number of artifacts returned!", expCount, foundArtifacts.size()); + + for (FoundArtifact fa : foundArtifacts) { + assertEquals("Only artifacts with one groupId expected!", expectedGid, fa.getGroupId()); + } + } + + @Test + public void testLocateArtifactByIncludedPackageHighestGMatchFilterVersion() { + String fc = "org.hibernate.dialect.MimerSQLDialect"; + String expectedGid = "org.hibernate"; + String expectedAid = "hibernate-core"; + String expectedAid2 = "hibernate"; + String expectedVersion = "5.2.10.Final"; + String expectedVersion2 = "3.2.7.ga"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection foundArtifacts = locator.locate(fc, true); + foundArtifacts = locator.filter(foundArtifacts, VersionFilter.HIGHEST_ONLY); + + assertEquals("Only 2 artifacts expected!",2 , foundArtifacts.size()); + Iterator faIt = foundArtifacts.iterator(); + FoundArtifact fa = faIt.next(); + assertEquals("Wrong groupId!", expectedGid, fa.getGroupId()); + assertTrue("Wrong aId "+fa.getArtifactId()+"!", fa.getArtifactId().equals(expectedAid) || fa.getArtifactId().equals(expectedAid2)); + assertTrue("Wrong version "+fa.getVersion()+"!", fa.getVersion().equals(expectedVersion) || fa.getVersion().equals(expectedVersion2)); + + fa = faIt.next(); + assertEquals("Wrong groupId!", expectedGid, fa.getGroupId()); + assertTrue("Wrong aId "+fa.getArtifactId()+"!", fa.getArtifactId().equals(expectedAid) || fa.getArtifactId().equals(expectedAid2)); + assertTrue("Wrong version "+fa.getVersion()+"!", fa.getVersion().equals(expectedVersion) || fa.getVersion().equals(expectedVersion2)); + } + + @Test + public void testLocateArtifactByIncludedPackageManualGroupIdFilterVersion() { + String fc = "org.hibernate.dialect.MimerSQLDialect"; + String groupIdFilter = "org.ow2.easybeans"; + String expectedAId = "easybeans-uberjar-hibernate"; + String expectedVersionH = "1.1.1"; + String expectedVersionL = "1.0.0"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection beforeFilter = locator.locate(fc, groupIdFilter, false); + assertNotNull("Null returned for search!", beforeFilter); + + Collection hv = locator.filter(beforeFilter, VersionFilter.HIGHEST_ONLY); + Collection lv = locator.filter(beforeFilter, VersionFilter.LOWEST_ONLY); + + assertEquals("Only one artifact expected for highest version!", 1, hv.size()); + Iterator faIt = hv.iterator(); + FoundArtifact fa = faIt.next(); + assertEquals("Wrong groupId!", groupIdFilter, fa.getGroupId()); + assertEquals("Wrong artifactId!", expectedAId, fa.getArtifactId()); + assertEquals("Wrong highest version!", expectedVersionH, fa.getVersion()); + + faIt = lv.iterator(); + fa = faIt.next(); + assertEquals("Wrong groupId!", groupIdFilter, fa.getGroupId()); + assertEquals("Wrong artifactId!", expectedAId, fa.getArtifactId()); + assertEquals("Wrong lowest version!", expectedVersionL, fa.getVersion()); + } + + @Test + public void testLocateArtifactByIncludedPackageWrongManualGid() { + String fc = "org.hibernate.dialect.MimerSQLDialect"; + String groupIdFilter = "asdf.asdf.asdf"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection artifacts = locator.locate(fc, groupIdFilter, false); + + assertNotNull("Null returned!", artifacts); + assertTrue("No artifacts expected for manual groupId filter "+groupIdFilter+"!", artifacts.isEmpty()); + } + + @Test + public void testLocateArtifactByIncludedPackageWrongAutoGid() { + String fc = "org.hibernate.dialect.MimerSQLDialect"; + String groupIdFilter = "asdf"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection artifacts = locator.locate(fc, groupIdFilter, false); + + assertNotNull("Null returned!", artifacts); + assertTrue("No artifacts expected for manual groupId filter "+groupIdFilter+"!", artifacts.isEmpty()); + } + + @Test + public void testLocateArtifactVersionFilter() { + String groupId = "org.hibernate"; + String artifactId = "hibernate-core"; + String lowestVersion = "3.3.0.CR1"; + String highestVersion = "5.2.10.Final"; + + CentralMavenRestLocator locator = new CentralMavenRestLocator(); + Collection foundArtifacts = locator.locate(groupId, artifactId); + assertNotNull("Null returned!", foundArtifacts); + Collection lowestVersions = locator.filter(foundArtifacts, VersionFilter.LOWEST_ONLY); + Collection highestVersions = locator.filter(foundArtifacts, VersionFilter.HIGHEST_ONLY); + + assertEquals("Only 1 artifact in lowestVersions expected!", 1, lowestVersions.size()); + FoundArtifact fa = lowestVersions.iterator().next(); + assertEquals("Wrong groupId of lowest version!", groupId, fa.getGroupId()); + assertEquals("Wrong artifactId of lowest version!", artifactId, fa.getArtifactId()); + assertEquals("Wrong version of lowest version!", lowestVersion, fa.getVersion()); + + assertEquals("Only 1 artifact in highestVersions expected!", 1, highestVersions.size()); + fa = highestVersions.iterator().next(); + assertEquals("Wrong groupId of highest version!", groupId, fa.getGroupId()); + assertEquals("Wrong artifactId of highest version!", artifactId, fa.getArtifactId()); + assertEquals("Wrong version of highest version!", highestVersion, fa.getVersion()); + } + +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumerTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumerTest.java new file mode 100644 index 00000000..27c02446 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/CentralRepoRestConsumerTest.java @@ -0,0 +1,35 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.json.CentralRepoJsonResponse; +import org.junit.Test; + +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * @author Zdenek Vales + */ +public class CentralRepoRestConsumerTest { + + @Test + public void testFindArtifacts() { + String g = "org.hibernate"; + String a = "hibernate-core"; + QueryBuilder qb = new QueryBuilder() + .addParameter(QueryParam.GROUP_ID, g) + .addParameter(QueryParam.ARTIFACT_ID, a) + .addAdditionalParameter(AdditionalQueryParam.CORE, "gav") + .addAdditionalParameter(AdditionalQueryParam.SERVICE, "json"); + + CentralRepoRestConsumer restConsumer = new CentralRepoRestConsumer(); + + Response response = restConsumer.sendRequest(qb); + assertEquals("Wrong response obtained for url: "+qb.toString()+" !", Response.Status.OK.getStatusCode(), response.getStatus()); + + CentralRepoJsonResponse jsonResponse = response.readEntity(CentralRepoJsonResponse.class); + assertTrue("No artifcat found!", jsonResponse.getResponse().getNumFound() > 0); + assertTrue("No artifacts loaded!", jsonResponse.getResponse().getDocs().length > 0); + } +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilderTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilderTest.java new file mode 100644 index 00000000..d0926f60 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/central/rest/QueryBuilderTest.java @@ -0,0 +1,43 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author Zdenek Vales + */ +public class QueryBuilderTest { + + @Test + public void testBuildQuery() { + String expected1 = "q=g:\"group-id\"+AND+a:\"artifact.some.id\"&core=gav&wt=json"; + String expected2 = "q=g:\"group-id\"+AND+a:\"artifact.some.id\"+AND+v:\"VERSION-1.0.1\"&core=gav&wt=json"; + String expected3 = "q=g:\"group-id\"+AND+a:\"artifact.some.id\"+AND+v:\"VERSION-1.0.2\"&core=gav&wt=json"; + + QueryBuilder qb = new QueryBuilder() + .addParameter(QueryParam.GROUP_ID, "group-id") + .addParameter(QueryParam.ARTIFACT_ID, "artifact.some.id") + .addAdditionalParameter(AdditionalQueryParam.CORE, "gav") + .addAdditionalParameter(AdditionalQueryParam.SERVICE, "json"); + assertEquals("Wrong query 1!", expected1, qb.toString()); + + qb.addParameter(QueryParam.VERSION, "VERSION-1.0.1"); + assertEquals("Wrong query 2!", expected2, qb.toString()); + + qb.addParameter(QueryParam.VERSION, "VERSION-1.0.2"); + assertEquals("Wrong query 2!", expected3, qb.toString()); + } + + @Test + public void testBuildStandardQuery() { + String expected2 = "q=g:\"group-id\"+AND+a:\"artifact.some.id\"+AND+v:\"VERSION-1.0.1\"&core=gav&wt=json"; + String expected3 = "q=g:\"group-id\"+AND+a:\"artifact.some.id\"+AND+v:\"VERSION-1.0.2\"&core=gav&wt=json"; + + QueryBuilder qb = QueryBuilder.createStandard("group-id", "artifact.some.id", "VERSION-1.0.1"); + assertEquals("Wrong query 2!", expected2, qb.toString()); + + qb.addParameter(QueryParam.VERSION, "VERSION-1.0.2"); + assertEquals("Wrong query 2!", expected3, qb.toString()); + } +} diff --git a/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolverTest.java b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolverTest.java new file mode 100644 index 00000000..5950fe52 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/java/cz/zcu/kiv/crce/mvn/plugin/search/impl/resolver/MavenAetherResolverTest.java @@ -0,0 +1,127 @@ +package cz.zcu.kiv.crce.mvn.plugin.search.impl.resolver; + +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenResolver; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.CentralMavenRestLocator; +import org.eclipse.aether.repository.RemoteRepository; +import org.junit.Test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.*; + +/** + * Created by valesz on 13.04.2017. + */ +public class MavenAetherResolverTest { + + @Test + public void testReconfigure3() throws FileNotFoundException { + MavenAetherResolver resolver = new MavenAetherResolver(); + File f = new File(getClass().getResource("/mavenAetherLocatorTest.properties").getPath()); + + // default config + List repositories = resolver.getRepositories(); + assertEquals("Only one remote repository expected to be configured!", 1, repositories.size()); + RemoteRepository repo = repositories.get(0); + assertEquals(repo.getId(), MavenAetherResolver.REPOSITORY_ID_DEF); + assertEquals(repo.getContentType(), MavenAetherResolver.REPOSITORY_TYPE_DEF); + assertEquals(repo.getUrl(), MavenAetherResolver.REPOSITORY_URL_DEF); + assertEquals(resolver.getLocalRepoPath(), MavenAetherResolver.LOCAL_REPOSITORY_PATH_DEF); + + // new config with null file => should be default + resolver.reconfigure((File)null); + repositories = resolver.getRepositories(); + assertEquals("Only one remote repository expected to be configured!", 1, repositories.size()); + repo = repositories.get(0); + assertEquals(repo.getId(), MavenAetherResolver.REPOSITORY_ID_DEF); + assertEquals(repo.getContentType(), MavenAetherResolver.REPOSITORY_TYPE_DEF); + assertEquals(repo.getUrl(), MavenAetherResolver.REPOSITORY_URL_DEF); + assertEquals(resolver.getLocalRepoPath(), MavenAetherResolver.LOCAL_REPOSITORY_PATH_DEF); + + } + + @Test(expected = FileNotFoundException.class) + public void testReconfigure2() throws FileNotFoundException { + MavenAetherResolver resolver = new MavenAetherResolver(); + + // default config + List repositories = resolver.getRepositories(); + assertEquals("Only one remote repository expected to be configured!", 1, repositories.size()); + RemoteRepository repo = repositories.get(0); + assertEquals(repo.getId(), MavenAetherResolver.REPOSITORY_ID_DEF); + assertEquals(repo.getContentType(), MavenAetherResolver.REPOSITORY_TYPE_DEF); + assertEquals(repo.getUrl(), MavenAetherResolver.REPOSITORY_URL_DEF); + assertEquals(resolver.getLocalRepoPath(), MavenAetherResolver.LOCAL_REPOSITORY_PATH_DEF); + + // new config + resolver.reconfigure(new File("asasd")); + fail("Exception should have been thrown for non-existent file!"); + } + + @Test + public void testReconfigure() throws IOException { + MavenAetherResolver resolver = new MavenAetherResolver(); + File f = new File(getClass().getResource("/mavenAetherLocatorTest.properties").getPath()); + String repoIdFormat = "central-new-%d"; + String repoTypeFormat = "default-new-%d"; + String repoUrlFormat = "http://repo%d.maven.org/maven2/"; + + // default config + List repositories = resolver.getRepositories(); + assertEquals("Only one remote repository expected to be configured!", 1, repositories.size()); + RemoteRepository repo = repositories.get(0); + assertEquals(repo.getId(), MavenAetherResolver.REPOSITORY_ID_DEF); + assertEquals(repo.getContentType(), MavenAetherResolver.REPOSITORY_TYPE_DEF); + assertEquals(repo.getUrl(), MavenAetherResolver.REPOSITORY_URL_DEF); + assertEquals(resolver.getLocalRepoPath(), MavenAetherResolver.LOCAL_REPOSITORY_PATH_DEF); + + // new config + resolver.reconfigure(f); + assertEquals(resolver.getLocalRepoPath(),"d:/tools/develop/apache-maven/repository/"); + repositories = resolver.getRepositories(); + assertEquals("Three repositories expected to be configured!", 3, repositories.size()); + for (int i = 0; i < repositories.size(); i++) { + RemoteRepository r = repositories.get(i); + assertEquals("Wrong id of "+i+" repository!", String.format(repoIdFormat, i), r.getId()); + assertEquals("Wrong type of "+i+" repository!", String.format(repoTypeFormat, i), r.getContentType()); + assertEquals("Wrong id of "+i+" repository!", String.format(repoUrlFormat, i), r.getUrl()); + } + + } + + @Test + public void testResolve() { + MavenLocator mavenLocator = new CentralMavenRestLocator(); + MavenResolver mavenResolver = new MavenAetherResolver(); + + String groupId = "io.airlift"; + String artifactId = "airline"; + String version = "0.6"; + + FoundArtifact foundArtifact = mavenLocator.locate(groupId, artifactId, version); + assertNotNull("Artifact not located!", foundArtifact); + + File file = mavenResolver.resolve(foundArtifact); + assertNotNull("Artifact not resolved!", file); + assertTrue("Non existent file returned!", file.exists()); + } + + @Test + public void testResolve2() { + MavenLocator locator = new CentralMavenRestLocator(); + MavenResolver resolver = new MavenAetherResolver(); + String groupId = "org.hibernate"; + String artifactId = "hibernate-core"; + String version = "5.2.7.Final"; + + FoundArtifact artifact = locator.locate(groupId, artifactId, version); + File file = resolver.resolve(artifact); + assertNotNull("Artifact not reseolved!", file); + assertTrue("Non existent file returned!", file.exists()); + } +} diff --git a/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final-orig.jar b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final-orig.jar new file mode 100644 index 00000000..5150c1de Binary files /dev/null and b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final-orig.jar differ diff --git a/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final.jar b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final.jar new file mode 100644 index 00000000..5150c1de Binary files /dev/null and b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-5.2.7.Final.jar differ diff --git a/modules/crce-mvn-plugin/src/test/resources/hibernate-core-pom.xml b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-pom.xml new file mode 100644 index 00000000..8a91c1f7 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/resources/hibernate-core-pom.xml @@ -0,0 +1,106 @@ + + 4.0.0 + org.hibernate + hibernate-core + 5.2.7.Final + + + org.jboss.logging + jboss-logging + 3.3.0.Final + compile + + + org.hibernate.javax.persistence + hibernate-jpa-2.1-api + 1.0.0.Final + compile + + + org.javassist + javassist + 3.20.0-GA + compile + + + antlr + antlr + 2.7.7 + compile + + + org.apache.geronimo.specs + geronimo-jta_1.1_spec + 1.1.1 + compile + + + org.jboss + jandex + 2.0.3.Final + compile + + + com.fasterxml + classmate + 1.3.0 + compile + + + dom4j + dom4j + 1.6.1 + compile + + + * + * + + + + + org.hibernate.common + hibernate-commons-annotations + 5.0.1.Final + compile + + + Core Hibernate O/RM functionality + + The core O/RM functionality as provided by Hibernate + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl-2.1.html + + See discussion at http://hibernate.org/license for more details. + + repo + + + http://hibernate.org + + Hibernate.org + http://hibernate.org + + + jira + https://hibernate.atlassian.net/browse/HHH + + + http://github.com/hibernate/hibernate-orm + + scm:git:http://github.com/hibernate/hibernate-orm.git + + scm:git:git@github.com:hibernate/hibernate-orm.git + + + + hibernate-team + The Hibernate Development Team + Hibernate.org + http://hibernate.org + + + \ No newline at end of file diff --git a/modules/crce-mvn-plugin/src/test/resources/mavenAetherLocatorTest.properties b/modules/crce-mvn-plugin/src/test/resources/mavenAetherLocatorTest.properties new file mode 100644 index 00000000..14b79524 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/resources/mavenAetherLocatorTest.properties @@ -0,0 +1,13 @@ +# configuration of maven aether resolver +repository.local.path=d:/tools/develop/apache-maven/repository/ +repository0.id=central-new-0 +repository0.type=default-new-0 +repository0.url=http://repo0.maven.org/maven2/ + +repository1.id=central-new-1 +repository1.type=default-new-1 +repository1.url=http://repo1.maven.org/maven2/ + +repository2.id=central-new-2 +repository2.type=default-new-2 +repository2.url=http://repo2.maven.org/maven2/ diff --git a/modules/crce-mvn-plugin/src/test/resources/pom.xml b/modules/crce-mvn-plugin/src/test/resources/pom.xml new file mode 100644 index 00000000..12ab7082 --- /dev/null +++ b/modules/crce-mvn-plugin/src/test/resources/pom.xml @@ -0,0 +1,10 @@ + + 4.0.0 + org.zcu.thesis + thesis + 0.1 + jar + + + + diff --git a/modules/crce-mvn-plugin/src/test/resources/test-hibernate-core b/modules/crce-mvn-plugin/src/test/resources/test-hibernate-core new file mode 100644 index 00000000..5150c1de Binary files /dev/null and b/modules/crce-mvn-plugin/src/test/resources/test-hibernate-core differ diff --git a/modules/crce-mvn-plugin/src/test/resources/test-jar.jar b/modules/crce-mvn-plugin/src/test/resources/test-jar.jar new file mode 100644 index 00000000..bbcf4421 Binary files /dev/null and b/modules/crce-mvn-plugin/src/test/resources/test-jar.jar differ diff --git a/modules/crce-repository-maven-impl/osgi.bnd b/modules/crce-repository-maven-impl/osgi.bnd index 427b5f1d..10e88734 100644 --- a/modules/crce-repository-maven-impl/osgi.bnd +++ b/modules/crce-repository-maven-impl/osgi.bnd @@ -1,26 +1,26 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Export-Package: - -Import-Package:\ - !org.apache.lucene.*,\ - !de.schlichtherle.*,\ - !org.apache.maven.*,\ - !org.sonatype.aether.*,\ - !junit.framework,\ - * - -Embed-Dependency:\ - indexer-artifact,\ - indexer-core,\ - lucene-core,\ - groupId=org.sonatype.aether;artifactId=aether-api,\ - groupId=org.sonatype.aether;artifactId=aether-util,\ - maven-aether-provider,\ - maven-model,\ - maven-model-builder,\ - maven-repository-metadata +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Export-Package: + +Import-Package:\ + !org.apache.lucene.*,\ + !de.schlichtherle.*,\ + !org.apache.maven.*,\ + !org.sonatype.aether.*,\ + !junit.framework,\ + * + +Embed-Dependency:\ + indexer-artifact,\ + indexer-core,\ + lucene-core,\ + groupId=org.sonatype.aether;artifactId=aether-api,\ + groupId=org.sonatype.aether;artifactId=aether-util,\ + maven-aether-provider,\ + maven-model,\ + maven-model-builder,\ + maven-repository-metadata diff --git a/modules/crce-repository-maven-impl/pom.xml b/modules/crce-repository-maven-impl/pom.xml index 33009a8e..975fafab 100644 --- a/modules/crce-repository-maven-impl/pom.xml +++ b/modules/crce-repository-maven-impl/pom.xml @@ -1,251 +1,251 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-repository-maven-impl - bundle - - CRCE - Maven Repository Implementation - - - ${namespace}.repository.maven.impl - ${namespace}.repository.maven - 5.1.1 - 0.9.1.v20140329 - 3.2.1 - true - - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - - - - - - - - - - org.apache.felix - org.osgi.service.obr - - - - - - commons-io - commons-io - - - - org.eclipse.sisu - org.eclipse.sisu.plexus - 0.2.1 - - - org.codehaus.plexus - plexus-classworlds - - - - - - org.eclipse.sisu - org.eclipse.sisu.inject - 0.2.1 - - - org.sonatype.sisu - sisu-guice - 3.2.1 - - - org.codehaus.plexus - plexus-classworlds - 2.5.1 - - - com.google.inject - guice - 3.0 - - - - org.eclipse.aether - aether-api - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-impl - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-spi - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-connector-basic - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-transport-file - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-transport-http - ${version.org.eclipse.aether} - - - org.eclipse.aether - aether-util - ${version.org.eclipse.aether} - - - - - - - cz.zcu.kiv.crce.wrapper - org.apache.httpcomponents.httpclient - 4.2.6 - - - cz.zcu.kiv.crce.wrapper - org.apache.httpcomponents.httpcore - 4.2.5 - - - cz.zcu.kiv.crce.wrapper - org.codehaus.plexus.plexus-utils - 3.0.17 - - - cz.zcu.kiv.crce.wrapper - org.codehaus.plexus.plexus-interpolation - 1.19 - - - cz.zcu.kiv.crce.wrapper - org.codehaus.plexus.plexus-component-annotations - 1.5.5 - - - - - - org.apache.maven.indexer - indexer-artifact - ${version.org.apache.maven.indexer} - - - org.apache.maven.indexer - indexer-core - ${version.org.apache.maven.indexer} - - - org.apache.maven - maven-model - ${version.org.apache.maven} - - - org.apache.maven - maven-model-builder - ${version.org.apache.maven} - - - org.apache.maven - maven-aether-provider - ${version.org.apache.maven} - - - org.apache.maven - maven-repository-metadata - ${version.org.apache.maven} - - - org.apache.lucene - lucene-core - 3.6.2 - - - org.glassfish.hk2.external - javax.inject - 2.2.0 - - - - org.sonatype.aether - aether-api - 1.13.1 - - - org.sonatype.aether - aether-util - 1.13.1 - - - - - - ${project.groupId} - crce-core - pom - - - - ${project.groupId} - crce-concurrency - ${project.version} - - - - - - junit - junit - - - org.apache.felix.dependencymanager.annotation - org.apache.felix - - - maven-project - org.apache.maven - - - - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-repository-maven-impl + bundle + + CRCE - Maven Repository Implementation + + + ${namespace}.repository.maven.impl + ${namespace}.repository.maven + 5.1.1 + 0.9.1.v20140329 + 3.2.1 + true + + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + + + + + + + + + + org.apache.felix + org.osgi.service.obr + + + + + + commons-io + commons-io + + + + org.eclipse.sisu + org.eclipse.sisu.plexus + 0.2.1 + + + org.codehaus.plexus + plexus-classworlds + + + + + + org.eclipse.sisu + org.eclipse.sisu.inject + 0.2.1 + + + org.sonatype.sisu + sisu-guice + 3.2.1 + + + org.codehaus.plexus + plexus-classworlds + 2.5.1 + + + com.google.inject + guice + 3.0 + + + + org.eclipse.aether + aether-api + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-impl + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-spi + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-connector-basic + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-transport-file + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-transport-http + ${version.org.eclipse.aether} + + + org.eclipse.aether + aether-util + ${version.org.eclipse.aether} + + + + + + + cz.zcu.kiv.crce.wrapper + org.apache.httpcomponents.httpclient + 4.2.6 + + + cz.zcu.kiv.crce.wrapper + org.apache.httpcomponents.httpcore + 4.2.5 + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-utils + 3.0.17 + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-interpolation + 1.19 + + + cz.zcu.kiv.crce.wrapper + org.codehaus.plexus.plexus-component-annotations + 1.5.5 + + + + + + org.apache.maven.indexer + indexer-artifact + ${version.org.apache.maven.indexer} + + + org.apache.maven.indexer + indexer-core + ${version.org.apache.maven.indexer} + + + org.apache.maven + maven-model + ${version.org.apache.maven} + + + org.apache.maven + maven-model-builder + ${version.org.apache.maven} + + + org.apache.maven + maven-aether-provider + ${version.org.apache.maven} + + + org.apache.maven + maven-repository-metadata + ${version.org.apache.maven} + + + org.apache.lucene + lucene-core + 3.6.2 + + + org.glassfish.hk2.external + javax.inject + 2.2.0 + + + + org.sonatype.aether + aether-api + 1.13.1 + + + org.sonatype.aether + aether-util + 1.13.1 + + + + + + ${project.groupId} + crce-core + pom + + + + ${project.groupId} + crce-concurrency + ${project.version} + + + + + + junit + junit + + + org.apache.felix.dependencymanager.annotation + org.apache.felix + + + maven-project + org.apache.maven + + + + + + + \ No newline at end of file diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/Activator.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/Activator.java index 13e41164..13f9f161 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/Activator.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/Activator.java @@ -1,172 +1,172 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Dictionary; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.felix.dm.Component; -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedServiceFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * Activator of this bundle. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Activator extends DependencyActivatorBase implements ManagedServiceFactory { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - public static final String PID = "cz.zcu.kiv.crce.repository.maven"; - - public static final String CFG_PROPERTY__STORE_URI = "store.uri"; - - /** - * PID to component. - */ - private final Map components = new HashMap<>(); - /** - * PID to URI. - */ - private final Map uris = new HashMap<>(); - - private volatile DependencyManager dependencyManager; /* injected by dependency manager */ - - @Override - public void init(BundleContext bc, DependencyManager dm) throws Exception { - logger.debug("Initializing maven repository."); - - Properties props = new Properties(); - props.put(Constants.SERVICE_PID, PID); - dm.add(createComponent() - .setInterface(ManagedServiceFactory.class.getName(), props) - .setImplementation(this) - ); - } - - @Override - public void destroy(BundleContext bc, DependencyManager dm) throws Exception { - for (Component component : components.values()) { - dependencyManager.remove(component); - } - logger.debug("Maven repository destroyed."); - } - - @Override - public String getName() { - return "Maven repository store factory."; - } - - @Override - public void updated(String pid, Dictionary properties) throws ConfigurationException { - logger.trace("ManagedServiceFactory updated with pid: {}", pid); - - if (properties == null) { - logger.warn("Repository ({}) configuration is empty!", pid); - return; - } - - logger.debug("Updating maven repository ({}) configuration: {}", properties); - - String path = (String) properties.get(CFG_PROPERTY__STORE_URI); - - URI uri; - File file = null; - try { - uri = new URI(path); - if (uri.getScheme() == null) { - file = new File(path); - uri = file.toURI(); - } else if ("file".equals(uri.getScheme())) { - file = new File(uri); - } else { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Unsupported URI scheme for filebased repository: " + uri.getScheme()); - } - } catch (URISyntaxException ex) { - logger.warn("Invalid URI syntax: " + path, ex); - file = new File(path); - uri = file.toURI(); - } - - final String absolutePath = file.getAbsolutePath(); - - logger.debug("Repository URI: {}, file: {}", uri, absolutePath); - - if (!file.isDirectory()) { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Store URI is not a directory: " + path); - } - - for (Map.Entry entry : uris.entrySet()) { - if (entry.getValue().equals(absolutePath) && !entry.getKey().equals(pid)) { - throw new ConfigurationException(CFG_PROPERTY__STORE_URI, - "Another repository (PID: " + entry.getKey() + ") is already configured for this path: " + absolutePath); - } - } - - String oldPath = uris.get(pid); - if (oldPath != null) { - if (oldPath.equals(absolutePath)) { - logger.debug("Repository (PID: {}) is already configured for this path: {}", pid, absolutePath); - return; - } else { - deleted(pid); - } - } - - Properties props = new Properties(); - props.put("id", pid); - props.put("name", "Maven: " + uri); - - Component storeComponent = createComponent() - .setInterface(Store.class.getName(), props) - .setImplementation(new MavenStoreImpl(uri)) -// .add(dependencyManager.createConfigurationDependency().setPid(pid).setPropagate(true)) - .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceDAO.class)) - .add(createServiceDependency().setRequired(true).setService(RepositoryDAO.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataValidator.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceLoader.class)) - .add(createServiceDependency().setRequired(true).setService(IdentityIndexer.class)) - .add(createServiceDependency().setRequired(true).setService(ResourceIndexerService.class)) - .add(createServiceDependency().setRequired(true).setService(TaskRunnerService.class)); - - logger.debug("Registering repository store: {}", storeComponent); - - uris.put(pid, absolutePath); - components.put(pid, storeComponent); - dependencyManager.add(storeComponent); - } - - @Override - public void deleted(String pid) { - Component storeComponent = components.remove(pid); - if (storeComponent != null) { - logger.debug("Unregistering repository store: {}", storeComponent); - - dependencyManager.remove(storeComponent); - uris.remove(pid); - } - } -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.felix.dm.Component; +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.service.cm.ConfigurationException; +import org.osgi.service.cm.ManagedServiceFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * Activator of this bundle. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Activator extends DependencyActivatorBase implements ManagedServiceFactory { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + public static final String PID = "cz.zcu.kiv.crce.repository.maven"; + + public static final String CFG_PROPERTY__STORE_URI = "store.uri"; + + /** + * PID to component. + */ + private final Map components = new HashMap<>(); + /** + * PID to URI. + */ + private final Map uris = new HashMap<>(); + + private volatile DependencyManager dependencyManager; /* injected by dependency manager */ + + @Override + public void init(BundleContext bc, DependencyManager dm) throws Exception { + logger.debug("Initializing maven repository."); + + Properties props = new Properties(); + props.put(Constants.SERVICE_PID, PID); + dm.add(createComponent() + .setInterface(ManagedServiceFactory.class.getName(), props) + .setImplementation(this) + ); + } + + @Override + public void destroy(BundleContext bc, DependencyManager dm) throws Exception { + for (Component component : components.values()) { + dependencyManager.remove(component); + } + logger.debug("Maven repository destroyed."); + } + + @Override + public String getName() { + return "Maven repository store factory."; + } + + @Override + public void updated(String pid, Dictionary properties) throws ConfigurationException { + logger.trace("ManagedServiceFactory updated with pid: {}", pid); + + if (properties == null) { + logger.warn("Repository ({}) configuration is empty!", pid); + return; + } + + logger.debug("Updating maven repository ({}) configuration: {}", properties); + + String path = (String) properties.get(CFG_PROPERTY__STORE_URI); + + URI uri; + File file = null; + try { + uri = new URI(path); + if (uri.getScheme() == null) { + file = new File(path); + uri = file.toURI(); + } else if ("file".equals(uri.getScheme())) { + file = new File(uri); + } else { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Unsupported URI scheme for filebased repository: " + uri.getScheme()); + } + } catch (URISyntaxException ex) { + logger.warn("Invalid URI syntax: " + path, ex); + file = new File(path); + uri = file.toURI(); + } + + final String absolutePath = file.getAbsolutePath(); + + logger.debug("Repository URI: {}, file: {}", uri, absolutePath); + + if (!file.isDirectory()) { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, "Store URI is not a directory: " + path); + } + + for (Map.Entry entry : uris.entrySet()) { + if (entry.getValue().equals(absolutePath) && !entry.getKey().equals(pid)) { + throw new ConfigurationException(CFG_PROPERTY__STORE_URI, + "Another repository (PID: " + entry.getKey() + ") is already configured for this path: " + absolutePath); + } + } + + String oldPath = uris.get(pid); + if (oldPath != null) { + if (oldPath.equals(absolutePath)) { + logger.debug("Repository (PID: {}) is already configured for this path: {}", pid, absolutePath); + return; + } else { + deleted(pid); + } + } + + Properties props = new Properties(); + props.put("id", pid); + props.put("name", "Maven: " + uri); + + Component storeComponent = createComponent() + .setInterface(Store.class.getName(), props) + .setImplementation(new MavenStoreImpl(uri)) +// .add(dependencyManager.createConfigurationDependency().setPid(pid).setPropagate(true)) + .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceDAO.class)) + .add(createServiceDependency().setRequired(true).setService(RepositoryDAO.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataValidator.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceLoader.class)) + .add(createServiceDependency().setRequired(true).setService(IdentityIndexer.class)) + .add(createServiceDependency().setRequired(true).setService(ResourceIndexerService.class)) + .add(createServiceDependency().setRequired(true).setService(TaskRunnerService.class)); + + logger.debug("Registering repository store: {}", storeComponent); + + uris.put(pid, absolutePath); + components.put(pid, storeComponent); + dependencyManager.add(storeComponent); + } + + @Override + public void deleted(String pid) { + Component storeComponent = components.remove(pid); + if (storeComponent != null) { + logger.debug("Unregistering repository store: {}", storeComponent); + + dependencyManager.remove(storeComponent); + uris.remove(pid); + } + } +} diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/CloseableIndexingContext.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/CloseableIndexingContext.java index 2d59bff8..c22f3336 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/CloseableIndexingContext.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/CloseableIndexingContext.java @@ -1,221 +1,221 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Set; - -import org.apache.lucene.analysis.Analyzer; -import org.apache.lucene.index.IndexWriter; -import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.store.Directory; -import org.apache.maven.index.Indexer; -import org.apache.maven.index.artifact.GavCalculator; -import org.apache.maven.index.context.DocumentFilter; -import org.apache.maven.index.context.IndexCreator; -import org.apache.maven.index.context.IndexingContext; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class CloseableIndexingContext implements IndexingContext, Closeable { - - private final IndexingContext delegate; - private final Indexer indexer; - private boolean closed; - - public CloseableIndexingContext(IndexingContext delegate, Indexer indexer) { - this.delegate = delegate; - this.indexer = indexer; - } - - @Override - public String getId() { - return delegate.getId(); - } - - @Override - public String getRepositoryId() { - return delegate.getRepositoryId(); - } - - @Override - public File getRepository() { - return delegate.getRepository(); - } - - @Override - public String getRepositoryUrl() { - return delegate.getRepositoryUrl(); - } - - @Override - public String getIndexUpdateUrl() { - return delegate.getIndexUpdateUrl(); - } - - @Override - public boolean isSearchable() { - return delegate.isSearchable(); - } - - @Override - public void setSearchable(boolean searchable) { - delegate.setSearchable(searchable); - } - - @Override - public Date getTimestamp() { - return delegate.getTimestamp(); - } - - @Override - public void updateTimestamp() throws IOException { - delegate.updateTimestamp(); - } - - @Override - public void updateTimestamp(boolean save) throws IOException { - delegate.updateTimestamp(save); - } - - @Override - public void updateTimestamp(boolean save, Date date) throws IOException { - delegate.updateTimestamp(save, date); - } - - @Override - public int getSize() throws IOException { - return delegate.getSize(); - } - - @Override - public IndexSearcher acquireIndexSearcher() throws IOException { - return delegate.acquireIndexSearcher(); - } - - @Override - public void releaseIndexSearcher(IndexSearcher s) throws IOException { - delegate.releaseIndexSearcher(s); - } - - @Override - public IndexWriter getIndexWriter() throws IOException { - return delegate.getIndexWriter(); - } - - @Override - public List getIndexCreators() { - return delegate.getIndexCreators(); - } - - @Override - public Analyzer getAnalyzer() { - return delegate.getAnalyzer(); - } - - @Override - public void commit() throws IOException { - delegate.commit(); - } - - @Override - public void rollback() throws IOException { - delegate.rollback(); - } - - @Override - public void optimize() throws IOException { - delegate.optimize(); - } - - @Override - public void close(boolean deleteFiles) throws IOException { - delegate.close(deleteFiles); - } - - @Override - public void purge() throws IOException { - delegate.purge(); - } - - @Override - public void merge(Directory directory) throws IOException { - delegate.merge(directory); - } - - @Override - public void merge(Directory directory, DocumentFilter filter) throws IOException { - delegate.merge(directory, filter); - } - - @Override - public void replace(Directory directory) throws IOException { - delegate.replace(directory); - } - - @Override - public Directory getIndexDirectory() { - return delegate.getIndexDirectory(); - } - - @Override - public File getIndexDirectoryFile() { - return delegate.getIndexDirectoryFile(); - } - - @Override - public GavCalculator getGavCalculator() { - return delegate.getGavCalculator(); - } - - @Override - public void setAllGroups(Collection groups) throws IOException { - delegate.setAllGroups(groups); - } - - @Override - public Set getAllGroups() throws IOException { - return delegate.getAllGroups(); - } - - @Override - public void setRootGroups(Collection groups) throws IOException { - delegate.setRootGroups(groups); - } - - @Override - public Set getRootGroups() throws IOException { - return delegate.getRootGroups(); - } - - @Override - public void rebuildGroups() throws IOException { - delegate.rebuildGroups(); - } - - @Override - public boolean isReceivingUpdates() { - return delegate.isReceivingUpdates(); - } - - @Override - public void close() throws IOException { - if (!closed) { - if (indexer != null) { - indexer.closeIndexingContext(delegate, false); - } else { - delegate.close(true); - } - closed = true; - } - } - - public Indexer getIndexer() { - return indexer; - } -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.store.Directory; +import org.apache.maven.index.Indexer; +import org.apache.maven.index.artifact.GavCalculator; +import org.apache.maven.index.context.DocumentFilter; +import org.apache.maven.index.context.IndexCreator; +import org.apache.maven.index.context.IndexingContext; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class CloseableIndexingContext implements IndexingContext, Closeable { + + private final IndexingContext delegate; + private final Indexer indexer; + private boolean closed; + + public CloseableIndexingContext(IndexingContext delegate, Indexer indexer) { + this.delegate = delegate; + this.indexer = indexer; + } + + @Override + public String getId() { + return delegate.getId(); + } + + @Override + public String getRepositoryId() { + return delegate.getRepositoryId(); + } + + @Override + public File getRepository() { + return delegate.getRepository(); + } + + @Override + public String getRepositoryUrl() { + return delegate.getRepositoryUrl(); + } + + @Override + public String getIndexUpdateUrl() { + return delegate.getIndexUpdateUrl(); + } + + @Override + public boolean isSearchable() { + return delegate.isSearchable(); + } + + @Override + public void setSearchable(boolean searchable) { + delegate.setSearchable(searchable); + } + + @Override + public Date getTimestamp() { + return delegate.getTimestamp(); + } + + @Override + public void updateTimestamp() throws IOException { + delegate.updateTimestamp(); + } + + @Override + public void updateTimestamp(boolean save) throws IOException { + delegate.updateTimestamp(save); + } + + @Override + public void updateTimestamp(boolean save, Date date) throws IOException { + delegate.updateTimestamp(save, date); + } + + @Override + public int getSize() throws IOException { + return delegate.getSize(); + } + + @Override + public IndexSearcher acquireIndexSearcher() throws IOException { + return delegate.acquireIndexSearcher(); + } + + @Override + public void releaseIndexSearcher(IndexSearcher s) throws IOException { + delegate.releaseIndexSearcher(s); + } + + @Override + public IndexWriter getIndexWriter() throws IOException { + return delegate.getIndexWriter(); + } + + @Override + public List getIndexCreators() { + return delegate.getIndexCreators(); + } + + @Override + public Analyzer getAnalyzer() { + return delegate.getAnalyzer(); + } + + @Override + public void commit() throws IOException { + delegate.commit(); + } + + @Override + public void rollback() throws IOException { + delegate.rollback(); + } + + @Override + public void optimize() throws IOException { + delegate.optimize(); + } + + @Override + public void close(boolean deleteFiles) throws IOException { + delegate.close(deleteFiles); + } + + @Override + public void purge() throws IOException { + delegate.purge(); + } + + @Override + public void merge(Directory directory) throws IOException { + delegate.merge(directory); + } + + @Override + public void merge(Directory directory, DocumentFilter filter) throws IOException { + delegate.merge(directory, filter); + } + + @Override + public void replace(Directory directory) throws IOException { + delegate.replace(directory); + } + + @Override + public Directory getIndexDirectory() { + return delegate.getIndexDirectory(); + } + + @Override + public File getIndexDirectoryFile() { + return delegate.getIndexDirectoryFile(); + } + + @Override + public GavCalculator getGavCalculator() { + return delegate.getGavCalculator(); + } + + @Override + public void setAllGroups(Collection groups) throws IOException { + delegate.setAllGroups(groups); + } + + @Override + public Set getAllGroups() throws IOException { + return delegate.getAllGroups(); + } + + @Override + public void setRootGroups(Collection groups) throws IOException { + delegate.setRootGroups(groups); + } + + @Override + public Set getRootGroups() throws IOException { + return delegate.getRootGroups(); + } + + @Override + public void rebuildGroups() throws IOException { + delegate.rebuildGroups(); + } + + @Override + public boolean isReceivingUpdates() { + return delegate.isReceivingUpdates(); + } + + @Override + public void close() throws IOException { + if (!closed) { + if (indexer != null) { + indexer.closeIndexingContext(delegate, false); + } else { + delegate.close(true); + } + closed = true; + } + } + + public Indexer getIndexer() { + return indexer; + } +} diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/IdentityIndexer.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/IdentityIndexer.java index aafbc5da..e4d27cb5 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/IdentityIndexer.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/IdentityIndexer.java @@ -1,89 +1,89 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.apache.felix.dm.annotation.api.Component; -import org.apache.felix.dm.annotation.api.ServiceDependency; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.service.MetadataService; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@Component(provides = IdentityIndexer.class) -public class IdentityIndexer { - - private static final Logger logger = LoggerFactory.getLogger(IdentityIndexer.class); - - private static final String MIME__APPLICATION_OCTET_STREAM = "application/octet-stream"; - - - @ServiceDependency private volatile MetadataService metadataService; - - public void preIndex(File file, String name, Resource resource) { - Capability identity = metadataService.getIdentity(resource); - - metadataService.setUri(resource, file.toURI().normalize()); - metadataService.setFileName(resource, name); - - identity.setAttribute("original-file-name", String.class, name); // TODO hardcoded - } - - public void postIndex(File file, Resource resource) { - Capability identity = metadataService.getIdentity(resource); - - metadataService.setSize(resource, file.length()); - String hash = getSHA(file); - if (hash != null) { - identity.setAttribute("hash", String.class, hash); // TODO hardcoded - } - - SimpleAttributeType mime = new SimpleAttributeType<>("mime", String.class); // TODO hardcoded - Attribute attribute = identity.getAttribute(mime); - if (attribute == null) { - identity.setAttribute(mime, MIME__APPLICATION_OCTET_STREAM); - } - } - - /** - * Get hexadecimal SHA-256 of file with resource or null, if error occurred during counting digest. - * - * @param file - * @return hexadecimal SHA-256 of file with resource or null - */ - private String getSHA(File file) { - try (FileInputStream fis = new FileInputStream(file)) { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - - byte[] buffer = new byte[10 * 1024]; - - int nread; - while ((nread = fis.read(buffer)) != -1) { - md.update(buffer, 0, nread); - } - byte[] mdbytes = md.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mdbytes.length; i++) { - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); // NOPMD better clarity - } - - return sb.toString(); - - } catch (NoSuchAlgorithmException | IOException e) { - logger.warn("Hash generation failed.", e); - return null; - } - } -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import org.apache.felix.dm.annotation.api.Component; +import org.apache.felix.dm.annotation.api.ServiceDependency; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.service.MetadataService; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@Component(provides = IdentityIndexer.class) +public class IdentityIndexer { + + private static final Logger logger = LoggerFactory.getLogger(IdentityIndexer.class); + + private static final String MIME__APPLICATION_OCTET_STREAM = "application/octet-stream"; + + + @ServiceDependency private volatile MetadataService metadataService; + + public void preIndex(File file, String name, Resource resource) { + Capability identity = metadataService.getIdentity(resource); + + metadataService.setUri(resource, file.toURI().normalize()); + metadataService.setFileName(resource, name); + + identity.setAttribute("original-file-name", String.class, name); // TODO hardcoded + } + + public void postIndex(File file, Resource resource) { + Capability identity = metadataService.getIdentity(resource); + + metadataService.setSize(resource, file.length()); + String hash = getSHA(file); + if (hash != null) { + identity.setAttribute("hash", String.class, hash); // TODO hardcoded + } + + SimpleAttributeType mime = new SimpleAttributeType<>("mime", String.class); // TODO hardcoded + Attribute attribute = identity.getAttribute(mime); + if (attribute == null) { + identity.setAttribute(mime, MIME__APPLICATION_OCTET_STREAM); + } + } + + /** + * Get hexadecimal SHA-256 of file with resource or null, if error occurred during counting digest. + * + * @param file + * @return hexadecimal SHA-256 of file with resource or null + */ + private String getSHA(File file) { + try (FileInputStream fis = new FileInputStream(file)) { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + + byte[] buffer = new byte[10 * 1024]; + + int nread; + while ((nread = fis.read(buffer)) != -1) { + md.update(buffer, 0, nread); + } + byte[] mdbytes = md.digest(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mdbytes.length; i++) { + sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); // NOPMD better clarity + } + + return sb.toString(); + + } catch (NoSuchAlgorithmException | IOException e) { + logger.warn("Hash generation failed.", e); + return null; + } + } +} diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/LocalRepositoryIndexer.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/LocalRepositoryIndexer.java index ecd274df..98cd5f6e 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/LocalRepositoryIndexer.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/LocalRepositoryIndexer.java @@ -1,263 +1,263 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.apache.lucene.search.BooleanClause; -import org.apache.lucene.search.BooleanQuery; -import org.apache.maven.index.ArtifactInfo; -import org.apache.maven.index.FlatSearchRequest; -import org.apache.maven.index.FlatSearchResponse; -import org.apache.maven.index.MAVEN; -import org.apache.maven.index.expr.SourcedSearchExpression; -import org.apache.maven.repository.internal.MavenRepositorySystemUtils; - -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.RepositorySystemSession; -import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; -import org.eclipse.aether.impl.DefaultServiceLocator; -import org.eclipse.aether.repository.LocalRepository; -import org.eclipse.aether.resolution.ArtifactRequest; -import org.eclipse.aether.resolution.ArtifactResult; -import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; -import org.eclipse.aether.spi.connector.transport.TransporterFactory; -import org.eclipse.aether.transport.file.FileTransporterFactory; -import org.eclipse.aether.transport.http.HttpTransporterFactory; - -import org.apache.lucene.store.FSDirectory; -import org.apache.maven.index.DefaultScannerListener; -import org.apache.maven.index.Indexer; -import org.apache.maven.index.IndexerEngine; -import org.apache.maven.index.Scanner; -import org.apache.maven.index.ScanningRequest; -import org.apache.maven.index.context.DefaultIndexingContext; -import org.apache.maven.index.context.IndexCreator; -import org.apache.maven.index.context.IndexUtils; -import org.apache.maven.index.context.IndexingContext; - -import org.codehaus.plexus.ContainerConfiguration; -import org.codehaus.plexus.DefaultContainerConfiguration; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.PlexusContainerException; -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.util.FileUtils; -import org.eclipse.aether.resolution.ArtifactResolutionException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.concurrency.model.Task; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class LocalRepositoryIndexer extends Task { - - private static final Logger logger = LoggerFactory.getLogger(LocalRepositoryIndexer.class); - - private final URI uri; - private final MetadataIndexerCallback metadataIndexerCallback; - - public LocalRepositoryIndexer(URI uri, MetadataIndexerCallback metadataIndexerCallback) { - super(uri.toString(), "Indexes local maven repository.", "crce-repository-maven-impl"); - this.uri = uri; - this.metadataIndexerCallback = metadataIndexerCallback; - } - - @Override - protected Object run() throws Exception { - logger.info("Indexing local Maven repository started: {}", uri); - - logger.debug("Updating Maven repository index."); - FlatSearchResponse response; - try (CloseableIndexingContext indexingContext = index("local", new File(uri), new File("target/mavenindex"), true)) { - Indexer indexer = indexingContext.getIndexer(); - - BooleanQuery query = new BooleanQuery(); - query.add(indexer.constructQuery(MAVEN.PACKAGING, new SourcedSearchExpression("bundle")), BooleanClause.Occur.MUST); - - response = indexer.searchFlat(new FlatSearchRequest(query, indexingContext)); - } catch (Exception e) { - logger.error("Error updating Maven repository index.", e); - return null; - } - logger.debug("Updating Maven repository index done."); - - RepositorySystem repositorySystem = newRepositorySystem(); - RepositorySystemSession session = newSession(repositorySystem, uri); - - logger.debug("Indexing artifacts (amount: {}).", response.getTotalHitsCount()); - - ArtifactRequest artifactRequest = new ArtifactRequest(); - for (ArtifactInfo ai : response.getResults()) { - artifactRequest.setArtifact(new DefaultArtifact(ai.groupId + ":" + ai.artifactId + ":" + ai.version)); - ArtifactResult result; - try { - result = repositorySystem.resolveArtifact(session, artifactRequest); - } catch (ArtifactResolutionException e) { - logger.info("Artifact is not present in local repository: " + artifactRequest.toString()); - // TODO optionally download the artifact from a remote repository - continue; - } - File artifact = result.getArtifact().getFile().getAbsoluteFile(); - - logger.trace("Indexing artifact {}", artifact); - - metadataIndexerCallback.index(artifact); - } - - logger.info("Indexing local Maven repository finished: {}", uri); - return null; - } - - - private static RepositorySystem newRepositorySystem() { - DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); - locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); - locator.addService(TransporterFactory.class, FileTransporterFactory.class); - locator.addService(TransporterFactory.class, HttpTransporterFactory.class); - - return locator.getService(RepositorySystem.class); - } - - private static RepositorySystemSession newSession(RepositorySystem system, URI uri) { - DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - - LocalRepository localRepo = new LocalRepository(new File(uri)); - session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); - - return session; - } - - - private CloseableIndexingContext index(String name, File repository, File indexParentDir, boolean update) - throws PlexusContainerException, ComponentLookupException, IOException { - logger.trace("Updating index '{}' at '{}' for local repo '{}', update: {}", name, indexParentDir, repository, update); - if (repository == null || indexParentDir == null) { - return null; - } - - if (!repository.exists()) { - throw new IOException("Repository directory " + repository + " does not exist"); - } - - if (!indexParentDir.exists() && !indexParentDir.mkdirs()) { - throw new IOException("Cannot create parent directory for indices: " + indexParentDir); - } - - logger.trace("Initializing Plexus container."); - - PlexusContainer plexusContainer; - Indexer indexer; - try { - ContainerConfiguration configuration = new DefaultContainerConfiguration(); - - ClassRealm classRealm = new ClassRealm(null, "crce-maven-repo-indexer", getClass().getClassLoader()); - configuration.setRealm(classRealm); - - plexusContainer = new DefaultPlexusContainer(configuration); - indexer = plexusContainer.lookup(Indexer.class); -// final IndexUpdater indexUpdater = plexusContainer.lookup(IndexUpdater.class); - } catch (Exception e) { - logger.error("Error initializing Plexus container.", e); - throw new IllegalStateException(e); - } - - List indexers = new ArrayList<>(); - indexers.add(plexusContainer.lookup(IndexCreator.class, "min")); -// indexers.add(plexusContainer.lookup(IndexCreator.class, "jarContent")); // indexes classes - - logger.trace("Creating indexing context."); - - IndexingContext indexingContext = indexer.createIndexingContext( - name + "-context", - name, - repository, - new File(indexParentDir, name), - null, - null, - true, - true, - indexers - ); - - // always use temporary context when reindexing - final File tmpFile = File.createTempFile(indexingContext.getId(), "-tmp", indexParentDir); - final File tmpDir = new File(indexParentDir, tmpFile.getName() + ".dir"); - if (!tmpDir.mkdirs()) { - throw new IOException("Cannot create temporary directory: " + tmpDir); - } - - logger.trace("Temporary dir: " + tmpDir); - - try { - Scanner scanner = plexusContainer.lookup(Scanner.class); - IndexerEngine indexerEngine = plexusContainer.lookup(IndexerEngine.class); - - final FSDirectory directory = FSDirectory.open(tmpDir); - if (update) { - IndexUtils.copyDirectory(indexingContext.getIndexDirectory(), directory); - } - - logger.trace("Creating temporary indexing context."); - - try (CloseableIndexingContext tmpContext = new CloseableIndexingContext( - new DefaultIndexingContext( - indexingContext.getId() + "-tmp", - indexingContext.getRepositoryId(), - indexingContext.getRepository(), - directory, - indexingContext.getRepositoryUrl(), - indexingContext.getIndexUpdateUrl(), - indexingContext.getIndexCreators(), - true - ), - null) - ) { - - logger.trace("Scanning."); - - ScanningRequest scanningRequest = new ScanningRequest( - tmpContext, - new DefaultScannerListener(tmpContext, indexerEngine, update, null), - null - ); - - scanner.scan(scanningRequest); - tmpContext.updateTimestamp(true); - - logger.trace("Replacing contexts."); - - indexingContext.replace(tmpContext.getIndexDirectory()); - } catch (Throwable t) { - logger.error("Error indexing local Maven repository 1.", t); - } - } catch (IOException | ComponentLookupException ex) { - logger.error("Error indexing local Maven repository 2.", ex); - throw new IOException("Error scanning context " + indexingContext.getId() + ": " + ex, ex); - } catch (Throwable t) { - logger.error("Error indexing local Maven repository 3.", t); - } finally { - try { - if (tmpFile.exists()) { - tmpFile.delete(); - } - } finally { - FileUtils.deleteDirectory(tmpDir); // TODO replace plexus utils - } - } - - logger.trace("Indexing done."); - - return new CloseableIndexingContext(indexingContext, indexer); - } - -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.maven.index.ArtifactInfo; +import org.apache.maven.index.FlatSearchRequest; +import org.apache.maven.index.FlatSearchResponse; +import org.apache.maven.index.MAVEN; +import org.apache.maven.index.expr.SourcedSearchExpression; +import org.apache.maven.repository.internal.MavenRepositorySystemUtils; + +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; +import org.eclipse.aether.impl.DefaultServiceLocator; +import org.eclipse.aether.repository.LocalRepository; +import org.eclipse.aether.resolution.ArtifactRequest; +import org.eclipse.aether.resolution.ArtifactResult; +import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; +import org.eclipse.aether.spi.connector.transport.TransporterFactory; +import org.eclipse.aether.transport.file.FileTransporterFactory; +import org.eclipse.aether.transport.http.HttpTransporterFactory; + +import org.apache.lucene.store.FSDirectory; +import org.apache.maven.index.DefaultScannerListener; +import org.apache.maven.index.Indexer; +import org.apache.maven.index.IndexerEngine; +import org.apache.maven.index.Scanner; +import org.apache.maven.index.ScanningRequest; +import org.apache.maven.index.context.DefaultIndexingContext; +import org.apache.maven.index.context.IndexCreator; +import org.apache.maven.index.context.IndexUtils; +import org.apache.maven.index.context.IndexingContext; + +import org.codehaus.plexus.ContainerConfiguration; +import org.codehaus.plexus.DefaultContainerConfiguration; +import org.codehaus.plexus.DefaultPlexusContainer; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.PlexusContainerException; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.codehaus.plexus.util.FileUtils; +import org.eclipse.aether.resolution.ArtifactResolutionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.concurrency.model.Task; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class LocalRepositoryIndexer extends Task { + + private static final Logger logger = LoggerFactory.getLogger(LocalRepositoryIndexer.class); + + private final URI uri; + private final MetadataIndexerCallback metadataIndexerCallback; + + public LocalRepositoryIndexer(URI uri, MetadataIndexerCallback metadataIndexerCallback) { + super(uri.toString(), "Indexes local maven repository.", "crce-repository-maven-impl"); + this.uri = uri; + this.metadataIndexerCallback = metadataIndexerCallback; + } + + @Override + protected Object run() throws Exception { + logger.info("Indexing local Maven repository started: {}", uri); + + logger.debug("Updating Maven repository index."); + FlatSearchResponse response; + try (CloseableIndexingContext indexingContext = index("local", new File(uri), new File("target/mavenindex"), true)) { + Indexer indexer = indexingContext.getIndexer(); + + BooleanQuery query = new BooleanQuery(); + query.add(indexer.constructQuery(MAVEN.PACKAGING, new SourcedSearchExpression("bundle")), BooleanClause.Occur.MUST); + + response = indexer.searchFlat(new FlatSearchRequest(query, indexingContext)); + } catch (Exception e) { + logger.error("Error updating Maven repository index.", e); + return null; + } + logger.debug("Updating Maven repository index done."); + + RepositorySystem repositorySystem = newRepositorySystem(); + RepositorySystemSession session = newSession(repositorySystem, uri); + + logger.debug("Indexing artifacts (amount: {}).", response.getTotalHitsCount()); + + ArtifactRequest artifactRequest = new ArtifactRequest(); + for (ArtifactInfo ai : response.getResults()) { + artifactRequest.setArtifact(new DefaultArtifact(ai.groupId + ":" + ai.artifactId + ":" + ai.version)); + ArtifactResult result; + try { + result = repositorySystem.resolveArtifact(session, artifactRequest); + } catch (ArtifactResolutionException e) { + logger.info("Artifact is not present in local repository: " + artifactRequest.toString()); + // TODO optionally download the artifact from a remote repository + continue; + } + File artifact = result.getArtifact().getFile().getAbsoluteFile(); + + logger.trace("Indexing artifact {}", artifact); + + metadataIndexerCallback.index(artifact); + } + + logger.info("Indexing local Maven repository finished: {}", uri); + return null; + } + + + private static RepositorySystem newRepositorySystem() { + DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); + locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); + locator.addService(TransporterFactory.class, FileTransporterFactory.class); + locator.addService(TransporterFactory.class, HttpTransporterFactory.class); + + return locator.getService(RepositorySystem.class); + } + + private static RepositorySystemSession newSession(RepositorySystem system, URI uri) { + DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); + + LocalRepository localRepo = new LocalRepository(new File(uri)); + session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); + + return session; + } + + + private CloseableIndexingContext index(String name, File repository, File indexParentDir, boolean update) + throws PlexusContainerException, ComponentLookupException, IOException { + logger.trace("Updating index '{}' at '{}' for local repo '{}', update: {}", name, indexParentDir, repository, update); + if (repository == null || indexParentDir == null) { + return null; + } + + if (!repository.exists()) { + throw new IOException("Repository directory " + repository + " does not exist"); + } + + if (!indexParentDir.exists() && !indexParentDir.mkdirs()) { + throw new IOException("Cannot create parent directory for indices: " + indexParentDir); + } + + logger.trace("Initializing Plexus container."); + + PlexusContainer plexusContainer; + Indexer indexer; + try { + ContainerConfiguration configuration = new DefaultContainerConfiguration(); + + ClassRealm classRealm = new ClassRealm(null, "crce-maven-repo-indexer", getClass().getClassLoader()); + configuration.setRealm(classRealm); + + plexusContainer = new DefaultPlexusContainer(configuration); + indexer = plexusContainer.lookup(Indexer.class); +// final IndexUpdater indexUpdater = plexusContainer.lookup(IndexUpdater.class); + } catch (Exception e) { + logger.error("Error initializing Plexus container.", e); + throw new IllegalStateException(e); + } + + List indexers = new ArrayList<>(); + indexers.add(plexusContainer.lookup(IndexCreator.class, "min")); +// indexers.add(plexusContainer.lookup(IndexCreator.class, "jarContent")); // indexes classes + + logger.trace("Creating indexing context."); + + IndexingContext indexingContext = indexer.createIndexingContext( + name + "-context", + name, + repository, + new File(indexParentDir, name), + null, + null, + true, + true, + indexers + ); + + // always use temporary context when reindexing + final File tmpFile = File.createTempFile(indexingContext.getId(), "-tmp", indexParentDir); + final File tmpDir = new File(indexParentDir, tmpFile.getName() + ".dir"); + if (!tmpDir.mkdirs()) { + throw new IOException("Cannot create temporary directory: " + tmpDir); + } + + logger.trace("Temporary dir: " + tmpDir); + + try { + Scanner scanner = plexusContainer.lookup(Scanner.class); + IndexerEngine indexerEngine = plexusContainer.lookup(IndexerEngine.class); + + final FSDirectory directory = FSDirectory.open(tmpDir); + if (update) { + IndexUtils.copyDirectory(indexingContext.getIndexDirectory(), directory); + } + + logger.trace("Creating temporary indexing context."); + + try (CloseableIndexingContext tmpContext = new CloseableIndexingContext( + new DefaultIndexingContext( + indexingContext.getId() + "-tmp", + indexingContext.getRepositoryId(), + indexingContext.getRepository(), + directory, + indexingContext.getRepositoryUrl(), + indexingContext.getIndexUpdateUrl(), + indexingContext.getIndexCreators(), + true + ), + null) + ) { + + logger.trace("Scanning."); + + ScanningRequest scanningRequest = new ScanningRequest( + tmpContext, + new DefaultScannerListener(tmpContext, indexerEngine, update, null), + null + ); + + scanner.scan(scanningRequest); + tmpContext.updateTimestamp(true); + + logger.trace("Replacing contexts."); + + indexingContext.replace(tmpContext.getIndexDirectory()); + } catch (Throwable t) { + logger.error("Error indexing local Maven repository 1.", t); + } + } catch (IOException | ComponentLookupException ex) { + logger.error("Error indexing local Maven repository 2.", ex); + throw new IOException("Error scanning context " + indexingContext.getId() + ": " + ex, ex); + } catch (Throwable t) { + logger.error("Error indexing local Maven repository 3.", t); + } finally { + try { + if (tmpFile.exists()) { + tmpFile.delete(); + } + } finally { + FileUtils.deleteDirectory(tmpDir); // TODO replace plexus utils + } + } + + logger.trace("Indexing done."); + + return new CloseableIndexingContext(indexingContext, indexer); + } + +} diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MavenStoreImpl.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MavenStoreImpl.java index 07889036..953e6b26 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MavenStoreImpl.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MavenStoreImpl.java @@ -1,160 +1,160 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Repository; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; -import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.repository.plugins.Executable; -import cz.zcu.kiv.crce.resolver.ResourceLoader; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class MavenStoreImpl implements Store { - - private static final Logger logger = LoggerFactory.getLogger(MavenStoreImpl.class); - - private volatile MetadataFactory metadataFactory; - private volatile RepositoryDAO repositoryDAO; - private volatile ResourceDAO resourceDAO; - private volatile TaskRunnerService taskRunnerService; - private volatile ResourceIndexerService resourceIndexerService; - private volatile ResourceLoader resourceLoader; - private volatile MetadataService metadataService; - private volatile IdentityIndexer identityIndexer; - private volatile MetadataValidator metadataValidator; - - private Repository repository; - private final URI baseUri; - - MavenStoreImpl(URI baseUri) { - this.baseUri = baseUri; - } - - @Override - public Resource put(Resource resource) throws IOException, RefusedArtifactException { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean remove(Resource resource) throws IOException { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getResources() { - try { - return resourceDAO.loadResources(repository); - } catch (IOException e) { - logger.error("Could not load resources of repository {}.", baseUri, e); - } - return Collections.emptyList(); - } - - @Override - public List getResources(Requirement requirement) { - List resources = Collections.emptyList(); - try { - resources = resourceLoader.getResources(repository, requirement); - } catch (IOException e) { - logger.error("Could not load resources for requirement ({})", requirement.getNamespace(), e); - } - - if (logger.isDebugEnabled()) { - logger.debug("getResources(requirement={}) returns {}", requirement.getNamespace(), resources.size()); - } - return resources; - } - - @Override - public void execute(List resources, Executable executable, Properties properties) { - throw new UnsupportedOperationException("Not supported yet."); - } - - - synchronized void start() { - try { - repository = repositoryDAO.loadRepository(baseUri); - } catch (IOException ex) { - logger.error("Could not load repository for {}", baseUri, ex); - } - - if (repository == null) { // TODO this is wrong when indexing fails - repository = metadataFactory.createRepository(baseUri); - try { - repositoryDAO.saveRepository(repository); - } catch (IOException ex) { - logger.error("Could not save repository for {}", baseUri, ex); - } - index(); - } - } - - void stop() { - logger.info("Stopping DM component {}", this); - } - - private void index() { - taskRunnerService.scheduleTask(new LocalRepositoryIndexer(baseUri, new MetadataIndexerCallback() { - - @Override - public void index(File file) { - try { - if (resourceIndexerService != null && !resourceDAO.existsResource(file.toURI())) { - Resource resource; - try { - resource = resourceIndexerService.indexResource(file); - } catch (IOException e) { - logger.error("Could not index file {}", file, e); - return; - } - metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); - - identityIndexer.preIndex(file, file.getName(), resource); - identityIndexer.postIndex(file, resource); - - ResourceValidationResult validationResult = metadataValidator.validate(resource); - if (!validationResult.isContextValid()) { - logger.error("Indexed Resource {} is not valid:\r\n{}", resource.getId(), validationResult); - return; - } - logger.info("Indexed resource {} is valid.", resource.getId()); - - try { - resourceDAO.saveResource(resource); - } catch (IOException e) { - logger.error("Could not save indexed resource for file {}: {}", file, resource, e); - } - } - } catch (IOException e) { - logger.error("Could not check that resource exists: {}", file, e); - } - } - })); - } - - @Override - public String toString() { - return "MavenStoreImpl{" + "baseUri=" + baseUri + '}'; - } -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.concurrency.service.TaskRunnerService; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Repository; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.dao.RepositoryDAO; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.indexer.ResourceIndexerService; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.service.validation.MetadataValidator; +import cz.zcu.kiv.crce.metadata.service.validation.ResourceValidationResult; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.repository.plugins.Executable; +import cz.zcu.kiv.crce.resolver.ResourceLoader; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class MavenStoreImpl implements Store { + + private static final Logger logger = LoggerFactory.getLogger(MavenStoreImpl.class); + + private volatile MetadataFactory metadataFactory; + private volatile RepositoryDAO repositoryDAO; + private volatile ResourceDAO resourceDAO; + private volatile TaskRunnerService taskRunnerService; + private volatile ResourceIndexerService resourceIndexerService; + private volatile ResourceLoader resourceLoader; + private volatile MetadataService metadataService; + private volatile IdentityIndexer identityIndexer; + private volatile MetadataValidator metadataValidator; + + private Repository repository; + private final URI baseUri; + + MavenStoreImpl(URI baseUri) { + this.baseUri = baseUri; + } + + @Override + public Resource put(Resource resource) throws IOException, RefusedArtifactException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean remove(Resource resource) throws IOException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getResources() { + try { + return resourceDAO.loadResources(repository); + } catch (IOException e) { + logger.error("Could not load resources of repository {}.", baseUri, e); + } + return Collections.emptyList(); + } + + @Override + public List getResources(Requirement requirement) { + List resources = Collections.emptyList(); + try { + resources = resourceLoader.getResources(repository, requirement); + } catch (IOException e) { + logger.error("Could not load resources for requirement ({})", requirement.getNamespace(), e); + } + + if (logger.isDebugEnabled()) { + logger.debug("getResources(requirement={}) returns {}", requirement.getNamespace(), resources.size()); + } + return resources; + } + + @Override + public void execute(List resources, Executable executable, Properties properties) { + throw new UnsupportedOperationException("Not supported yet."); + } + + + synchronized void start() { + try { + repository = repositoryDAO.loadRepository(baseUri); + } catch (IOException ex) { + logger.error("Could not load repository for {}", baseUri, ex); + } + + if (repository == null) { // TODO this is wrong when indexing fails + repository = metadataFactory.createRepository(baseUri); + try { + repositoryDAO.saveRepository(repository); + } catch (IOException ex) { + logger.error("Could not save repository for {}", baseUri, ex); + } + index(); + } + } + + void stop() { + logger.info("Stopping DM component {}", this); + } + + private void index() { + taskRunnerService.scheduleTask(new LocalRepositoryIndexer(baseUri, new MetadataIndexerCallback() { + + @Override + public void index(File file) { + try { + if (resourceIndexerService != null && !resourceDAO.existsResource(file.toURI())) { + Resource resource; + try { + resource = resourceIndexerService.indexResource(file); + } catch (IOException e) { + logger.error("Could not index file {}", file, e); + return; + } + metadataService.getIdentity(resource).setAttribute("repository-id", String.class, repository.getId()); + + identityIndexer.preIndex(file, file.getName(), resource); + identityIndexer.postIndex(file, resource); + + ResourceValidationResult validationResult = metadataValidator.validate(resource); + if (!validationResult.isContextValid()) { + logger.error("Indexed Resource {} is not valid:\r\n{}", resource.getId(), validationResult); + return; + } + logger.info("Indexed resource {} is valid.", resource.getId()); + + try { + resourceDAO.saveResource(resource); + } catch (IOException e) { + logger.error("Could not save indexed resource for file {}: {}", file, resource, e); + } + } + } catch (IOException e) { + logger.error("Could not check that resource exists: {}", file, e); + } + } + })); + } + + @Override + public String toString() { + return "MavenStoreImpl{" + "baseUri=" + baseUri + '}'; + } +} diff --git a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MetadataIndexerCallback.java b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MetadataIndexerCallback.java index e558d16e..35a87b54 100644 --- a/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MetadataIndexerCallback.java +++ b/modules/crce-repository-maven-impl/src/main/java/cz/zcu/kiv/crce/repository/maven/internal/MetadataIndexerCallback.java @@ -1,12 +1,12 @@ -package cz.zcu.kiv.crce.repository.maven.internal; - -import java.io.File; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface MetadataIndexerCallback { - - void index(File file); -} +package cz.zcu.kiv.crce.repository.maven.internal; + +import java.io.File; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface MetadataIndexerCallback { + + void index(File file); +} diff --git a/modules/crce-rest-v2/osgi.bnd b/modules/crce-rest-v2/osgi.bnd index fc1204f1..33ddd002 100644 --- a/modules/crce-rest-v2/osgi.bnd +++ b/modules/crce-rest-v2/osgi.bnd @@ -1,35 +1,35 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Version>: \ - ${pom.version} - -Bundle-SymbolicName: \ - ${bundle.symbolicName} - -Bundle-Name: CRCE - Rest V2 - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Import-Package: \ - !javax.annotation, \ - !org.apache.felix.dm.impl, \ - javax.servlet, \ - javax.servlet.http, \ - org.osgi.framework, \ - org.osgi.service.log, \ - org.osgi.service.useradmin, \ - org.glassfish.jersey.servlet, \ - cz.zcu.kiv.crce.repository, \ - * - -Export-Package: - -Dynamic-ImportPackage: * - -Bundle-ClassPath: .,WEB-INF/classes - -Web-ContextPath: rest/v2 - -Webapp-Context: rest/v2 +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Version>: \ + ${pom.version} + +Bundle-SymbolicName: \ + ${bundle.symbolicName} + +Bundle-Name: CRCE - Rest V2 + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Import-Package: \ + !javax.annotation, \ + !org.apache.felix.dm.impl, \ + javax.servlet, \ + javax.servlet.http, \ + org.osgi.framework, \ + org.osgi.service.log, \ + org.osgi.service.useradmin, \ + org.glassfish.jersey.servlet, \ + cz.zcu.kiv.crce.repository, \ + * + +Export-Package: + +Dynamic-ImportPackage: * + +Bundle-ClassPath: .,WEB-INF/classes + +Web-ContextPath: rest/v2 + +Webapp-Context: rest/v2 diff --git a/modules/crce-rest-v2/pom.xml b/modules/crce-rest-v2/pom.xml index b173521f..141f0b7f 100644 --- a/modules/crce-rest-v2/pom.xml +++ b/modules/crce-rest-v2/pom.xml @@ -1,164 +1,164 @@ - - - - ../pom - crce-modules-parent - cz.zcu.kiv.crce - 2.1.1-SNAPSHOT - - 4.0.0 - - crce-rest-v2 - - war - - CRCE - REST Version 2 - - - ${namespace}.rest.v2 - ${namespace}.rest.v2 - all - - - - - - maven-war-plugin - - - - WEB-INF/lib/*.jar - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - true - - - - org.apache.felix - maven-bundle-plugin - true - - - bundle-manifest - process-classes - - manifest - - - - - - - - - - jar - bundle - war - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - 3.1.0 - - war - - - - - - - - - - - org.apache.felix - org.apache.felix.bundlerepository - - - - - - ${project.groupId} - crce-core - pom - - - - - - cz.zcu.kiv.crce - crce-metadata-osgi-bundle - ${project.version} - - - cz.zcu.kiv.crce - crce-compatibility-api - ${project.version} - - - cz.zcu.kiv.crce - crce-vo - ${project.version} - - - - - - javax.servlet - servlet-api - - - javax.ws.rs - javax.ws.rs-api - - - org.glassfish.jersey.containers - jersey-container-servlet-core - - - org.glassfish.jersey.media - jersey-media-multipart - - - org.glassfish.jersey.media - jersey-media-json-jackson - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-xml-provider - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - - - - - - junit - junit - - - + + + + ../pom + crce-modules-parent + cz.zcu.kiv.crce + 2.1.1-SNAPSHOT + + 4.0.0 + + crce-rest-v2 + + war + + CRCE - REST Version 2 + + + ${namespace}.rest.v2 + ${namespace}.rest.v2 + all + + + + + + maven-war-plugin + + + + WEB-INF/lib/*.jar + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + true + + + + org.apache.felix + maven-bundle-plugin + true + + + bundle-manifest + process-classes + + manifest + + + + + + + + + + jar + bundle + war + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + 3.1.0 + + war + + + + + + + + + + + org.apache.felix + org.apache.felix.bundlerepository + + + + + + ${project.groupId} + crce-core + pom + + + + + + cz.zcu.kiv.crce + crce-metadata-osgi-bundle + ${project.version} + + + cz.zcu.kiv.crce + crce-compatibility-api + ${project.version} + + + cz.zcu.kiv.crce + crce-vo + ${project.version} + + + + + + javax.servlet + servlet-api + + + javax.ws.rs + javax.ws.rs-api + + + org.glassfish.jersey.containers + jersey-container-servlet-core + + + org.glassfish.jersey.media + jersey-media-multipart + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + + + + + + junit + junit + + + \ No newline at end of file diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/Activator.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/Activator.java index 25c0bbab..ff6f6136 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/Activator.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/Activator.java @@ -1,106 +1,106 @@ -package cz.zcu.kiv.crce.rest.v2.internal; - -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.vo.service.MappingService; - -@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") -public final class Activator extends DependencyActivatorBase { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - private static volatile Activator instance; - - /* - * Injected by Dependency Manager. - */ - private volatile Store store; - private volatile MetadataService metadataService; - private volatile MetadataFactory metadataFactory; - private volatile FilterParser filterParser; - private volatile CompatibilitySearchService compatibilityService; - private volatile SessionRegister sessionRegister; - private volatile MappingService mappingService; - - public static Activator instance() { - return instance; - } - - public Store getStore() { - return store; - } - - public MetadataService getMetadataService() { - return metadataService; - } - - public MetadataFactory getMetadataFactory() { - return metadataFactory; - } - - public FilterParser getFilterParser() { - return filterParser; - } - - public MappingService getMappingService() { - return mappingService; - } - - @Nullable - public CompatibilitySearchService getCompatibilityService() { - if(compatibilityService == null) { - logger.info("Compatibility service is not available!"); - } - return compatibilityService; - } - - public Buffer getBuffer(HttpServletRequest req) { - if (req == null) { - return null; - } - - String sid = req.getSession(true).getId(); - return sessionRegister.getSessionData(sid).getBuffer(); - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - - } - - @Override - @edu.umd.cs.findbugs.annotations - .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") - public void init(BundleContext context, DependencyManager manager) throws Exception { - instance = this; - - logger.debug("Initializing Rest-V2 Activator!"); - - manager.add(createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(Store.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(FilterParser.class).setRequired(true)) - .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) - .add(createServiceDependency().setService(MappingService.class).setRequired(true)) - .add(createServiceDependency().setService(CompatibilitySearchService.class).setRequired(false)) - ); - - logger.debug("Finished initializing Rest-V2 Activator!"); - } -} +package cz.zcu.kiv.crce.rest.v2.internal; + +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.vo.service.MappingService; + +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") +public final class Activator extends DependencyActivatorBase { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + private static volatile Activator instance; + + /* + * Injected by Dependency Manager. + */ + private volatile Store store; + private volatile MetadataService metadataService; + private volatile MetadataFactory metadataFactory; + private volatile FilterParser filterParser; + private volatile CompatibilitySearchService compatibilityService; + private volatile SessionRegister sessionRegister; + private volatile MappingService mappingService; + + public static Activator instance() { + return instance; + } + + public Store getStore() { + return store; + } + + public MetadataService getMetadataService() { + return metadataService; + } + + public MetadataFactory getMetadataFactory() { + return metadataFactory; + } + + public FilterParser getFilterParser() { + return filterParser; + } + + public MappingService getMappingService() { + return mappingService; + } + + @Nullable + public CompatibilitySearchService getCompatibilityService() { + if(compatibilityService == null) { + logger.info("Compatibility service is not available!"); + } + return compatibilityService; + } + + public Buffer getBuffer(HttpServletRequest req) { + if (req == null) { + return null; + } + + String sid = req.getSession(true).getId(); + return sessionRegister.getSessionData(sid).getBuffer(); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + + } + + @Override + @edu.umd.cs.findbugs.annotations + .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") + public void init(BundleContext context, DependencyManager manager) throws Exception { + instance = this; + + logger.debug("Initializing Rest-V2 Activator!"); + + manager.add(createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(Store.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(FilterParser.class).setRequired(true)) + .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) + .add(createServiceDependency().setService(MappingService.class).setRequired(true)) + .add(createServiceDependency().setService(CompatibilitySearchService.class).setRequired(false)) + ); + + logger.debug("Finished initializing Rest-V2 Activator!"); + } +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/RestApplication.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/RestApplication.java index 5f8a16f1..c68250b9 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/RestApplication.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/RestApplication.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.rest.v2.internal; -import java.util.HashSet; -import java.util.Set; - -import javax.ws.rs.core.Application; - -import org.glassfish.jersey.filter.LoggingFilter; -import org.glassfish.jersey.jackson.JacksonFeature; -import org.glassfish.jersey.media.multipart.MultiPartFeature; - -/** - * Registers features to Jersey. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class RestApplication extends Application { - - @Override - public Set> getClasses() { - final Set> classes = new HashSet<>(); - classes.add(MultiPartFeature.class); - classes.add(LoggingFilter.class); - classes.add(JacksonFeature.class); - return classes; - } -} +package cz.zcu.kiv.crce.rest.v2.internal; +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.core.Application; + +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +/** + * Registers features to Jersey. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class RestApplication extends Application { + + @Override + public Set> getClasses() { + final Set> classes = new HashSet<>(); + classes.add(MultiPartFeature.class); + classes.add(LoggingFilter.class); + classes.add(JacksonFeature.class); + return classes; + } +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/MetadataRes.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/MetadataRes.java index 4dbb7d04..3b835e8a 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/MetadataRes.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/MetadataRes.java @@ -1,96 +1,96 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws; - -import javax.ws.rs.core.Response; - -/** - * Date: 5.5.15 - * - * @author Jakub Danek - */ -public interface MetadataRes { - - /** - * Enumeration of possible operations. - * - * Used when searching for compatible bundles to specify whether user - * aims for update or downgrade. - * - */ - enum Operation { - UPGRADE("UP"), - DOWNGRADE("DOWN"), - LOWEST("LOW"), - HIGHEST("HIGH"), - ANY("ANY"); - - private String value; - - Operation(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - } - - /** - * Returns list of all resources available. - * - * Only basic crce identity metadata displayed. - * - * @return - */ - Response metadata(); - - /** - * Returns list of available bundles with given name. - * - * Displays only basic crce identity information. - * - * @param name name to filter by - * @return - */ - Response metadata(String name); - - /** - * Displays list of available resources with given name and version - * @param name name of the resource - * @param version version of the resource - * @return - */ - Response metadata(String name, String version); - - /** - * Displays detailed information about a concrete resource. - * @param uuid id of the resource - * @return - */ - Response metadataDetails(String uuid); - - /** - * Displays differences between the resource identified by name and version - * and the resource identified by otherName and otherVersion. - * - * Both otherName and otherVersion are optional filtering parameters. If none are provided - * all available diffs for the resource are returned. - * - * @param name - * @param version - * @param otherName optional parameter - * @param otherVersion optional parameter - * @return - */ - Response diffs(String name, String version, String otherName, String otherVersion); - - /** - * Returns metadata for a compatible resource with "our" resource (specified by name and version) - * based on the operation provided. - * - * @param name name of our resource - * @param version version of our resource - * @param operation desired operation - * @return - */ - Response compatible(String name, String version, Operation operation); -} +package cz.zcu.kiv.crce.rest.v2.internal.ws; + +import javax.ws.rs.core.Response; + +/** + * Date: 5.5.15 + * + * @author Jakub Danek + */ +public interface MetadataRes { + + /** + * Enumeration of possible operations. + * + * Used when searching for compatible bundles to specify whether user + * aims for update or downgrade. + * + */ + enum Operation { + UPGRADE("UP"), + DOWNGRADE("DOWN"), + LOWEST("LOW"), + HIGHEST("HIGH"), + ANY("ANY"); + + private String value; + + Operation(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + + /** + * Returns list of all resources available. + * + * Only basic crce identity metadata displayed. + * + * @return + */ + Response metadata(); + + /** + * Returns list of available bundles with given name. + * + * Displays only basic crce identity information. + * + * @param name name to filter by + * @return + */ + Response metadata(String name); + + /** + * Displays list of available resources with given name and version + * @param name name of the resource + * @param version version of the resource + * @return + */ + Response metadata(String name, String version); + + /** + * Displays detailed information about a concrete resource. + * @param uuid id of the resource + * @return + */ + Response metadataDetails(String uuid); + + /** + * Displays differences between the resource identified by name and version + * and the resource identified by otherName and otherVersion. + * + * Both otherName and otherVersion are optional filtering parameters. If none are provided + * all available diffs for the resource are returned. + * + * @param name + * @param version + * @param otherName optional parameter + * @param otherVersion optional parameter + * @return + */ + Response diffs(String name, String version, String otherName, String otherVersion); + + /** + * Returns metadata for a compatible resource with "our" resource (specified by name and version) + * based on the operation provided. + * + * @param name name of our resource + * @param version version of our resource + * @param operation desired operation + * @return + */ + Response compatible(String name, String version, Operation operation); +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/ResourceRes.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/ResourceRes.java index 4cb92cff..d3585a15 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/ResourceRes.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/ResourceRes.java @@ -1,64 +1,64 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws; - -import java.io.InputStream; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - - -/** - * Date: 5.5.15 - * - * @author Jakub Danek - */ -public interface ResourceRes { - - /** - * Returns list of available resources. - * - * Displays only basic crce identity information. - * - * @return - */ - Response resources(); - - /** - * Returns list of available resources with given name. - * - * Displays only basic crce identity information. - * - * @param name name to filter by - * @return - */ - Response resources(String name); - - /** - * Returns list of available resources with given name and version. - * - * @param name resource name - * @param version resource version - * @return - */ - Response resources(String name, String version); - - /** - * Returns concrete resource binary based on provided UUID - * @param uuid resource id in crce - * @return - */ - Response resourceBinary(String uuid); - - /** - * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. - * - * @param uploadedInputStream file stream - * @param fileDetail file headers - * @param req request - * @return OK if success, 403 otherwise - */ - Response uploadResource(InputStream uploadedInputStream, - FormDataContentDisposition fileDetail, - HttpServletRequest req); -} +package cz.zcu.kiv.crce.rest.v2.internal.ws; + +import java.io.InputStream; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + + +/** + * Date: 5.5.15 + * + * @author Jakub Danek + */ +public interface ResourceRes { + + /** + * Returns list of available resources. + * + * Displays only basic crce identity information. + * + * @return + */ + Response resources(); + + /** + * Returns list of available resources with given name. + * + * Displays only basic crce identity information. + * + * @param name name to filter by + * @return + */ + Response resources(String name); + + /** + * Returns list of available resources with given name and version. + * + * @param name resource name + * @param version resource version + * @return + */ + Response resources(String name, String version); + + /** + * Returns concrete resource binary based on provided UUID + * @param uuid resource id in crce + * @return + */ + Response resourceBinary(String uuid); + + /** + * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. + * + * @param uploadedInputStream file stream + * @param fileDetail file headers + * @param req request + * @return OK if success, 403 otherwise + */ + Response uploadResource(InputStream uploadedInputStream, + FormDataContentDisposition fileDetail, + HttpServletRequest req); +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/HelpMeExceptionMapper.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/HelpMeExceptionMapper.java index 90217f51..e7facc1f 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/HelpMeExceptionMapper.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/HelpMeExceptionMapper.java @@ -1,35 +1,35 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Debug exception mapper which forces write of exceptions into - * logs. - * - * Date: 18.5.15 - * - * @author Jakub Danek - */ -@Provider -public class HelpMeExceptionMapper implements ExceptionMapper { - - private static final Logger logger = LoggerFactory.getLogger(HelpMeExceptionMapper.class); - - @Override - public Response toResponse(Exception e) { - logger.error(e.getMessage(), e); - return Response - .status(Status.INTERNAL_SERVER_ERROR) - .type(MediaType.APPLICATION_JSON) - .entity(e.getCause()) - .build(); - } - -} +package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Debug exception mapper which forces write of exceptions into + * logs. + * + * Date: 18.5.15 + * + * @author Jakub Danek + */ +@Provider +public class HelpMeExceptionMapper implements ExceptionMapper { + + private static final Logger logger = LoggerFactory.getLogger(HelpMeExceptionMapper.class); + + @Override + public Response toResponse(Exception e) { + logger.error(e.getMessage(), e); + return Response + .status(Status.INTERNAL_SERVER_ERROR) + .type(MediaType.APPLICATION_JSON) + .entity(e.getCause()) + .build(); + } + +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/MetadataResJersey.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/MetadataResJersey.java index dcfdd150..391a96a0 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/MetadataResJersey.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/MetadataResJersey.java @@ -1,185 +1,185 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; - -import java.util.LinkedList; -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.GenericEntity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.rest.v2.internal.Activator; -import cz.zcu.kiv.crce.rest.v2.internal.ws.MetadataRes; -import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; - -/** - * Date: 2.8.15 - * - * @author Jakub Danek - */ - -@Path("/metadata") -@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) -@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) -public class MetadataResJersey implements MetadataRes { - - private static final Logger logger = LoggerFactory.getLogger(MetadataResJersey.class); - - @GET - @Override - public Response metadata() { - logger.info("Serving /metadata GET request"); - List resources = Activator.instance().getStore().getResources(); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) {}).build(); - } - - @GET - @Path("/catalogue/{name}") - @Override - public Response metadata(@PathParam("name") String name) { - logger.info("Serving /metadata/catalogue" + name + " GET request"); - Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name); - List resources = Activator.instance().getStore().getResources(r); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) { - }).build(); - } - - @GET - @Path("/catalogue/{name}/{version}") - @Override - public Response metadata(@PathParam("name") String name, @PathParam("version") String version) { - logger.info("Serving /metadata/catalogue" + name + "/" + version + " GET request"); - Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name, version); - List resources = Activator.instance().getStore().getResources(r); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) { - }).build(); - } - - /** - * Displays detailed information about a concrete resource. - * - * @param uuid id of the resource - * @return - */ - @GET - @Path("/{id}") - @Override - public Response metadataDetails(@PathParam("id")String uuid) { - logger.info("Serving /metadata/" + uuid + " GET request"); - List resources = Activator.instance().getStore().getResources(); - - Resource toRet = null; - for (Resource resource : resources) { - if(uuid.equals(resource.getId())) { - toRet = resource; - break; - } - } - - if(toRet == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - - DetailedResourceVO vo = Activator.instance().getMappingService().mapFull(toRet); - return Response.ok(vo).build(); - } - - @GET - @Path("/catalogue/{externalId}/{version}/diffs") - @Override - public Response diffs(@PathParam("externalId") String externalId, - @PathParam("version") String version, - @QueryParam("otherExternalId") String otherExternalId, - @QueryParam("otherVersion") String otherVersion) { - Activator act = Activator.instance(); - - CompatibilitySearchService service = act.getCompatibilityService(); - if(service == null) { - return createNotAvailableResponse(); - } - - - List res = act.getStore().getResources(act.getMetadataService().createIdentityRequirement(externalId, version)); - List diffs = new LinkedList<>(); - - for (Resource re : res) { - diffs.addAll(service.listLowerCompatibilities(re)); - diffs.addAll(service.listUpperCompatibilities(re)); - } - - List vos = act.getMappingService().mapCompatibility(diffs); - - return Response.ok().entity(new GenericEntity>(vos) {}).build(); - } - - @GET - @Path("/catalogue/{externalId}/{version}/compatible") - @Override - public Response compatible(@PathParam("externalId") String externalId, @PathParam("version") String version, @QueryParam("op") Operation operation) { - Activator act = Activator.instance(); - - CompatibilitySearchService service = act.getCompatibilityService(); - if(service == null) { - return createNotAvailableResponse(); - } - - List res = act.getStore().getResources(act.getMetadataService().createIdentityRequirement(externalId, version)); - List compatible = new LinkedList<>(); - Resource tmp; - for (Resource re : res) { - switch (operation) { - case DOWNGRADE: - tmp = service.findNearestDowngrade(re); - break; - case UPGRADE: - tmp = service.findNearestUpgrade(re); - break; - case HIGHEST: - tmp = service.findHighestUpgrade(re); - break; - case LOWEST: - tmp = service.findLowestDowngrade(re); - break; - case ANY: - default: - tmp = service.findHighestUpgrade(re); - if(tmp == null) { - tmp = service.findNearestDowngrade(re); - } - break; - } - - if(tmp != null) { - compatible.add(tmp); - } - } - - List resources = act.getMappingService().mapFull(compatible); - - return Response.ok().entity(new GenericEntity>(resources) {}).build(); - } - - private Response createNotAvailableResponse() { - return Response.status(Response.Status.NOT_FOUND).entity("The request functionality is not supported by this instance.").build(); - } -} +package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; + +import java.util.LinkedList; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.rest.v2.internal.Activator; +import cz.zcu.kiv.crce.rest.v2.internal.ws.MetadataRes; +import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; + +/** + * Date: 2.8.15 + * + * @author Jakub Danek + */ + +@Path("/metadata") +@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +public class MetadataResJersey implements MetadataRes { + + private static final Logger logger = LoggerFactory.getLogger(MetadataResJersey.class); + + @GET + @Override + public Response metadata() { + logger.info("Serving /metadata GET request"); + List resources = Activator.instance().getStore().getResources(); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) {}).build(); + } + + @GET + @Path("/catalogue/{name}") + @Override + public Response metadata(@PathParam("name") String name) { + logger.info("Serving /metadata/catalogue" + name + " GET request"); + Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name); + List resources = Activator.instance().getStore().getResources(r); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) { + }).build(); + } + + @GET + @Path("/catalogue/{name}/{version}") + @Override + public Response metadata(@PathParam("name") String name, @PathParam("version") String version) { + logger.info("Serving /metadata/catalogue" + name + "/" + version + " GET request"); + Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name, version); + List resources = Activator.instance().getStore().getResources(r); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) { + }).build(); + } + + /** + * Displays detailed information about a concrete resource. + * + * @param uuid id of the resource + * @return + */ + @GET + @Path("/{id}") + @Override + public Response metadataDetails(@PathParam("id")String uuid) { + logger.info("Serving /metadata/" + uuid + " GET request"); + List resources = Activator.instance().getStore().getResources(); + + Resource toRet = null; + for (Resource resource : resources) { + if(uuid.equals(resource.getId())) { + toRet = resource; + break; + } + } + + if(toRet == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + + DetailedResourceVO vo = Activator.instance().getMappingService().mapFull(toRet); + return Response.ok(vo).build(); + } + + @GET + @Path("/catalogue/{externalId}/{version}/diffs") + @Override + public Response diffs(@PathParam("externalId") String externalId, + @PathParam("version") String version, + @QueryParam("otherExternalId") String otherExternalId, + @QueryParam("otherVersion") String otherVersion) { + Activator act = Activator.instance(); + + CompatibilitySearchService service = act.getCompatibilityService(); + if(service == null) { + return createNotAvailableResponse(); + } + + + List res = act.getStore().getResources(act.getMetadataService().createIdentityRequirement(externalId, version)); + List diffs = new LinkedList<>(); + + for (Resource re : res) { + diffs.addAll(service.listLowerCompatibilities(re)); + diffs.addAll(service.listUpperCompatibilities(re)); + } + + List vos = act.getMappingService().mapCompatibility(diffs); + + return Response.ok().entity(new GenericEntity>(vos) {}).build(); + } + + @GET + @Path("/catalogue/{externalId}/{version}/compatible") + @Override + public Response compatible(@PathParam("externalId") String externalId, @PathParam("version") String version, @QueryParam("op") Operation operation) { + Activator act = Activator.instance(); + + CompatibilitySearchService service = act.getCompatibilityService(); + if(service == null) { + return createNotAvailableResponse(); + } + + List res = act.getStore().getResources(act.getMetadataService().createIdentityRequirement(externalId, version)); + List compatible = new LinkedList<>(); + Resource tmp; + for (Resource re : res) { + switch (operation) { + case DOWNGRADE: + tmp = service.findNearestDowngrade(re); + break; + case UPGRADE: + tmp = service.findNearestUpgrade(re); + break; + case HIGHEST: + tmp = service.findHighestUpgrade(re); + break; + case LOWEST: + tmp = service.findLowestDowngrade(re); + break; + case ANY: + default: + tmp = service.findHighestUpgrade(re); + if(tmp == null) { + tmp = service.findNearestDowngrade(re); + } + break; + } + + if(tmp != null) { + compatible.add(tmp); + } + } + + List resources = act.getMappingService().mapFull(compatible); + + return Response.ok().entity(new GenericEntity>(resources) {}).build(); + } + + private Response createNotAvailableResponse() { + return Response.status(Response.Status.NOT_FOUND).entity("The request functionality is not supported by this instance.").build(); + } +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/ResourceResJersey.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/ResourceResJersey.java index 2d728fd7..8e74c87c 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/ResourceResJersey.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/jersey/ResourceResJersey.java @@ -1,138 +1,138 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.GenericEntity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.rest.v2.internal.Activator; -import cz.zcu.kiv.crce.rest.v2.internal.ws.ResourceRes; -import cz.zcu.kiv.crce.rest.v2.internal.ws.util.ResponseUtil; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; - - -/** - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@Path("/resources") -@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) -@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) -public class ResourceResJersey implements ResourceRes { - - private static final Logger logger = LoggerFactory.getLogger(ResourceResJersey.class); - - @Override - @GET - public Response resources() { - List resources = Activator.instance().getStore().getResources(); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) {}).build(); - } - - @Override - @GET - @Path("/catalogue/{name}") - public Response resources(@PathParam("name")String name) { - logger.info("Serving /resources/catalogue" + name + " GET request"); - Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name); - List resources = Activator.instance().getStore().getResources(r); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) {}).build(); - } - - @Override - @GET - @Path("/catalogue/{name}/{version}") - public Response resources(@PathParam("name")String name, @PathParam("version")String version) { - logger.info("Serving /resources/catalogue" + name + "/" + version + " GET request"); - Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name, version); - List resources = Activator.instance().getStore().getResources(r); - List vos = Activator.instance().getMappingService().mapBasic(resources); - - return Response.ok().entity(new GenericEntity>(vos) {}).build(); - } - - /** - * Returns concrete resource binary based on provided UUID - * - * @param uuid resource id in crce - * @return - */ - @Override - @GET - @Path("{id}") - public Response resourceBinary(@PathParam("id") String uuid) { - logger.info("Serving /resources/" + uuid + " GET request"); - List resources = Activator.instance().getStore().getResources(); - - Resource toRet = null; - for (Resource resource : resources) { - if(uuid.equals(resource.getId())) { - toRet = resource; - break; - } - } - - if(toRet == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - - return ResponseUtil.serveResourceAsFile(toRet); - } - - /** - * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. - * - * @param uploadedInputStream file stream - * @param fileDetail file headers - * @param req request - * @return OK if success, 403 otherwise - */ - @POST - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Override - public Response uploadResource(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @Context HttpServletRequest req) { - - logger.debug("Get buffer for uploadBundle request {}.", req.getRequestURI()); - Buffer b = Activator.instance().getBuffer(req); - - String filename = fileDetail.getFileName(); - logger.debug("Uploaded filename: {}", filename); - try { - b.put(filename, uploadedInputStream); - b.commit(true); - } catch (IOException | RefusedArtifactException e) { - logger.error("Error during resource upload.", e); - return Response.status(403).build(); - } - - logger.debug("Upload of bundle via REST successful."); - return Response.ok().build(); - } -} +package cz.zcu.kiv.crce.rest.v2.internal.ws.jersey; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.rest.v2.internal.Activator; +import cz.zcu.kiv.crce.rest.v2.internal.ws.ResourceRes; +import cz.zcu.kiv.crce.rest.v2.internal.ws.util.ResponseUtil; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; + + +/** + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@Path("/resources") +@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +public class ResourceResJersey implements ResourceRes { + + private static final Logger logger = LoggerFactory.getLogger(ResourceResJersey.class); + + @Override + @GET + public Response resources() { + List resources = Activator.instance().getStore().getResources(); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) {}).build(); + } + + @Override + @GET + @Path("/catalogue/{name}") + public Response resources(@PathParam("name")String name) { + logger.info("Serving /resources/catalogue" + name + " GET request"); + Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name); + List resources = Activator.instance().getStore().getResources(r); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) {}).build(); + } + + @Override + @GET + @Path("/catalogue/{name}/{version}") + public Response resources(@PathParam("name")String name, @PathParam("version")String version) { + logger.info("Serving /resources/catalogue" + name + "/" + version + " GET request"); + Requirement r = Activator.instance().getMetadataService().createIdentityRequirement(name, version); + List resources = Activator.instance().getStore().getResources(r); + List vos = Activator.instance().getMappingService().mapBasic(resources); + + return Response.ok().entity(new GenericEntity>(vos) {}).build(); + } + + /** + * Returns concrete resource binary based on provided UUID + * + * @param uuid resource id in crce + * @return + */ + @Override + @GET + @Path("{id}") + public Response resourceBinary(@PathParam("id") String uuid) { + logger.info("Serving /resources/" + uuid + " GET request"); + List resources = Activator.instance().getStore().getResources(); + + Resource toRet = null; + for (Resource resource : resources) { + if(uuid.equals(resource.getId())) { + toRet = resource; + break; + } + } + + if(toRet == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + + return ResponseUtil.serveResourceAsFile(toRet); + } + + /** + * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. + * + * @param uploadedInputStream file stream + * @param fileDetail file headers + * @param req request + * @return OK if success, 403 otherwise + */ + @POST + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Override + public Response uploadResource(@FormDataParam("file") InputStream uploadedInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context HttpServletRequest req) { + + logger.debug("Get buffer for uploadBundle request {}.", req.getRequestURI()); + Buffer b = Activator.instance().getBuffer(req); + + String filename = fileDetail.getFileName(); + logger.debug("Uploaded filename: {}", filename); + try { + b.put(filename, uploadedInputStream); + b.commit(true); + } catch (IOException | RefusedArtifactException e) { + logger.error("Error during resource upload.", e); + return Response.status(403).build(); + } + + logger.debug("Upload of bundle via REST successful."); + return Response.ok().build(); + } +} diff --git a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/util/ResponseUtil.java b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/util/ResponseUtil.java index b862fc84..0a32c046 100644 --- a/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/util/ResponseUtil.java +++ b/modules/crce-rest-v2/src/main/java/cz/zcu/kiv/crce/rest/v2/internal/ws/util/ResponseUtil.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.rest.v2.internal.ws.util; - -import java.io.File; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.rest.v2.internal.Activator; - -/** - * Date: 2.8.15 - * - * @author Jakub Danek - */ -public class ResponseUtil { - - public static Response serveResourceAsFile(Resource resource) { - MetadataService metadataService = Activator.instance().getMetadataService(); - - File resourceFile = new File(metadataService.getUri(resource)); - - Attribute attribute = metadataService.getIdentity(resource) - .getAttribute(new SimpleAttributeType<>("mime", String.class)); - - String filename = metadataService.getFileName(resource); - - return Response.ok(resourceFile) - .type(attribute != null ? attribute.getValue() : MediaType.APPLICATION_OCTET_STREAM) - .header("content-disposition", "attachment; filename = " + filename) - .build(); - } -} +package cz.zcu.kiv.crce.rest.v2.internal.ws.util; + +import java.io.File; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.rest.v2.internal.Activator; + +/** + * Date: 2.8.15 + * + * @author Jakub Danek + */ +public class ResponseUtil { + + public static Response serveResourceAsFile(Resource resource) { + MetadataService metadataService = Activator.instance().getMetadataService(); + + File resourceFile = new File(metadataService.getUri(resource)); + + Attribute attribute = metadataService.getIdentity(resource) + .getAttribute(new SimpleAttributeType<>("mime", String.class)); + + String filename = metadataService.getFileName(resource); + + return Response.ok(resourceFile) + .type(attribute != null ? attribute.getValue() : MediaType.APPLICATION_OCTET_STREAM) + .header("content-disposition", "attachment; filename = " + filename) + .build(); + } +} diff --git a/modules/crce-rest-v2/src/main/webapp/WEB-INF/web.xml b/modules/crce-rest-v2/src/main/webapp/WEB-INF/web.xml index 1ac164df..ba57526c 100644 --- a/modules/crce-rest-v2/src/main/webapp/WEB-INF/web.xml +++ b/modules/crce-rest-v2/src/main/webapp/WEB-INF/web.xml @@ -1,41 +1,41 @@ - - - - - - - - - - JerseyV2 - org.glassfish.jersey.servlet.ServletContainer - - jersey.config.server.provider.packages - cz.zcu.kiv.crce.rest.v2.internal.ws.jersey - - - javax.ws.rs.Application - cz.zcu.kiv.crce.rest.v2.internal.RestApplication - - - jersey.config.jaxb.collections.processXmlRootElement - true - - - com.sun.jersey.config.feature.Trace - true - - 1 - - - JerseyV2 - /* - - - + + + + + + + + + + JerseyV2 + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + cz.zcu.kiv.crce.rest.v2.internal.ws.jersey + + + javax.ws.rs.Application + cz.zcu.kiv.crce.rest.v2.internal.RestApplication + + + jersey.config.jaxb.collections.processXmlRootElement + true + + + com.sun.jersey.config.feature.Trace + true + + 1 + + + JerseyV2 + /* + + + diff --git a/modules/crce-rest/osgi.bnd b/modules/crce-rest/osgi.bnd index 721d016f..c9f6f689 100644 --- a/modules/crce-rest/osgi.bnd +++ b/modules/crce-rest/osgi.bnd @@ -1,34 +1,34 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Version>: \ - ${pom.version} - -Bundle-SymbolicName: \ - ${bundle.symbolicName} - -Bundle-Name: CRCE - Rest - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Import-Package: \ - !javax.annotation, \ - javax.servlet, \ - javax.servlet.http, \ - org.osgi.framework, \ - org.osgi.service.log, \ - org.osgi.service.useradmin, \ - org.glassfish.jersey.servlet, \ - cz.zcu.kiv.crce.repository, \ - * - -Export-Package: - -Dynamic-ImportPackage: * - -Bundle-ClassPath: .,WEB-INF/classes - -Web-ContextPath: rest - -Webapp-Context: rest +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Version>: \ + ${pom.version} + +Bundle-SymbolicName: \ + ${bundle.symbolicName} + +Bundle-Name: CRCE - Rest + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Import-Package: \ + !javax.annotation, \ + javax.servlet, \ + javax.servlet.http, \ + org.osgi.framework, \ + org.osgi.service.log, \ + org.osgi.service.useradmin, \ + org.glassfish.jersey.servlet, \ + cz.zcu.kiv.crce.repository, \ + * + +Export-Package: + +Dynamic-ImportPackage: * + +Bundle-ClassPath: .,WEB-INF/classes + +Web-ContextPath: rest + +Webapp-Context: rest diff --git a/modules/crce-rest/pom.xml b/modules/crce-rest/pom.xml index 69c9f1e3..57f0aaf2 100644 --- a/modules/crce-rest/pom.xml +++ b/modules/crce-rest/pom.xml @@ -1,228 +1,228 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-rest - war - - CRCE - REST - - - ${namespace}.rest - ${namespace}.rest - all - - - - - - maven-war-plugin - - - - WEB-INF/lib/*.jar - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - true - - - - org.apache.felix - maven-bundle-plugin - true - - - bundle-manifest - process-classes - - manifest - - - - - - - - - - jar - bundle - war - - - - - org.apache.felix - org.apache.felix.dependencymanager.annotation - 3.1.0 - - war - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - unpack-xsd - initialize - - unpack - - - - - ${project.groupId} - crce-metadata-api - 3.0.0 - ${basedir}/target/xsd - - - ${project.groupId} - crce-compatibility-api - ${project.version} - ${basedir}/target/xsd - - - **/*.xsd - - - - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - set-additional-system-properties - - set-system-properties - - - - - - - javax.xml.accessExternalSchema - file,http - - - - - - - org.codehaus.mojo - jaxb2-maven-plugin - 1.6 - - - xjc-metadata - - xjc - - - cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd - metadata.xjb - cz.zcu.kiv.crce.rest.internal.jaxb.metadata - -episode ${basedir}/target/xsd/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.episode - - - - xjc-compatibility - - xjc - - - cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd - compatibility.xjb - cz.zcu.kiv.crce.rest.internal.jaxb.compatibility - -b ${basedir}/target/xsd/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.episode - false - - - - - ${basedir}/target/xsd/ - ${basedir}/src/main/resources/jaxb/ - true - - - - - - - - - - - org.apache.felix - org.apache.felix.bundlerepository - - - - - - ${project.groupId} - crce-core - pom - - - - - - cz.zcu.kiv.crce - crce-metadata-osgi-bundle - ${project.version} - - - cz.zcu.kiv.crce - crce-compatibility-api - ${project.version} - - - - - - javax.servlet - servlet-api - - - javax.ws.rs - javax.ws.rs-api - - - org.glassfish.jersey.containers - jersey-container-servlet-core - - - org.glassfish.jersey.media - jersey-media-multipart - - - - - - junit - junit - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-rest + war + + CRCE - REST + + + ${namespace}.rest + ${namespace}.rest + all + + + + + + maven-war-plugin + + + + WEB-INF/lib/*.jar + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + true + + + + org.apache.felix + maven-bundle-plugin + true + + + bundle-manifest + process-classes + + manifest + + + + + + + + + + jar + bundle + war + + + + + org.apache.felix + org.apache.felix.dependencymanager.annotation + 3.1.0 + + war + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack-xsd + initialize + + unpack + + + + + ${project.groupId} + crce-metadata-api + 3.0.0 + ${basedir}/target/xsd + + + ${project.groupId} + crce-compatibility-api + ${project.version} + ${basedir}/target/xsd + + + **/*.xsd + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + set-additional-system-properties + + set-system-properties + + + + + + + javax.xml.accessExternalSchema + file,http + + + + + + + org.codehaus.mojo + jaxb2-maven-plugin + 1.6 + + + xjc-metadata + + xjc + + + cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.xsd + metadata.xjb + cz.zcu.kiv.crce.rest.internal.jaxb.metadata + -episode ${basedir}/target/xsd/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.episode + + + + xjc-compatibility + + xjc + + + cz/zcu/kiv/crce/compatibility/schema/v1_0_0/compatibility.xsd + compatibility.xjb + cz.zcu.kiv.crce.rest.internal.jaxb.compatibility + -b ${basedir}/target/xsd/cz/zcu/kiv/crce/metadata/schema/metadata-1.0.0.episode + false + + + + + ${basedir}/target/xsd/ + ${basedir}/src/main/resources/jaxb/ + true + + + + + + + + + + + org.apache.felix + org.apache.felix.bundlerepository + + + + + + ${project.groupId} + crce-core + pom + + + + + + cz.zcu.kiv.crce + crce-metadata-osgi-bundle + ${project.version} + + + cz.zcu.kiv.crce + crce-compatibility-api + ${project.version} + + + + + + javax.servlet + servlet-api + + + javax.ws.rs + javax.ws.rs-api + + + org.glassfish.jersey.containers + jersey-container-servlet-core + + + org.glassfish.jersey.media + jersey-media-multipart + + + + + + junit + junit + + \ No newline at end of file diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/Activator.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/Activator.java index 7265ce28..c164289a 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/Activator.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/Activator.java @@ -1,102 +1,102 @@ -package cz.zcu.kiv.crce.rest.internal; - -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; -import cz.zcu.kiv.crce.rest.internal.mapping.JaxbMapping; - -@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") -public final class Activator extends DependencyActivatorBase { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - private static volatile Activator instance; - - /* - * Injected by Dependency Manager. - */ - private volatile Store store; - private volatile MetadataService metadataService; - private volatile JaxbMapping convertorToBeans; - private volatile MetadataFactory metadataFactory; - private volatile FilterParser filterParser; - private volatile CompatibilitySearchService compatibilityService; - private volatile SessionRegister sessionRegister; - - public static Activator instance() { - return instance; - } - - public Store getStore() { - return store; - } - - public MetadataService getMetadataService() { - return metadataService; - } - - public JaxbMapping getConvertorToBeans() { - return convertorToBeans; - } - - public MetadataFactory getMetadataFactory() { - return metadataFactory; - } - - public FilterParser getFilterParser() { - return filterParser; - } - - @Nullable - public CompatibilitySearchService getCompatibilityService() { - if(compatibilityService == null) { - logger.info("Compatibility service is not available!"); - } - return compatibilityService; - } - - public Buffer getBuffer(HttpServletRequest req) { - if (req == null) { - return null; - } - - String sid = req.getSession(true).getId(); - return sessionRegister.getSessionData(sid).getBuffer(); - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - - } - - @Override - @edu.umd.cs.findbugs.annotations - .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") - public void init(BundleContext context, DependencyManager manager) throws Exception { - instance = this; - - manager.add(createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(Store.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(JaxbMapping.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(FilterParser.class).setRequired(true)) - .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) - .add(createServiceDependency().setService(CompatibilitySearchService.class).setAutoConfig(false).setRequired(false)) - ); - } -} +package cz.zcu.kiv.crce.rest.internal; + +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.osgi.util.FilterParser; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; +import cz.zcu.kiv.crce.rest.internal.mapping.JaxbMapping; + +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") +public final class Activator extends DependencyActivatorBase { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + private static volatile Activator instance; + + /* + * Injected by Dependency Manager. + */ + private volatile Store store; + private volatile MetadataService metadataService; + private volatile JaxbMapping convertorToBeans; + private volatile MetadataFactory metadataFactory; + private volatile FilterParser filterParser; + private volatile CompatibilitySearchService compatibilityService; + private volatile SessionRegister sessionRegister; + + public static Activator instance() { + return instance; + } + + public Store getStore() { + return store; + } + + public MetadataService getMetadataService() { + return metadataService; + } + + public JaxbMapping getConvertorToBeans() { + return convertorToBeans; + } + + public MetadataFactory getMetadataFactory() { + return metadataFactory; + } + + public FilterParser getFilterParser() { + return filterParser; + } + + @Nullable + public CompatibilitySearchService getCompatibilityService() { + if(compatibilityService == null) { + logger.info("Compatibility service is not available!"); + } + return compatibilityService; + } + + public Buffer getBuffer(HttpServletRequest req) { + if (req == null) { + return null; + } + + String sid = req.getSession(true).getId(); + return sessionRegister.getSessionData(sid).getBuffer(); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + + } + + @Override + @edu.umd.cs.findbugs.annotations + .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") + public void init(BundleContext context, DependencyManager manager) throws Exception { + instance = this; + + manager.add(createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(Store.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(JaxbMapping.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(FilterParser.class).setRequired(true)) + .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) + .add(createServiceDependency().setService(CompatibilitySearchService.class).setAutoConfig(false).setRequired(false)) + ); + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetBundle.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetBundle.java index 1415d798..7799b089 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetBundle.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetBundle.java @@ -1,30 +1,30 @@ -package cz.zcu.kiv.crce.rest.internal; - - -import javax.ws.rs.core.Response; - -/** - * Server will provide a single bundle. - * @author Jan Reznicek - * - */ -public interface GetBundle { - - - /** - * Get bundle by id. - * URI is /bundle/id. - * @param id id of a bundle - * @return bundle or error response - */ - Response getBundleById(String id); - - /** - * Return bundle specified by name and version. - * If version is not set, select the one with highest version. - * @param name name of bundle - * @param version version of bundle - * @return bundle or error response - */ - Response getBundlebyNameAndVersion(String name, String version); -} +package cz.zcu.kiv.crce.rest.internal; + + +import javax.ws.rs.core.Response; + +/** + * Server will provide a single bundle. + * @author Jan Reznicek + * + */ +public interface GetBundle { + + + /** + * Get bundle by id. + * URI is /bundle/id. + * @param id id of a bundle + * @return bundle or error response + */ + Response getBundleById(String id); + + /** + * Return bundle specified by name and version. + * If version is not set, select the one with highest version. + * @param name name of bundle + * @param version version of bundle + * @return bundle or error response + */ + Response getBundlebyNameAndVersion(String name, String version); +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetMetadata.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetMetadata.java index 14588bbf..024f49ad 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetMetadata.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetMetadata.java @@ -1,46 +1,46 @@ -package cz.zcu.kiv.crce.rest.internal; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * Server will provide a metadata information about resources in the repository. - * @author Jan Reznicek - * - */ -public interface GetMetadata { - - - /** - * Returns response with metadata of resources from the store repository. - * All parameters all obligatory (can be null). - * If the request is without filter query parameter, return all resources. - * If the request have filter parameter, return resources that met the filter. - * Parameters core, cap, req and prop determines, what part shloud xml contains. - * If all of those parameters(core, cap, req and prop) are null, xml will contains all parts. - * @param filter obligatory LDAP filter - * @param core core metadata - * @param cap all capabilities - * @param req all requirement - * @param prop all properties - * @param ui contextual info about URI - * @return Response with metadata of resources from the store repository, or error with html status. - */ - Response getMetadata(String filter, String core, String cap,String req, String prop, UriInfo ui); - - - /** - * Return response with metadata of one resource, that is specified by id. - * If the request have filter parameter, return resources that met the filter. - * Parameters core, cap, req and prop determines, what part shloud xml contains. - * If all of those parameters(core, cap, req and prop) are null, xml will contains all parts. - * @param id compulsory id of the resource - * @param core core metadata - * @param cap all capabilities - * @param req all requirement - * @param prop all properties - * @param ui contextual info about URI - * @return Response with metadata of resource from repository with the id, or error with html status. - */ - Response getMetadataById(String id, String core, String cap, String req, String prop, UriInfo ui); -} +package cz.zcu.kiv.crce.rest.internal; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +/** + * Server will provide a metadata information about resources in the repository. + * @author Jan Reznicek + * + */ +public interface GetMetadata { + + + /** + * Returns response with metadata of resources from the store repository. + * All parameters all obligatory (can be null). + * If the request is without filter query parameter, return all resources. + * If the request have filter parameter, return resources that met the filter. + * Parameters core, cap, req and prop determines, what part shloud xml contains. + * If all of those parameters(core, cap, req and prop) are null, xml will contains all parts. + * @param filter obligatory LDAP filter + * @param core core metadata + * @param cap all capabilities + * @param req all requirement + * @param prop all properties + * @param ui contextual info about URI + * @return Response with metadata of resources from the store repository, or error with html status. + */ + Response getMetadata(String filter, String core, String cap,String req, String prop, UriInfo ui); + + + /** + * Return response with metadata of one resource, that is specified by id. + * If the request have filter parameter, return resources that met the filter. + * Parameters core, cap, req and prop determines, what part shloud xml contains. + * If all of those parameters(core, cap, req and prop) are null, xml will contains all parts. + * @param id compulsory id of the resource + * @param core core metadata + * @param cap all capabilities + * @param req all requirement + * @param prop all properties + * @param ui contextual info about URI + * @return Response with metadata of resource from repository with the id, or error with html status. + */ + Response getMetadataById(String id, String core, String cap, String req, String prop, UriInfo ui); +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetReplaceBundle.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetReplaceBundle.java index e2f9f7dd..9de5306f 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetReplaceBundle.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/GetReplaceBundle.java @@ -1,41 +1,41 @@ -package cz.zcu.kiv.crce.rest.internal; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * When the client asks CRCE for data about replacement bundle versions and - * provides identifier of a bundle version b_i which exists in the repository - * and optionally provides a desired operation(op). - * - * Then CRCE sends a set of meta-data (the "core" part) of those bundle versions - * b_r which are strictly compatible with b_i and have same provider, name as - * b_i and optionally satisfy the operation or replies - * "no such version found in repository". - * - * Note: The operation value can be - * - *
    - *
  • upgrade [default] = b_r must have same provider, name as b_i and higher - * version than b_i
  • - *
  • nearest = metadata of a single bundle which has lowest r > i
  • - *
  • highest = metadata of a single bundle which has highest r > i
  • - *
  • downgrade = b_r must have same provider, name as b_i and lower version than b_i
  • - *
  • any = b_r must have same provider, name as b_i and version of b_r - * is different to that of b_i
  • - *
- * - * @author Jan Reznicek - * - */ -public interface GetReplaceBundle { - - /** - * In current version return resource with same name as in id and highest possible version. - * @param id - * @param op - * @param ui contextual info about URI - * @return resource - */ - Response replaceBundle(String id, String op, UriInfo ui); -} +package cz.zcu.kiv.crce.rest.internal; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +/** + * When the client asks CRCE for data about replacement bundle versions and + * provides identifier of a bundle version b_i which exists in the repository + * and optionally provides a desired operation(op). + * + * Then CRCE sends a set of meta-data (the "core" part) of those bundle versions + * b_r which are strictly compatible with b_i and have same provider, name as + * b_i and optionally satisfy the operation or replies + * "no such version found in repository". + * + * Note: The operation value can be + * + *
    + *
  • upgrade [default] = b_r must have same provider, name as b_i and higher + * version than b_i
  • + *
  • nearest = metadata of a single bundle which has lowest r > i
  • + *
  • highest = metadata of a single bundle which has highest r > i
  • + *
  • downgrade = b_r must have same provider, name as b_i and lower version than b_i
  • + *
  • any = b_r must have same provider, name as b_i and version of b_r + * is different to that of b_i
  • + *
+ * + * @author Jan Reznicek + * + */ +public interface GetReplaceBundle { + + /** + * In current version return resource with same name as in id and highest possible version. + * @param id + * @param op + * @param ui contextual info about URI + * @return resource + */ + Response replaceBundle(String id, String op, UriInfo ui); +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostOtherBundlesMetadata.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostOtherBundlesMetadata.java index d01b8aa8..3ba0ca64 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostOtherBundlesMetadata.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostOtherBundlesMetadata.java @@ -1,42 +1,42 @@ -package cz.zcu.kiv.crce.rest.internal; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * Server provide metadata about other bundles (repository contents diff). - * - * When the client asks CRCE to provide bundle metadata of those bundles which - * it does not know about and sends a list of bundle identifiers (= those - * bundles it knows about) and optionally sends a filter criteria specifying - * which subset of metadata it is interested in - * - * Then CRCE sends that (subset of) metadata only for the following bundles - * currently available in repository in "stored" state: - *
    - *
  • are not in the list sent by client ("new bundles")
  • - *
  • are in the list but have been removed from the repository - * ("deleted bundles" - just a list of bundle identifiers).
  • - *
- * - * @author Jan Reznicek - * - */ -public interface PostOtherBundlesMetadata { - - /** - * Server provide metadata about other bundles (repository contents diff). - * Response contains bundles, that: - *
    - *
  • are not in the list sent by client, but all in storage ("new bundles")
  • - *
  • are in the list but have been removed from the repository - * ("deleted bundles" - just a list of bundle identifiers).
  • - *
- * - * - * @param knownBundles XML with information about bundles, that client knows. - * @param ui contextual info about URI - * @return Response with difference between knownBundles and state of server. - */ - Response otherBundles(String knownBundles, UriInfo ui); -} +package cz.zcu.kiv.crce.rest.internal; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +/** + * Server provide metadata about other bundles (repository contents diff). + * + * When the client asks CRCE to provide bundle metadata of those bundles which + * it does not know about and sends a list of bundle identifiers (= those + * bundles it knows about) and optionally sends a filter criteria specifying + * which subset of metadata it is interested in + * + * Then CRCE sends that (subset of) metadata only for the following bundles + * currently available in repository in "stored" state: + *
    + *
  • are not in the list sent by client ("new bundles")
  • + *
  • are in the list but have been removed from the repository + * ("deleted bundles" - just a list of bundle identifiers).
  • + *
+ * + * @author Jan Reznicek + * + */ +public interface PostOtherBundlesMetadata { + + /** + * Server provide metadata about other bundles (repository contents diff). + * Response contains bundles, that: + *
    + *
  • are not in the list sent by client, but all in storage ("new bundles")
  • + *
  • are in the list but have been removed from the repository + * ("deleted bundles" - just a list of bundle identifiers).
  • + *
+ * + * + * @param knownBundles XML with information about bundles, that client knows. + * @param ui contextual info about URI + * @return Response with difference between knownBundles and state of server. + */ + Response otherBundles(String knownBundles, UriInfo ui); +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostProviderOfCapability.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostProviderOfCapability.java index d2084fb7..2b97e8aa 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostProviderOfCapability.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/PostProviderOfCapability.java @@ -1,29 +1,29 @@ -package cz.zcu.kiv.crce.rest.internal; - -import javax.ws.rs.core.Response; - -/** - * When the client asks CRCE to send metadata of provider(s) - * and sends a meta-data descriptor of the requirement to be satisfied. - * - * Then CRCE sends a set of meta-data (the "core" part and "capability" which matches the requirement) of bundles which provides the capability and satisfies the criteria - * or replies "no such bundle available". - * - * @author Jan Reznicek - */ -public interface PostProviderOfCapability { - - /** - * When the client asks CRCE to send metadata of provider(s) - * and sends a meta-data descriptor of the requirement to be satisfied. - * - * Then CRCE sends a set of meta-data (the "core" part and "capability" which matches the requirement) of bundles which provides the capability and satisfies the criteria - * or replies "no such bundle available". - * - * - * @param requirement requirement to be satisfied - * --@param ui contextual info about URI - * @return Response metadata of bundles, that matches the requirement - */ - Response providerOfCapability(String requirement/*, UriInfo ui*/); -} +package cz.zcu.kiv.crce.rest.internal; + +import javax.ws.rs.core.Response; + +/** + * When the client asks CRCE to send metadata of provider(s) + * and sends a meta-data descriptor of the requirement to be satisfied. + * + * Then CRCE sends a set of meta-data (the "core" part and "capability" which matches the requirement) of bundles which provides the capability and satisfies the criteria + * or replies "no such bundle available". + * + * @author Jan Reznicek + */ +public interface PostProviderOfCapability { + + /** + * When the client asks CRCE to send metadata of provider(s) + * and sends a meta-data descriptor of the requirement to be satisfied. + * + * Then CRCE sends a set of meta-data (the "core" part and "capability" which matches the requirement) of bundles which provides the capability and satisfies the criteria + * or replies "no such bundle available". + * + * + * @param requirement requirement to be satisfied + * --@param ui contextual info about URI + * @return Response metadata of bundles, that matches the requirement + */ + Response providerOfCapability(String requirement/*, UriInfo ui*/); +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/RestApplication.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/RestApplication.java index 4de70993..ef62ad32 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/RestApplication.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/RestApplication.java @@ -1,23 +1,23 @@ -package cz.zcu.kiv.crce.rest.internal; - -import java.util.HashSet; -import java.util.Set; - -import javax.ws.rs.core.Application; - -import org.glassfish.jersey.media.multipart.MultiPartFeature; - -/** - * Registers features to Jersey. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class RestApplication extends Application { - - @Override - public Set> getClasses() { - final Set> classes = new HashSet<>(); - classes.add(MultiPartFeature.class); - return classes; - } -} +package cz.zcu.kiv.crce.rest.internal; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.core.Application; + +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +/** + * Registers features to Jersey. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class RestApplication extends Application { + + @Override + public Set> getClasses() { + final Set> classes = new HashSet<>(); + classes.add(MultiPartFeature.class); + return classes; + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/CompatibilityMapper.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/CompatibilityMapper.java index 5d48792d..3a0d1e60 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/CompatibilityMapper.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/CompatibilityMapper.java @@ -1,149 +1,149 @@ -package cz.zcu.kiv.crce.rest.internal.mapping; - -import java.util.List; - -import javax.annotation.Nullable; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.transform.dom.DOMResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.ObjectFactory; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property; - -/** - * Java-to-JAXB mapping class for Compatibility data. - *

- * Date: 18.3.14 - * - * @author Jakub Danek - */ -public class CompatibilityMapper { - private ObjectFactory compatibilityObjectFactory = new ObjectFactory(); - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory metadataObjectFactory = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory(); - - /** - * Map compatibility data related to the resource into a Property and attach the property - * to the resource. - * - * @param resource resource to map - * @return Property wrapper around the compatibility data - */ - @Nullable - public Property mapCompatibility(Resource resource) { - CompatibilitySearchService service = Activator.instance().getCompatibilityService(); - if(service == null) { - return null; - } - - Property compProp = null; - List compatibilities = service.listLowerCompatibilities(resource); - if (!compatibilities.isEmpty()) { - compProp = metadataObjectFactory.createProperty(); - compProp.setNamespace(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); - - Element e; - for (Compatibility c : compatibilities) { - e = marshallToElement(mapCompatibility(c)); - - if (e != null) { - compProp.getAnies().add(e); - } - } - - } - - - return compProp; - } - - /** - * Marshall JAXB Compatibility class into DOM Element. - * - * @param o JAXB compatibility instance - * @return DOM Element - */ - private Element marshallToElement(cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility o) { - try { - Class clazz = o.getClass(); - ClassLoader cl = ObjectFactory.class.getClassLoader(); - - JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(), cl); - - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - DOMResult res = new DOMResult(); - m.marshal(o, res); - - return ((Document) res.getNode()).getDocumentElement(); - } catch (JAXBException e) { - return null; - } - } - - - /** - * Map CRCE Compatibility instance to JAXB - * - * @param compatibility - * @return - */ - private cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility mapCompatibility(Compatibility compatibility) { - cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility jaxbCompatibility = compatibilityObjectFactory.createCompatibility(); - - //different vendor - if (!compatibility.getResourceName().equals(compatibility.getBaseResourceName())) { - jaxbCompatibility.setBaseName(compatibility.getBaseResourceName()); - } - jaxbCompatibility.setBaseVersion(compatibility.getBaseResourceVersion().toString()); - jaxbCompatibility.setContract(compatibility.getContract().getValue()); - jaxbCompatibility.setValue(compatibility.getDiffValue().name()); - - List jaxbDiffs = jaxbCompatibility.getDifves(); - for (Diff d : compatibility.getDiffDetails()) { - jaxbDiffs.add(mapDiff(d)); - } - - return jaxbCompatibility; - } - - /** - * Map CRCE Diff instance to JAXB - * - * @param diff - * @return - */ - private cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Diff mapDiff(Diff diff) { - cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Diff jaxbDiff = compatibilityObjectFactory.createDiff(); - - jaxbDiff.setName(diff.getName()); - jaxbDiff.setNamespace(diff.getNamespace()); - //display only on package level - if (diff.getLevel() == DifferenceLevel.PACKAGE) { - jaxbDiff.setSyntax(diff.getSyntax()); - } - jaxbDiff.setValue(diff.getValue().name()); - jaxbDiff.setLevel(diff.getLevel().toString()); - if (diff.getRole() != null) { - jaxbDiff.setRole(diff.getRole().toString()); - } - - List children = jaxbDiff.getDifves(); - for (Diff d : diff.getChildren()) { - children.add(mapDiff(d)); - } - - return jaxbDiff; - } - -} +package cz.zcu.kiv.crce.rest.internal.mapping; + +import java.util.List; + +import javax.annotation.Nullable; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.transform.dom.DOMResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.ObjectFactory; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property; + +/** + * Java-to-JAXB mapping class for Compatibility data. + *

+ * Date: 18.3.14 + * + * @author Jakub Danek + */ +public class CompatibilityMapper { + private ObjectFactory compatibilityObjectFactory = new ObjectFactory(); + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory metadataObjectFactory = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory(); + + /** + * Map compatibility data related to the resource into a Property and attach the property + * to the resource. + * + * @param resource resource to map + * @return Property wrapper around the compatibility data + */ + @Nullable + public Property mapCompatibility(Resource resource) { + CompatibilitySearchService service = Activator.instance().getCompatibilityService(); + if(service == null) { + return null; + } + + Property compProp = null; + List compatibilities = service.listLowerCompatibilities(resource); + if (!compatibilities.isEmpty()) { + compProp = metadataObjectFactory.createProperty(); + compProp.setNamespace(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); + + Element e; + for (Compatibility c : compatibilities) { + e = marshallToElement(mapCompatibility(c)); + + if (e != null) { + compProp.getAnies().add(e); + } + } + + } + + + return compProp; + } + + /** + * Marshall JAXB Compatibility class into DOM Element. + * + * @param o JAXB compatibility instance + * @return DOM Element + */ + private Element marshallToElement(cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility o) { + try { + Class clazz = o.getClass(); + ClassLoader cl = ObjectFactory.class.getClassLoader(); + + JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(), cl); + + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + DOMResult res = new DOMResult(); + m.marshal(o, res); + + return ((Document) res.getNode()).getDocumentElement(); + } catch (JAXBException e) { + return null; + } + } + + + /** + * Map CRCE Compatibility instance to JAXB + * + * @param compatibility + * @return + */ + private cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility mapCompatibility(Compatibility compatibility) { + cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Compatibility jaxbCompatibility = compatibilityObjectFactory.createCompatibility(); + + //different vendor + if (!compatibility.getResourceName().equals(compatibility.getBaseResourceName())) { + jaxbCompatibility.setBaseName(compatibility.getBaseResourceName()); + } + jaxbCompatibility.setBaseVersion(compatibility.getBaseResourceVersion().toString()); + jaxbCompatibility.setContract(compatibility.getContract().getValue()); + jaxbCompatibility.setValue(compatibility.getDiffValue().name()); + + List jaxbDiffs = jaxbCompatibility.getDifves(); + for (Diff d : compatibility.getDiffDetails()) { + jaxbDiffs.add(mapDiff(d)); + } + + return jaxbCompatibility; + } + + /** + * Map CRCE Diff instance to JAXB + * + * @param diff + * @return + */ + private cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Diff mapDiff(Diff diff) { + cz.zcu.kiv.crce.rest.internal.jaxb.compatibility.Diff jaxbDiff = compatibilityObjectFactory.createDiff(); + + jaxbDiff.setName(diff.getName()); + jaxbDiff.setNamespace(diff.getNamespace()); + //display only on package level + if (diff.getLevel() == DifferenceLevel.PACKAGE) { + jaxbDiff.setSyntax(diff.getSyntax()); + } + jaxbDiff.setValue(diff.getValue().name()); + jaxbDiff.setLevel(diff.getLevel().toString()); + if (diff.getRole() != null) { + jaxbDiff.setRole(diff.getRole().toString()); + } + + List children = jaxbDiff.getDifves(); + for (Diff d : diff.getChildren()) { + children.add(mapDiff(d)); + } + + return jaxbDiff; + } + +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/JaxbMapping.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/JaxbMapping.java index 6efe98c0..eda5fad2 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/JaxbMapping.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/JaxbMapping.java @@ -1,315 +1,315 @@ -package cz.zcu.kiv.crce.rest.internal.mapping; - -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.UriInfo; - -import org.apache.felix.dm.annotation.api.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Operator; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; - -/** - * Convert cz.zcu.kiv.crce.metadata.Resource to bean classes with JAXB annotations. These bean classes are ready to export metadata to xml. - * - * @author Jan Reznicek - * - */ -@Component(provides = JaxbMapping.class) -public class JaxbMapping { - - private static final Logger logger = LoggerFactory.getLogger(JaxbMapping.class); // NOPMD - - public static final String OSGI_IDENTITY_CAP_NAME = "osgi.identity"; - public static final String OSGI_CONTENT_CAP_NAME = "osgi.content"; - public static final String CRCE_IDENTITY_CAP_NAME = "crce.identity"; - public static final String OSGI_WIRING_NAME = "osgi.wiring.package"; - public static final String OSGI_WIRING_BUNDLE = "osgi.wiring.bundle"; - public static final String CRCE_METRICS_NAME = "crce.metrics"; - - private final ObjectFactory metadataObjectFactory = new ObjectFactory(); - - private final CompatibilityMapper compatibilityMapper = new CompatibilityMapper(); - - /** - * Default host, should not be needed, information is gained from request context. But is there for sure TODO: add default rest host to - * CRCE config file - */ - public static final String DEFAULT_HOST = "http://localhost:8080/rest/"; // TODO this won't always work - - /** - * Get URL of resource, that could be uset for REST action GET Bundle. - * - * @param resource resource - * @param ui contextual info about URI - * @return URL of the resource - */ - private String getURL(Resource resource, UriInfo ui) { - MetadataService metadataService = Activator.instance().getMetadataService(); - String name = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY) - .getAttributeValue(NsOsgiIdentity.ATTRIBUTE__NAME); - - if (name == null) { - return null; - } - - if (ui == null) { - return DEFAULT_HOST + "bundle/" + name; - } - String url = ui.getBaseUri().toString(); - return url + "bundle/" + name; - } - - - /** - * Get cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource with unknown crce.status. - * This cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource contains only id and capability crce.identity with attribute crce.status, that - * is "unknown" - * - * @param id the resource id - * @return information about unknown resource - */ - public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource getResourceWithUnknownStatus(String id) { // TODO check purpose of this method - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource resource = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource(); - - resource.setId(id); - - List caps = resource.getCapabilities(); - - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability crceIdentity = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability(); - crceIdentity.setNamespace("crce.identity"); - List attributes = crceIdentity.getAttributes(); - - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute jaxbAttribute = metadataObjectFactory.createAttribute(); - jaxbAttribute.setName("name"); - jaxbAttribute.setValue(resource.getId()); - attributes.add(jaxbAttribute); - - jaxbAttribute = metadataObjectFactory.createAttribute(); - jaxbAttribute.setName("status"); - jaxbAttribute.setValue("unknown"); - attributes.add(jaxbAttribute); - - caps.add(crceIdentity); - - return resource; - } - - // TODO the following methods are candidates for a common OSGi service - - protected Version getBundleVersion(Resource resource) { - if (resource != null) { - List resCapabilities = resource.getCapabilities(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); - if (!resCapabilities.isEmpty()) { - return resCapabilities.get(0).getAttributeValue(NsOsgiBundle.ATTRIBUTE__VERSION); - } - } - return null; - } - - protected String getBundleSymbolicName(Resource resource) { - if (resource != null) { - List resCapabilities = resource.getCapabilities(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); - if (!resCapabilities.isEmpty()) { - return resCapabilities.get(0).getAttributeValue(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME); - } - } - return null; - } - - // new mappings - - public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository mapRepository(List resources, MetadataFilter filter, UriInfo uriInfo) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository jaxbRepository = metadataObjectFactory.createRepository(); - - jaxbRepository.setIncrement(0L); - jaxbRepository.setName("store"); - - for (Resource resource : resources) { - jaxbRepository.getResources().add(mapResource(resource, filter, uriInfo)); - } - return jaxbRepository; - } - - public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource mapResource(Resource resource, MetadataFilter filter, UriInfo uriInfo) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource jaxbResource = metadataObjectFactory.createResource(); - - jaxbResource.setId(resource.getId()); - - List jaxbCapabilities = jaxbResource.getCapabilities(); - - // #81: 'crce.identity' must precede all remaining capabilities - if (includeCapability(CRCE_IDENTITY_CAP_NAME, filter)) { - List capabilities = resource.getCapabilities(CRCE_IDENTITY_CAP_NAME); - if (!capabilities.isEmpty()) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = mapCapability(capabilities.get(0)); - String url = getURL(resource, uriInfo); - if (url != null) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute attribute = metadataObjectFactory.createAttribute(); - attribute.setName("url"); // TODO hardcoded - attribute.setValue(url); - jaxbCapability.getAttributes().add(attribute); - } - jaxbCapabilities.add(jaxbCapability); - } - } - - for (Capability capability : resource.getRootCapabilities()) { - if (CRCE_IDENTITY_CAP_NAME.equals(capability.getNamespace())) { - continue; - } - if (includeCapability(capability.getNamespace(), filter)) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = mapCapability(capability); - jaxbCapabilities.add(jaxbCapability); - } - } - - List jaxbRequirements = jaxbResource.getRequirements(); - for (Requirement requirement : resource.getRequirements()) { - if (includeRequirement(requirement.getNamespace(), filter)) { - jaxbRequirements.add(mapRequirement(requirement)); - } - } - - List jaxbProperties = jaxbResource.getProperties(); - for (Property property : resource.getProperties()) { - if (includeProperty(property.getNamespace(), filter)) { - jaxbProperties.add(mapProperty(property)); - } - } - if (includeProperty(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY, filter)) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property p = compatibilityMapper.mapCompatibility(resource); - if (p != null) { - jaxbProperties.add(p); - } - } - - - return jaxbResource; - } - - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability mapCapability(Capability capability) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = metadataObjectFactory.createCapability(); - - jaxbCapability.setNamespace(capability.getNamespace()); - jaxbCapability.setId(capability.getId()); - - List directives = jaxbCapability.getDirectives(); - for (Map.Entry entry : capability.getDirectives().entrySet()) { - directives.add(mapDirective(entry)); - } - - List attributes = jaxbCapability.getAttributes(); - for (Attribute attribute : capability.getAttributes()) { - attributes.add(mapAttribute(attribute)); - } - - List capabilities = jaxbCapability.getCapabilities(); - for (Capability child : capability.getChildren()) { - capabilities.add(mapCapability(child)); - } - - List properties = jaxbCapability.getProperties(); - for (Property property : capability.getProperties()) { - properties.add(mapProperty(property)); - } - - return jaxbCapability; - } - - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement mapRequirement(Requirement requirement) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement jaxbRequirement = metadataObjectFactory.createRequirement(); - - jaxbRequirement.setNamespace(requirement.getNamespace()); - jaxbRequirement.setId(requirement.getId()); - - List directives = jaxbRequirement.getDirectives(); - for (Map.Entry entry : requirement.getDirectives().entrySet()) { - directives.add(mapDirective(entry)); - } - - List attributes = jaxbRequirement.getAttributes(); - for (Attribute attribute : requirement.getAttributes()) { - attributes.add(mapAttribute(attribute)); - } - - List requirements = jaxbRequirement.getRequirements(); - for (Requirement child : requirement.getChildren()) { - requirements.add(mapRequirement(child)); - } - - return jaxbRequirement; - } - - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property mapProperty(Property property) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property jaxbProperty = metadataObjectFactory.createProperty(); - - jaxbProperty.setNamespace(property.getNamespace()); - jaxbProperty.setId(property.getId()); - - List attributes = jaxbProperty.getAttributes(); - for (Attribute attribute : property.getAttributes()) { - attributes.add(mapAttribute(attribute)); - } - - // links not implemented yet - - return jaxbProperty; - } - - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Directive mapDirective(Map.Entry entry) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Directive jaxbDirective = metadataObjectFactory.createDirective(); - - jaxbDirective.setName(entry.getKey()); - jaxbDirective.setValue(entry.getValue()); - - return jaxbDirective; - } - - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute mapAttribute(Attribute attribute) { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute jaxbAttribute = metadataObjectFactory.createAttribute(); - - jaxbAttribute.setName(attribute.getName()); - jaxbAttribute.setValue(attribute.getStringValue()); - if (!String.class.equals(attribute.getType())) { - jaxbAttribute.setType(attribute.getType().getSimpleName()); - } - if (!Operator.EQUAL.equals(attribute.getOperator())) { - jaxbAttribute.setOperator(attribute.getOperator().getValue()); - } - return jaxbAttribute; - } - - private boolean includeCapability(String namespace, MetadataFilter filter) { - if (filter.isCoreCapabilities() && (namespace.endsWith(".content") || namespace.endsWith(".identity"))) { - //core capability - return true; - } - - return filter.includeCapabilities() - && (filter.getCapabilityNamespace() == null || namespace.equals(filter.getCapabilityNamespace())); - } - - private boolean includeRequirement(String namespace, MetadataFilter filter) { - return filter.includeRequirements() - && (filter.getRequirementNamespace() == null || namespace.equals(filter.getRequirementNamespace())); - } - - private boolean includeProperty(String namespace, MetadataFilter filter) { - return filter.includeProperties() && (filter.getPropertyNamespace() == null || namespace.equals(filter.getPropertyNamespace())); - } -} +package cz.zcu.kiv.crce.rest.internal.mapping; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.UriInfo; + +import org.apache.felix.dm.annotation.api.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Operator; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; + +/** + * Convert cz.zcu.kiv.crce.metadata.Resource to bean classes with JAXB annotations. These bean classes are ready to export metadata to xml. + * + * @author Jan Reznicek + * + */ +@Component(provides = JaxbMapping.class) +public class JaxbMapping { + + private static final Logger logger = LoggerFactory.getLogger(JaxbMapping.class); // NOPMD + + public static final String OSGI_IDENTITY_CAP_NAME = "osgi.identity"; + public static final String OSGI_CONTENT_CAP_NAME = "osgi.content"; + public static final String CRCE_IDENTITY_CAP_NAME = "crce.identity"; + public static final String OSGI_WIRING_NAME = "osgi.wiring.package"; + public static final String OSGI_WIRING_BUNDLE = "osgi.wiring.bundle"; + public static final String CRCE_METRICS_NAME = "crce.metrics"; + + private final ObjectFactory metadataObjectFactory = new ObjectFactory(); + + private final CompatibilityMapper compatibilityMapper = new CompatibilityMapper(); + + /** + * Default host, should not be needed, information is gained from request context. But is there for sure TODO: add default rest host to + * CRCE config file + */ + public static final String DEFAULT_HOST = "http://localhost:8080/rest/"; // TODO this won't always work + + /** + * Get URL of resource, that could be uset for REST action GET Bundle. + * + * @param resource resource + * @param ui contextual info about URI + * @return URL of the resource + */ + private String getURL(Resource resource, UriInfo ui) { + MetadataService metadataService = Activator.instance().getMetadataService(); + String name = metadataService.getSingletonCapability(resource, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY) + .getAttributeValue(NsOsgiIdentity.ATTRIBUTE__NAME); + + if (name == null) { + return null; + } + + if (ui == null) { + return DEFAULT_HOST + "bundle/" + name; + } + String url = ui.getBaseUri().toString(); + return url + "bundle/" + name; + } + + + /** + * Get cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource with unknown crce.status. + * This cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource contains only id and capability crce.identity with attribute crce.status, that + * is "unknown" + * + * @param id the resource id + * @return information about unknown resource + */ + public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource getResourceWithUnknownStatus(String id) { // TODO check purpose of this method + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource resource = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource(); + + resource.setId(id); + + List caps = resource.getCapabilities(); + + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability crceIdentity = new cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability(); + crceIdentity.setNamespace("crce.identity"); + List attributes = crceIdentity.getAttributes(); + + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute jaxbAttribute = metadataObjectFactory.createAttribute(); + jaxbAttribute.setName("name"); + jaxbAttribute.setValue(resource.getId()); + attributes.add(jaxbAttribute); + + jaxbAttribute = metadataObjectFactory.createAttribute(); + jaxbAttribute.setName("status"); + jaxbAttribute.setValue("unknown"); + attributes.add(jaxbAttribute); + + caps.add(crceIdentity); + + return resource; + } + + // TODO the following methods are candidates for a common OSGi service + + protected Version getBundleVersion(Resource resource) { + if (resource != null) { + List resCapabilities = resource.getCapabilities(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); + if (!resCapabilities.isEmpty()) { + return resCapabilities.get(0).getAttributeValue(NsOsgiBundle.ATTRIBUTE__VERSION); + } + } + return null; + } + + protected String getBundleSymbolicName(Resource resource) { + if (resource != null) { + List resCapabilities = resource.getCapabilities(NsOsgiBundle.NAMESPACE__OSGI_BUNDLE); + if (!resCapabilities.isEmpty()) { + return resCapabilities.get(0).getAttributeValue(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME); + } + } + return null; + } + + // new mappings + + public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository mapRepository(List resources, MetadataFilter filter, UriInfo uriInfo) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository jaxbRepository = metadataObjectFactory.createRepository(); + + jaxbRepository.setIncrement(0L); + jaxbRepository.setName("store"); + + for (Resource resource : resources) { + jaxbRepository.getResources().add(mapResource(resource, filter, uriInfo)); + } + return jaxbRepository; + } + + public cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource mapResource(Resource resource, MetadataFilter filter, UriInfo uriInfo) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource jaxbResource = metadataObjectFactory.createResource(); + + jaxbResource.setId(resource.getId()); + + List jaxbCapabilities = jaxbResource.getCapabilities(); + + // #81: 'crce.identity' must precede all remaining capabilities + if (includeCapability(CRCE_IDENTITY_CAP_NAME, filter)) { + List capabilities = resource.getCapabilities(CRCE_IDENTITY_CAP_NAME); + if (!capabilities.isEmpty()) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = mapCapability(capabilities.get(0)); + String url = getURL(resource, uriInfo); + if (url != null) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute attribute = metadataObjectFactory.createAttribute(); + attribute.setName("url"); // TODO hardcoded + attribute.setValue(url); + jaxbCapability.getAttributes().add(attribute); + } + jaxbCapabilities.add(jaxbCapability); + } + } + + for (Capability capability : resource.getRootCapabilities()) { + if (CRCE_IDENTITY_CAP_NAME.equals(capability.getNamespace())) { + continue; + } + if (includeCapability(capability.getNamespace(), filter)) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = mapCapability(capability); + jaxbCapabilities.add(jaxbCapability); + } + } + + List jaxbRequirements = jaxbResource.getRequirements(); + for (Requirement requirement : resource.getRequirements()) { + if (includeRequirement(requirement.getNamespace(), filter)) { + jaxbRequirements.add(mapRequirement(requirement)); + } + } + + List jaxbProperties = jaxbResource.getProperties(); + for (Property property : resource.getProperties()) { + if (includeProperty(property.getNamespace(), filter)) { + jaxbProperties.add(mapProperty(property)); + } + } + if (includeProperty(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY, filter)) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property p = compatibilityMapper.mapCompatibility(resource); + if (p != null) { + jaxbProperties.add(p); + } + } + + + return jaxbResource; + } + + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability mapCapability(Capability capability) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability jaxbCapability = metadataObjectFactory.createCapability(); + + jaxbCapability.setNamespace(capability.getNamespace()); + jaxbCapability.setId(capability.getId()); + + List directives = jaxbCapability.getDirectives(); + for (Map.Entry entry : capability.getDirectives().entrySet()) { + directives.add(mapDirective(entry)); + } + + List attributes = jaxbCapability.getAttributes(); + for (Attribute attribute : capability.getAttributes()) { + attributes.add(mapAttribute(attribute)); + } + + List capabilities = jaxbCapability.getCapabilities(); + for (Capability child : capability.getChildren()) { + capabilities.add(mapCapability(child)); + } + + List properties = jaxbCapability.getProperties(); + for (Property property : capability.getProperties()) { + properties.add(mapProperty(property)); + } + + return jaxbCapability; + } + + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement mapRequirement(Requirement requirement) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement jaxbRequirement = metadataObjectFactory.createRequirement(); + + jaxbRequirement.setNamespace(requirement.getNamespace()); + jaxbRequirement.setId(requirement.getId()); + + List directives = jaxbRequirement.getDirectives(); + for (Map.Entry entry : requirement.getDirectives().entrySet()) { + directives.add(mapDirective(entry)); + } + + List attributes = jaxbRequirement.getAttributes(); + for (Attribute attribute : requirement.getAttributes()) { + attributes.add(mapAttribute(attribute)); + } + + List requirements = jaxbRequirement.getRequirements(); + for (Requirement child : requirement.getChildren()) { + requirements.add(mapRequirement(child)); + } + + return jaxbRequirement; + } + + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property mapProperty(Property property) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Property jaxbProperty = metadataObjectFactory.createProperty(); + + jaxbProperty.setNamespace(property.getNamespace()); + jaxbProperty.setId(property.getId()); + + List attributes = jaxbProperty.getAttributes(); + for (Attribute attribute : property.getAttributes()) { + attributes.add(mapAttribute(attribute)); + } + + // links not implemented yet + + return jaxbProperty; + } + + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Directive mapDirective(Map.Entry entry) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Directive jaxbDirective = metadataObjectFactory.createDirective(); + + jaxbDirective.setName(entry.getKey()); + jaxbDirective.setValue(entry.getValue()); + + return jaxbDirective; + } + + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute mapAttribute(Attribute attribute) { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute jaxbAttribute = metadataObjectFactory.createAttribute(); + + jaxbAttribute.setName(attribute.getName()); + jaxbAttribute.setValue(attribute.getStringValue()); + if (!String.class.equals(attribute.getType())) { + jaxbAttribute.setType(attribute.getType().getSimpleName()); + } + if (!Operator.EQUAL.equals(attribute.getOperator())) { + jaxbAttribute.setOperator(attribute.getOperator().getValue()); + } + return jaxbAttribute; + } + + private boolean includeCapability(String namespace, MetadataFilter filter) { + if (filter.isCoreCapabilities() && (namespace.endsWith(".content") || namespace.endsWith(".identity"))) { + //core capability + return true; + } + + return filter.includeCapabilities() + && (filter.getCapabilityNamespace() == null || namespace.equals(filter.getCapabilityNamespace())); + } + + private boolean includeRequirement(String namespace, MetadataFilter filter) { + return filter.includeRequirements() + && (filter.getRequirementNamespace() == null || namespace.equals(filter.getRequirementNamespace())); + } + + private boolean includeProperty(String namespace, MetadataFilter filter) { + return filter.includeProperties() && (filter.getPropertyNamespace() == null || namespace.equals(filter.getPropertyNamespace())); + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/MetadataFilter.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/MetadataFilter.java index 63590d8a..38aa1683 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/MetadataFilter.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/mapping/MetadataFilter.java @@ -1,106 +1,106 @@ -package cz.zcu.kiv.crce.rest.internal.mapping; - -/** - * Filter criteria for GET Metadata operation. - * - * Filter criteria determines, which parts of XML with metedata should be included. - * - * - * @author Jan Reznicek - * - */ -public class MetadataFilter { - - private boolean coreCapabilities; - - private boolean includeCapabilities; - private String capabilityNamespace; - - private boolean includeRequirements; - private String requirementNamespace; - - private boolean includeProperties; - private String propertyNamespace; - - /** - * At default, including of each part of metadata is set to false. - */ - public MetadataFilter() { - coreCapabilities = false; - - includeCapabilities = false; - capabilityNamespace = null; - - includeRequirements = false; - requirementNamespace = null; - - includeProperties = false; - propertyNamespace = null; - } - - public boolean isCoreCapabilities() { - return coreCapabilities; - } - - public void setCoreCapabilities(boolean coreCapabilities) { - this.coreCapabilities = coreCapabilities; - } - - public boolean includeCapabilities() { - return includeCapabilities; - } - - public void setIncludeCapabilities(boolean includeCapabilities) { - this.includeCapabilities = includeCapabilities; - } - - public String getCapabilityNamespace() { - return capabilityNamespace; - } - - public void setCapabilityNamespace(String capabilityNamespace) { - this.capabilityNamespace = capabilityNamespace; - } - - public boolean includeRequirements() { - return includeRequirements; - } - - public void setIncludeRequirements(boolean includeRequirements) { - this.includeRequirements = includeRequirements; - } - - public String getRequirementNamespace() { - return requirementNamespace; - } - - public void setRequirementNamespace(String requirementNamespace) { - this.requirementNamespace = requirementNamespace; - } - - public boolean includeProperties() { - return includeProperties; - } - - public void setIncludeProperties(boolean includeProperties) { - this.includeProperties = includeProperties; - } - - public String getPropertyNamespace() { - return propertyNamespace; - } - - public void setPropertyNamespace(String propertyNamespace) { - this.propertyNamespace = propertyNamespace; - } - - /** - * Include all parts of metadata. - */ - public void includeAll() { - coreCapabilities = true; - includeCapabilities = true; - includeRequirements = true; - includeProperties = true; - } -} +package cz.zcu.kiv.crce.rest.internal.mapping; + +/** + * Filter criteria for GET Metadata operation. + * + * Filter criteria determines, which parts of XML with metedata should be included. + * + * + * @author Jan Reznicek + * + */ +public class MetadataFilter { + + private boolean coreCapabilities; + + private boolean includeCapabilities; + private String capabilityNamespace; + + private boolean includeRequirements; + private String requirementNamespace; + + private boolean includeProperties; + private String propertyNamespace; + + /** + * At default, including of each part of metadata is set to false. + */ + public MetadataFilter() { + coreCapabilities = false; + + includeCapabilities = false; + capabilityNamespace = null; + + includeRequirements = false; + requirementNamespace = null; + + includeProperties = false; + propertyNamespace = null; + } + + public boolean isCoreCapabilities() { + return coreCapabilities; + } + + public void setCoreCapabilities(boolean coreCapabilities) { + this.coreCapabilities = coreCapabilities; + } + + public boolean includeCapabilities() { + return includeCapabilities; + } + + public void setIncludeCapabilities(boolean includeCapabilities) { + this.includeCapabilities = includeCapabilities; + } + + public String getCapabilityNamespace() { + return capabilityNamespace; + } + + public void setCapabilityNamespace(String capabilityNamespace) { + this.capabilityNamespace = capabilityNamespace; + } + + public boolean includeRequirements() { + return includeRequirements; + } + + public void setIncludeRequirements(boolean includeRequirements) { + this.includeRequirements = includeRequirements; + } + + public String getRequirementNamespace() { + return requirementNamespace; + } + + public void setRequirementNamespace(String requirementNamespace) { + this.requirementNamespace = requirementNamespace; + } + + public boolean includeProperties() { + return includeProperties; + } + + public void setIncludeProperties(boolean includeProperties) { + this.includeProperties = includeProperties; + } + + public String getPropertyNamespace() { + return propertyNamespace; + } + + public void setPropertyNamespace(String propertyNamespace) { + this.propertyNamespace = propertyNamespace; + } + + /** + * Include all parts of metadata. + */ + public void includeAll() { + coreCapabilities = true; + includeCapabilities = true; + includeRequirements = true; + includeProperties = true; + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/structures/VersionDemand.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/structures/VersionDemand.java index 52c9bb38..a4549bba 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/structures/VersionDemand.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/structures/VersionDemand.java @@ -1,41 +1,41 @@ -package cz.zcu.kiv.crce.rest.internal.structures; - -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Representation one of requirement's version demands. - * In metadata, version demand is version attribute inside osgi.wiring.package requirement. - * - * Example im metadata: - * - * @author Jan reznicek - * - */ -public class VersionDemand { - - public static final String GREATER_THAN = "greater-than"; - public static final String LESS_THAN = "less-than"; - public static final String EQUEAL = "equal"; - public static final String LESS_EQUEAL = "less-equal"; - public static final String GREATER_EQUEAL = "greater-equal"; - public static final String NOT_EQUEAL = "not-equal"; - - private Version version; - private String operation; - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } -} +package cz.zcu.kiv.crce.rest.internal.structures; + +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Representation one of requirement's version demands. + * In metadata, version demand is version attribute inside osgi.wiring.package requirement. + * + * Example im metadata: + * + * @author Jan reznicek + * + */ +public class VersionDemand { + + public static final String GREATER_THAN = "greater-than"; + public static final String LESS_THAN = "less-than"; + public static final String EQUEAL = "equal"; + public static final String LESS_EQUEAL = "less-equal"; + public static final String GREATER_EQUEAL = "greater-equal"; + public static final String NOT_EQUEAL = "not-equal"; + + private Version version; + private String operation; + + public Version getVersion() { + return version; + } + + public void setVersion(Version version) { + this.version = version; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/BundleResource.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/BundleResource.java index 94ad2d7b..df8c8ba3 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/BundleResource.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/BundleResource.java @@ -1,256 +1,256 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.GetBundle; - - -/** - * Server will provide a single bundle. - * - * @author Jan Reznicek - */ -@Path("/bundle") -public class BundleResource extends ResourceParent implements GetBundle { - - private static final Logger logger = LoggerFactory.getLogger(BundleResource.class); - - /** - * size of buffer between input an output stream for a bundle - */ - private static final int BUFSIZE = 1024; - - /** - * Create output stream from bundle - * - * @param resourceFile file with bundle - * @return output stream with bundle - * @throws WebApplicationException exception during converting bundle to output stream - */ - private StreamingOutput getBundleAsStream(final File resourceFile) throws WebApplicationException { - return new StreamingOutput() { - @Override - public void write(OutputStream output) throws IOException, WebApplicationException { - - try (DataInputStream resourceInput = new DataInputStream(new FileInputStream(resourceFile)); - OutputStream resourceOutput = new BufferedOutputStream(output)) { - - byte[] buffer = new byte[BUFSIZE]; - int bytesRead; - while ((bytesRead = resourceInput.read(buffer)) != -1) { - resourceOutput.write(buffer, 0, bytesRead); - } - resourceOutput.flush(); - } catch (RuntimeException e) { - - logger.warn("Request ({}) - Converting bundle to output stream failed.", getRequestId()); - - throw new WebApplicationException(e, 500); - } - } - }; - } - - /** - * Create file name of resource. - * Used for resources, whose original file name is unknown. - * - * @param resource resource - * @return file name of resource - */ - private String createFileName(Resource resource) { - String id = resource.getId(); - - List categories = Activator.instance().getMetadataService().getCategories(resource); - if (categories.contains("osgi")) { - return id + ".jar"; - } - if (categories.contains("zip")) { - return id + ".zip"; - } else { - return id; - } - } - - /** - * Get file name from resource. - * If original file name is unknown, create name from resource id. - * - * @param resource resource - * @return resource file name - */ - private String getFileName(Resource resource) { - try { - return Activator.instance().getMetadataService().getFileName(resource); - } catch (IllegalStateException e) { - logger.warn("File name is unknown, it will be generated", e); - return createFileName(resource); - } - } - - /** - * Create response with bundle by filter. - * Find bundle according LDAP filter in store repository and return him as output stream. - * - * @param requirement LDAP filter - * @return bundle as output stream - * @throws WebApplicationException some exception, contains html error status - */ - private Response responseByRequirement(Requirement requirement) throws WebApplicationException { - - logger.debug("Request ({}) - Get bundle by filter: {}", getRequestId(), requirement); - - Resource resource = findSingleBundleByFilterWithHighestVersion(requirement); - - final File resourceFile = new File(Activator.instance().getMetadataService().getUri(resource)); - - StreamingOutput output = getBundleAsStream(resourceFile); - - MetadataService metadataService = Activator.instance().getMetadataService(); - Attribute attribute = metadataService.getIdentity(resource) - .getAttribute(new SimpleAttributeType<>("mime", String.class)); // TODO create attribute type - - Response response = - Response.ok(output) - .type(attribute != null ? attribute.getValue() : MediaType.APPLICATION_OCTET_STREAM) - .header("content-disposition", "attachment; filename = " + getFileName(resource)) - .build(); - - return response; - } - - /** - * Get bundle by id. - * URI is /bundle/id. - * - * @param id id of a bundle - * @return bundle or error response - */ - @GET - @Path("{id}") - @Override - public Response getBundleById(@PathParam("id") String id) { - newRequest(); - logger.debug("Request ({}) - Get bundle by id request was received.", getRequestId()); - - Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); - - try { - Response response = responseByRequirement(requirement); - - logger.debug("Request ({}) - Response was successfully created.", getRequestId()); - - return response; - - } catch (WebApplicationException e) { - return e.getResponse(); - } - } - - /** - * Return bundle specified by name and version. - * If version is not set, select the one with highest version. - * - * @param name name of bundle - * @param version version of bundle - * @return bundle or error response - */ - @GET - @Override - public Response getBundlebyNameAndVersion(@QueryParam("name") String name, @QueryParam("version") String version) { - newRequest(); - - logger.debug("Request ({}) - Get bundle by name and version request was received.", getRequestId()); - - Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - - if (name == null) { - logger.debug("Request ({}) - Wrong request, name of requested bundle has to be set.", getRequestId()); - return Response.status(400).build(); - } - - requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, name); - - if (version != null) { - requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, new Version(version)); - } - - try { - Response response = responseByRequirement(requirement); - - logger.debug("Request ({}) - Response was successfully created.", getRequestId()); - - return response; - } catch (WebApplicationException e) { - return e.getResponse(); - } - } - - /** - * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. - * - * @param uploadedInputStream file stream - * @param fileDetail file headers - * @param req request - * @return OK if success, 403 otherwise - */ - @POST - @Consumes(MediaType.MULTIPART_FORM_DATA) - public Response uploadBundle(@FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @Context HttpServletRequest req) { - newRequest(); - logger.debug("Get buffer for uploadBundle request {}.", getRequestId()); - Buffer b = Activator.instance().getBuffer(req); - - String filename = fileDetail.getFileName(); - logger.debug("Uploaded filename: {}", filename); - try { - b.put(filename, uploadedInputStream); - b.commit(true); - } catch (IOException | RefusedArtifactException e) { - logger.error("Error during resource upload.", e); - return Response.status(403).build(); - } - - logger.debug("Upload of bundle via REST successful."); - return Response.ok().build(); - } -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.GetBundle; + + +/** + * Server will provide a single bundle. + * + * @author Jan Reznicek + */ +@Path("/bundle") +public class BundleResource extends ResourceParent implements GetBundle { + + private static final Logger logger = LoggerFactory.getLogger(BundleResource.class); + + /** + * size of buffer between input an output stream for a bundle + */ + private static final int BUFSIZE = 1024; + + /** + * Create output stream from bundle + * + * @param resourceFile file with bundle + * @return output stream with bundle + * @throws WebApplicationException exception during converting bundle to output stream + */ + private StreamingOutput getBundleAsStream(final File resourceFile) throws WebApplicationException { + return new StreamingOutput() { + @Override + public void write(OutputStream output) throws IOException, WebApplicationException { + + try (DataInputStream resourceInput = new DataInputStream(new FileInputStream(resourceFile)); + OutputStream resourceOutput = new BufferedOutputStream(output)) { + + byte[] buffer = new byte[BUFSIZE]; + int bytesRead; + while ((bytesRead = resourceInput.read(buffer)) != -1) { + resourceOutput.write(buffer, 0, bytesRead); + } + resourceOutput.flush(); + } catch (RuntimeException e) { + + logger.warn("Request ({}) - Converting bundle to output stream failed.", getRequestId()); + + throw new WebApplicationException(e, 500); + } + } + }; + } + + /** + * Create file name of resource. + * Used for resources, whose original file name is unknown. + * + * @param resource resource + * @return file name of resource + */ + private String createFileName(Resource resource) { + String id = resource.getId(); + + List categories = Activator.instance().getMetadataService().getCategories(resource); + if (categories.contains("osgi")) { + return id + ".jar"; + } + if (categories.contains("zip")) { + return id + ".zip"; + } else { + return id; + } + } + + /** + * Get file name from resource. + * If original file name is unknown, create name from resource id. + * + * @param resource resource + * @return resource file name + */ + private String getFileName(Resource resource) { + try { + return Activator.instance().getMetadataService().getFileName(resource); + } catch (IllegalStateException e) { + logger.warn("File name is unknown, it will be generated", e); + return createFileName(resource); + } + } + + /** + * Create response with bundle by filter. + * Find bundle according LDAP filter in store repository and return him as output stream. + * + * @param requirement LDAP filter + * @return bundle as output stream + * @throws WebApplicationException some exception, contains html error status + */ + private Response responseByRequirement(Requirement requirement) throws WebApplicationException { + + logger.debug("Request ({}) - Get bundle by filter: {}", getRequestId(), requirement); + + Resource resource = findSingleBundleByFilterWithHighestVersion(requirement); + + final File resourceFile = new File(Activator.instance().getMetadataService().getUri(resource)); + + StreamingOutput output = getBundleAsStream(resourceFile); + + MetadataService metadataService = Activator.instance().getMetadataService(); + Attribute attribute = metadataService.getIdentity(resource) + .getAttribute(new SimpleAttributeType<>("mime", String.class)); // TODO create attribute type + + Response response = + Response.ok(output) + .type(attribute != null ? attribute.getValue() : MediaType.APPLICATION_OCTET_STREAM) + .header("content-disposition", "attachment; filename = " + getFileName(resource)) + .build(); + + return response; + } + + /** + * Get bundle by id. + * URI is /bundle/id. + * + * @param id id of a bundle + * @return bundle or error response + */ + @GET + @Path("{id}") + @Override + public Response getBundleById(@PathParam("id") String id) { + newRequest(); + logger.debug("Request ({}) - Get bundle by id request was received.", getRequestId()); + + Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); + + try { + Response response = responseByRequirement(requirement); + + logger.debug("Request ({}) - Response was successfully created.", getRequestId()); + + return response; + + } catch (WebApplicationException e) { + return e.getResponse(); + } + } + + /** + * Return bundle specified by name and version. + * If version is not set, select the one with highest version. + * + * @param name name of bundle + * @param version version of bundle + * @return bundle or error response + */ + @GET + @Override + public Response getBundlebyNameAndVersion(@QueryParam("name") String name, @QueryParam("version") String version) { + newRequest(); + + logger.debug("Request ({}) - Get bundle by name and version request was received.", getRequestId()); + + Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + + if (name == null) { + logger.debug("Request ({}) - Wrong request, name of requested bundle has to be set.", getRequestId()); + return Response.status(400).build(); + } + + requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, name); + + if (version != null) { + requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, new Version(version)); + } + + try { + Response response = responseByRequirement(requirement); + + logger.debug("Request ({}) - Response was successfully created.", getRequestId()); + + return response; + } catch (WebApplicationException e) { + return e.getResponse(); + } + } + + /** + * Allows sw upload of bundles into CRCE. Automatically saves the bundle into buffer and commits it to store. + * + * @param uploadedInputStream file stream + * @param fileDetail file headers + * @param req request + * @return OK if success, 403 otherwise + */ + @POST + @Consumes(MediaType.MULTIPART_FORM_DATA) + public Response uploadBundle(@FormDataParam("file") InputStream uploadedInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context HttpServletRequest req) { + newRequest(); + logger.debug("Get buffer for uploadBundle request {}.", getRequestId()); + Buffer b = Activator.instance().getBuffer(req); + + String filename = fileDetail.getFileName(); + logger.debug("Uploaded filename: {}", filename); + try { + b.put(filename, uploadedInputStream); + b.commit(true); + } catch (IOException | RefusedArtifactException e) { + logger.error("Error during resource upload.", e); + return Response.status(403).build(); + } + + logger.debug("Upload of bundle via REST successful."); + return Response.ok().build(); + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/MetadataResource.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/MetadataResource.java index f0fa7c52..ef5ce0dc 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/MetadataResource.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/MetadataResource.java @@ -1,181 +1,181 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.osgi.framework.InvalidSyntaxException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.GetMetadata; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; -import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; - -/** - * Server will provide a metadata information about resources in the repository. - * - * @author Jan Reznicek - */ -@Path("/metadata") -public class MetadataResource extends ResourceParent implements GetMetadata { - - private static final Logger logger = LoggerFactory.getLogger(MetadataResource.class); - - - @GET - @Produces({MediaType.APPLICATION_XML}) - @Override - public Response getMetadata( - @QueryParam("filter") String filter, - @QueryParam("core") String core, - @QueryParam("cap") String cap, - @QueryParam("req") String req, - @QueryParam("prop") String prop, - @Context UriInfo ui) { - - newRequest(); - logger.debug("Request ({}) - Get metadata request was received.", getRequestId()); - - List storeResources; - - MetadataFilter include = new MetadataFilter(); - - if (core == null && cap == null && req == null && prop == null) { - //include all - include.includeAll(); - } else { - if (core != null) { - include.setCoreCapabilities(true); - } - if (cap != null) { - include.setIncludeCapabilities(true); - if (cap.length() > 0) { - include.setCapabilityNamespace(cap); - } - } - if (req != null) { - include.setIncludeRequirements(true); - if (req.length() > 0) { - include.setRequirementNamespace(req); - } - } - if (prop != null) { - include.setIncludeProperties(true); - if (prop.length() > 0) { - include.setPropertyNamespace(prop); - } - } - } - - - try { - if (filter != null) { - Requirement requirement = Activator.instance().getFilterParser().parse(filter, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - logger.debug("Filter used to get metadata: {}.", filter); - storeResources = Activator.instance().getStore().getResources(requirement); - } else { - storeResources = Activator.instance().getStore().getResources(); - } - - if (!storeResources.isEmpty()) { - Repository repository = Activator.instance().getConvertorToBeans().mapRepository(storeResources, include, ui); - Response response = Response.ok(createXML(repository)).build(); - logger.debug("Request ({}) - Response was successfully created.", getRequestId()); - return response; - } else { - logger.debug("Request ({}) - No resource was found.", getRequestId()); - return Response.status(404).build(); - } - } catch (WebApplicationException e) { - return e.getResponse(); - } catch (InvalidSyntaxException e) { - logger.warn("Request ({}) - Invalid syntax of request LDAP filter.", getRequestId()); - logger.debug(e.getMessage(), e); - return Response.status(400).build(); - } - } - - - @GET - @Path("{id}") - @Produces({MediaType.APPLICATION_XML}) - @Override - public Response getMetadataById( - @PathParam("id") String id, - @QueryParam("core") String core, - @QueryParam("cap") String cap, - @QueryParam("req") String req, - @QueryParam("prop") String prop, - @Context UriInfo uriInfo) { - - newRequest(); - logger.debug("Request ({}) - Get metadata request for resource with id {} was received.", getRequestId(), id); - - MetadataFilter filter = new MetadataFilter(); - - if (core == null && cap == null && req == null && prop == null) { - //include all - filter.includeAll(); - } else { - if (core != null) { - filter.setCoreCapabilities(true); - } - if (cap != null) { - filter.setIncludeCapabilities(true); - if (cap.length() > 0) { - filter.setCapabilityNamespace(cap); - } - } - if (req != null) { - filter.setIncludeRequirements(true); - if (req.length() > 0) { - filter.setRequirementNamespace(req); - } - } - if (prop != null) { - filter.setIncludeProperties(true); - if (prop.length() > 0) { - filter.setPropertyNamespace(prop); - } - } - } - - try { - Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); - - List resources = Activator.instance().getStore().getResources(requirement); - - try { - if (!resources.isEmpty()) { - Repository repository = Activator.instance().getConvertorToBeans().mapRepository(resources, filter, uriInfo); - Response response = Response.ok(createXML(repository)).build(); - logger.debug("Request ({}) - Response was successfully created.", getRequestId()); - return response; - } else { - logger.debug("Request ({}) - No resource was found.", getRequestId()); - return Response.status(404).build(); - } - } catch (WebApplicationException e) { - return e.getResponse(); - } - } catch (Exception e) { - logger.error("Request ({}) - Could not get resources from store.", getRequestId(), e); - throw new WebApplicationException(500); - } - } -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.osgi.framework.InvalidSyntaxException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.GetMetadata; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; +import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; + +/** + * Server will provide a metadata information about resources in the repository. + * + * @author Jan Reznicek + */ +@Path("/metadata") +public class MetadataResource extends ResourceParent implements GetMetadata { + + private static final Logger logger = LoggerFactory.getLogger(MetadataResource.class); + + + @GET + @Produces({MediaType.APPLICATION_XML}) + @Override + public Response getMetadata( + @QueryParam("filter") String filter, + @QueryParam("core") String core, + @QueryParam("cap") String cap, + @QueryParam("req") String req, + @QueryParam("prop") String prop, + @Context UriInfo ui) { + + newRequest(); + logger.debug("Request ({}) - Get metadata request was received.", getRequestId()); + + List storeResources; + + MetadataFilter include = new MetadataFilter(); + + if (core == null && cap == null && req == null && prop == null) { + //include all + include.includeAll(); + } else { + if (core != null) { + include.setCoreCapabilities(true); + } + if (cap != null) { + include.setIncludeCapabilities(true); + if (cap.length() > 0) { + include.setCapabilityNamespace(cap); + } + } + if (req != null) { + include.setIncludeRequirements(true); + if (req.length() > 0) { + include.setRequirementNamespace(req); + } + } + if (prop != null) { + include.setIncludeProperties(true); + if (prop.length() > 0) { + include.setPropertyNamespace(prop); + } + } + } + + + try { + if (filter != null) { + Requirement requirement = Activator.instance().getFilterParser().parse(filter, NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + logger.debug("Filter used to get metadata: {}.", filter); + storeResources = Activator.instance().getStore().getResources(requirement); + } else { + storeResources = Activator.instance().getStore().getResources(); + } + + if (!storeResources.isEmpty()) { + Repository repository = Activator.instance().getConvertorToBeans().mapRepository(storeResources, include, ui); + Response response = Response.ok(createXML(repository)).build(); + logger.debug("Request ({}) - Response was successfully created.", getRequestId()); + return response; + } else { + logger.debug("Request ({}) - No resource was found.", getRequestId()); + return Response.status(404).build(); + } + } catch (WebApplicationException e) { + return e.getResponse(); + } catch (InvalidSyntaxException e) { + logger.warn("Request ({}) - Invalid syntax of request LDAP filter.", getRequestId()); + logger.debug(e.getMessage(), e); + return Response.status(400).build(); + } + } + + + @GET + @Path("{id}") + @Produces({MediaType.APPLICATION_XML}) + @Override + public Response getMetadataById( + @PathParam("id") String id, + @QueryParam("core") String core, + @QueryParam("cap") String cap, + @QueryParam("req") String req, + @QueryParam("prop") String prop, + @Context UriInfo uriInfo) { + + newRequest(); + logger.debug("Request ({}) - Get metadata request for resource with id {} was received.", getRequestId(), id); + + MetadataFilter filter = new MetadataFilter(); + + if (core == null && cap == null && req == null && prop == null) { + //include all + filter.includeAll(); + } else { + if (core != null) { + filter.setCoreCapabilities(true); + } + if (cap != null) { + filter.setIncludeCapabilities(true); + if (cap.length() > 0) { + filter.setCapabilityNamespace(cap); + } + } + if (req != null) { + filter.setIncludeRequirements(true); + if (req.length() > 0) { + filter.setRequirementNamespace(req); + } + } + if (prop != null) { + filter.setIncludeProperties(true); + if (prop.length() > 0) { + filter.setPropertyNamespace(prop); + } + } + } + + try { + Requirement requirement = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + requirement.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); + + List resources = Activator.instance().getStore().getResources(requirement); + + try { + if (!resources.isEmpty()) { + Repository repository = Activator.instance().getConvertorToBeans().mapRepository(resources, filter, uriInfo); + Response response = Response.ok(createXML(repository)).build(); + logger.debug("Request ({}) - Response was successfully created.", getRequestId()); + return response; + } else { + logger.debug("Request ({}) - No resource was found.", getRequestId()); + return Response.status(404).build(); + } + } catch (WebApplicationException e) { + return e.getResponse(); + } + } catch (Exception e) { + logger.error("Request ({}) - Could not get resources from store.", getRequestId(), e); + throw new WebApplicationException(500); + } + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/OtherBundlesMetadataResource.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/OtherBundlesMetadataResource.java index 8c4f4878..47dce254 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/OtherBundlesMetadataResource.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/OtherBundlesMetadataResource.java @@ -1,231 +1,231 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.PostOtherBundlesMetadata; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; -import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; - -/** - * Server provide metadata about other bundles (repository contents diff). - *

- * When the client asks CRCE to provide bundle metadata of those bundles which - * it does not know about and sends a list of bundle identifiers (= those - * bundles it knows about) and optionally sends a filter criteria specifying - * which subset of metadata it is interested in - *

- * Then CRCE sends that (subset of) metadata only for the following bundles - * currently available in repository in "stored" state: - *

    - *
  • are not in the list sent by client ("new bundles") - *
  • are in the list but have been removed from the repository - * ("deleted bundles" - just a list of bundle identifiers). - *
- * - * @author Jan Reznicek - */ -@Path("/other-bundles-metadata") -public class OtherBundlesMetadataResource extends ResourceParent implements PostOtherBundlesMetadata { - - private static final Logger log = LoggerFactory.getLogger(OtherBundlesMetadataResource.class); - - - /** - * Create XML String from repository. - * - * @param repository repository contains metadata about resources - * @return XML String with exported metadata - * @throws WebApplicationException unmarshal of xml failed. - */ - public Repository unmarshalXML(String repository) throws WebApplicationException { - - try { - ClassLoader cl = ObjectFactory.class.getClassLoader(); - JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl); - - Unmarshaller unmarshaller = jc.createUnmarshaller(); - - InputStream repositoryStream = new ByteArrayInputStream(repository.getBytes(DEF_ENCODING)); - Object obj = unmarshaller.unmarshal(repositoryStream); - - JAXBElement jxbE = (JAXBElement) obj; - - Repository rep = (Repository) jxbE.getValue(); - - return rep; - - } catch (UnsupportedEncodingException e) { - log.warn("Request ({}) - Unsuported encoding {}", getRequestId(), DEF_ENCODING); - log.debug(e.getMessage(), e); - throw new WebApplicationException(500); - - } catch (JAXBException e) { - log.info("Request ({}) - Post request XML unmarshal failed.", getRequestId()); - log.debug(e.getMessage(), e); - throw new WebApplicationException(400); - } - - } - - /** - * Create a set of id of all resources from repository. - * - * @param resources repository. - * @return set of id - */ - private Set createIdSet(Repository resources) { - List resList = resources.getResources(); - Set idSet = new HashSet<>(); - - for (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource res : resList) { - idSet.add(res.getId()); - } - - return idSet; - } - - /** - * Create a set of id of all resources from list of resources. - * - * @param resources list of resources. - * @return set of id - */ - private Set createIdSet(List resources) { - - Set idSet = new HashSet<>(); - - for (Resource res : resources) { - idSet.add(res.getId()); - } - - return idSet; - } - - /** - * Returns list of bundles, that are in storeResources, but not in clientBundlesIdSet. - * These bundles are new on store since last update of client bundles. - * - * @param storeResources list of bundles in the store - * @param clientBundlesIdSet set of id of bundles in the client - * @return list of bundles, that are new on store. - */ - private List findNewResources(List storeResources, Set clientBundlesIdSet) { - - List newResources = new ArrayList<>(); - - for (Resource res : storeResources) { - if (!clientBundlesIdSet.contains(res.getId())) { - newResources.add(res); - } - } - - return newResources; - } - - - /** - * Returns list of bundles, that are in clientResources, but not in storeIdset. - * These bundles was deleted from store since last update of client bundles. - * - * @param clientResources list of bundles in the client - * @param storeIdSet set of id of bundles in the store - * @return list of bundles, that have was deleted from store. - */ - private List determineUnknownResources( - List clientResources, Set storeIdSet) { - - List unknownResources = new ArrayList<>(); - for (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource res : clientResources) { - if (!storeIdSet.contains(res.getId())) { - unknownResources.add(Activator.instance().getConvertorToBeans().getResourceWithUnknownStatus(res.getId())); - } - } - - return unknownResources; - } - - - /** - * Return repository with other bundles (new to client). - * Other bundles are bundles currently available in repository in "stored" state: - *
    - *
  • are not in the list sent by client ("new bundles") - *
  • are in the list but have been removed from the repository ("deleted bundles" - just a list of bundle identifiers). - *
- * - * @param clientBundles - * @param ui contextual info about URI - * @return repositoty with other bundles - */ - private Repository findOtherBundles(Repository clientBundles, UriInfo ui) { - - List storeResources = Activator.instance().getStore().getResources(); - - Set clientBundlesIdSet = createIdSet(clientBundles); - Set storeIdSet = createIdSet(storeResources); - - List newResources = findNewResources(storeResources, clientBundlesIdSet); - List unknownResources = determineUnknownResources(clientBundles.getResources(), storeIdSet); - - //convert new resources to repository - MetadataFilter include = new MetadataFilter(); - include.includeAll(); - Repository repository = Activator.instance().getConvertorToBeans().mapRepository(newResources, include, ui); - - //add unknown resources - repository.getResources().addAll(unknownResources); - - return repository; - } - - - /** - * {@inheritDoc} - */ - @POST - @Consumes(MediaType.APPLICATION_XML) - @Produces({MediaType.APPLICATION_XML}) - @Override - public Response otherBundles(String knownBundles, @Context UriInfo ui) { - newRequest(); - log.debug("Request ({}) - Post other bundles request was received.", getRequestId()); - try { - Repository clientBundles = unmarshalXML(knownBundles); - Repository otherBundles = findOtherBundles(clientBundles, ui); - - Response response = Response.ok(createXML(otherBundles)).build(); - log.debug("Request ({}) - Response was successfully created.", getRequestId()); - return response; - - } catch (WebApplicationException e) { - - return e.getResponse(); - } - } -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.PostOtherBundlesMetadata; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; +import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; + +/** + * Server provide metadata about other bundles (repository contents diff). + *

+ * When the client asks CRCE to provide bundle metadata of those bundles which + * it does not know about and sends a list of bundle identifiers (= those + * bundles it knows about) and optionally sends a filter criteria specifying + * which subset of metadata it is interested in + *

+ * Then CRCE sends that (subset of) metadata only for the following bundles + * currently available in repository in "stored" state: + *

    + *
  • are not in the list sent by client ("new bundles") + *
  • are in the list but have been removed from the repository + * ("deleted bundles" - just a list of bundle identifiers). + *
+ * + * @author Jan Reznicek + */ +@Path("/other-bundles-metadata") +public class OtherBundlesMetadataResource extends ResourceParent implements PostOtherBundlesMetadata { + + private static final Logger log = LoggerFactory.getLogger(OtherBundlesMetadataResource.class); + + + /** + * Create XML String from repository. + * + * @param repository repository contains metadata about resources + * @return XML String with exported metadata + * @throws WebApplicationException unmarshal of xml failed. + */ + public Repository unmarshalXML(String repository) throws WebApplicationException { + + try { + ClassLoader cl = ObjectFactory.class.getClassLoader(); + JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl); + + Unmarshaller unmarshaller = jc.createUnmarshaller(); + + InputStream repositoryStream = new ByteArrayInputStream(repository.getBytes(DEF_ENCODING)); + Object obj = unmarshaller.unmarshal(repositoryStream); + + JAXBElement jxbE = (JAXBElement) obj; + + Repository rep = (Repository) jxbE.getValue(); + + return rep; + + } catch (UnsupportedEncodingException e) { + log.warn("Request ({}) - Unsuported encoding {}", getRequestId(), DEF_ENCODING); + log.debug(e.getMessage(), e); + throw new WebApplicationException(500); + + } catch (JAXBException e) { + log.info("Request ({}) - Post request XML unmarshal failed.", getRequestId()); + log.debug(e.getMessage(), e); + throw new WebApplicationException(400); + } + + } + + /** + * Create a set of id of all resources from repository. + * + * @param resources repository. + * @return set of id + */ + private Set createIdSet(Repository resources) { + List resList = resources.getResources(); + Set idSet = new HashSet<>(); + + for (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource res : resList) { + idSet.add(res.getId()); + } + + return idSet; + } + + /** + * Create a set of id of all resources from list of resources. + * + * @param resources list of resources. + * @return set of id + */ + private Set createIdSet(List resources) { + + Set idSet = new HashSet<>(); + + for (Resource res : resources) { + idSet.add(res.getId()); + } + + return idSet; + } + + /** + * Returns list of bundles, that are in storeResources, but not in clientBundlesIdSet. + * These bundles are new on store since last update of client bundles. + * + * @param storeResources list of bundles in the store + * @param clientBundlesIdSet set of id of bundles in the client + * @return list of bundles, that are new on store. + */ + private List findNewResources(List storeResources, Set clientBundlesIdSet) { + + List newResources = new ArrayList<>(); + + for (Resource res : storeResources) { + if (!clientBundlesIdSet.contains(res.getId())) { + newResources.add(res); + } + } + + return newResources; + } + + + /** + * Returns list of bundles, that are in clientResources, but not in storeIdset. + * These bundles was deleted from store since last update of client bundles. + * + * @param clientResources list of bundles in the client + * @param storeIdSet set of id of bundles in the store + * @return list of bundles, that have was deleted from store. + */ + private List determineUnknownResources( + List clientResources, Set storeIdSet) { + + List unknownResources = new ArrayList<>(); + for (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource res : clientResources) { + if (!storeIdSet.contains(res.getId())) { + unknownResources.add(Activator.instance().getConvertorToBeans().getResourceWithUnknownStatus(res.getId())); + } + } + + return unknownResources; + } + + + /** + * Return repository with other bundles (new to client). + * Other bundles are bundles currently available in repository in "stored" state: + *
    + *
  • are not in the list sent by client ("new bundles") + *
  • are in the list but have been removed from the repository ("deleted bundles" - just a list of bundle identifiers). + *
+ * + * @param clientBundles + * @param ui contextual info about URI + * @return repositoty with other bundles + */ + private Repository findOtherBundles(Repository clientBundles, UriInfo ui) { + + List storeResources = Activator.instance().getStore().getResources(); + + Set clientBundlesIdSet = createIdSet(clientBundles); + Set storeIdSet = createIdSet(storeResources); + + List newResources = findNewResources(storeResources, clientBundlesIdSet); + List unknownResources = determineUnknownResources(clientBundles.getResources(), storeIdSet); + + //convert new resources to repository + MetadataFilter include = new MetadataFilter(); + include.includeAll(); + Repository repository = Activator.instance().getConvertorToBeans().mapRepository(newResources, include, ui); + + //add unknown resources + repository.getResources().addAll(unknownResources); + + return repository; + } + + + /** + * {@inheritDoc} + */ + @POST + @Consumes(MediaType.APPLICATION_XML) + @Produces({MediaType.APPLICATION_XML}) + @Override + public Response otherBundles(String knownBundles, @Context UriInfo ui) { + newRequest(); + log.debug("Request ({}) - Post other bundles request was received.", getRequestId()); + try { + Repository clientBundles = unmarshalXML(knownBundles); + Repository otherBundles = findOtherBundles(clientBundles, ui); + + Response response = Response.ok(createXML(otherBundles)).build(); + log.debug("Request ({}) - Response was successfully created.", getRequestId()); + return response; + + } catch (WebApplicationException e) { + + return e.getResponse(); + } + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ProviderOfCapabilityResource.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ProviderOfCapabilityResource.java index b3431e49..02aac96e 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ProviderOfCapabilityResource.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ProviderOfCapabilityResource.java @@ -1,332 +1,332 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.PostProviderOfCapability; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; -import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; -import cz.zcu.kiv.crce.rest.internal.structures.VersionDemand; - -@Path("/provider-of-capability") -public class ProviderOfCapabilityResource extends ResourceParent implements PostProviderOfCapability { - - private static final Logger log = LoggerFactory.getLogger(PostProviderOfCapability.class); - - /** - * Unmarshal requirement. - * - * @param requirement XML representation of requirement - * @return requirement - * @throws WebApplicationException unmarshal of xml failed. - */ - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement unmarshalRequirent(String requirement) throws WebApplicationException { - - try { - ClassLoader cl = ObjectFactory.class.getClassLoader(); - JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl); - - Unmarshaller unmarshaller = jc.createUnmarshaller(); - - InputStream requirementStream = new ByteArrayInputStream(requirement.getBytes(DEF_ENCODING)); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(requirementStream); - Node requirementSubtree = doc.getFirstChild(); - log.info("node: " + requirementSubtree.getLocalName()); - - - Object obj = unmarshaller.unmarshal(requirementSubtree, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement.class); - - - JAXBElement jxbE = (JAXBElement) obj; - - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement req = (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement) jxbE.getValue(); - - return req; - - } catch (UnsupportedEncodingException e) { - log.warn("Request ({}) - Unsuported encoding {}", getRequestId(), DEF_ENCODING); - log.debug(e.getMessage(), e); - throw new WebApplicationException(500); - - } catch (JAXBException e) { - log.info("Request ({}) - Post request XML unmarshal failed.", getRequestId()); - log.debug(e.getMessage(), e); - throw new WebApplicationException(400); - - } catch (ParserConfigurationException e) { - log.warn("Request ({}) - ParserConfigurationException during unmarshal", getRequestId()); - log.debug(e.getMessage(), e); - throw new WebApplicationException(500); - - } catch (IOException e) { - log.warn("Request ({}) - IOException during unmarshal", getRequestId()); - log.debug(e.getMessage(), e); - throw new WebApplicationException(500); - - } catch (SAXException e) { - log.info("Request ({}) - XMLParser exception during unmarshal - {}", getRequestId(), e.getMessage()); - log.debug(e.getMessage(), e); - throw new WebApplicationException(400); - } - - } - - /** - * Get name attribute of the requirement. - * - * @param requirement the requirement - * @return name attribute of the requirement - */ - private String getRequirementName(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - List attributes = requirement.getAttributes(); - - for (Attribute attribute : attributes) { - if (attribute.getName().equals("name")) { - return attribute.getValue(); - } - } - - return null; - } - - /** - * Return list of resources, that has capability, that matches the requirement. - * - * @param requirement the requirement - * @return list of resources, that has capability, that matches the requirement. - */ - private List matchingResources(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - String reqName = getRequirementName(requirement); - if (reqName == null) { - log.info("Request ({}) - No name found in the input requierment.", getRequestId()); - throw new WebApplicationException(400); - } - - List allResources = findAllBundles(); - //log.info("All resources size " + allResources.length); - - List matchingResources = new ArrayList<>(); - - for (Resource res : allResources) { - if (checkIfMatchRequirement(res, reqName, requirement)) { - log.debug("Request ({}) - Matching resource found - {}", getRequestId(), res.getId()); - matchingResources.add(res); - } - } - - return matchingResources; - } - - /** - * Prepare list of version demands from the requirement - * - * @param requirement the requirement - * @return list of version demands - */ - private List prepareVersionDemandsList(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - - List versionDemandsList = new ArrayList<>(); - - List attributes = requirement.getAttributes(); - for (Attribute attribute : attributes) { - if (attribute.getName().equals("version")) { - if (attribute.getValue() != null && attribute.getType() != null) { - VersionDemand verDemand = new VersionDemand(); - verDemand.setVersion(new Version(attribute.getValue())); - verDemand.setOperation(attribute.getType()); - versionDemandsList.add(verDemand); - } else { - log.warn("Request ({}) - Requirement version attribute has not set value or type and will be skipped", getRequestId()); - } - } - } - - return versionDemandsList; - } - - /** - * Check if the version demand match the capability version. - * - * @param verDemand the version demand - * @param capabilityVersion the capability version - * @return boolean, if the version demand match the capability version. - */ - private boolean checkVersionDemand(VersionDemand verDemand, Version capabilityVersion) { - String operation = verDemand.getOperation(); - - int compareVersions = capabilityVersion.compareTo(verDemand.getVersion()); - - switch (operation) { - case VersionDemand.EQUEAL: - if (compareVersions == 0) { - return true; - } - break; - case VersionDemand.GREATER_THAN: - if (compareVersions > 0) { - return true; - } - break; - case VersionDemand.LESS_THAN: - if (compareVersions < 0) { - return true; - } - break; - case VersionDemand.GREATER_EQUEAL: - if (compareVersions >= 0) { - return true; - } - break; - case VersionDemand.LESS_EQUEAL: - if (compareVersions <= 0) { - return true; - } - break; - case VersionDemand.NOT_EQUEAL: - if (compareVersions != 0) { - return true; - } - break; - default: - return false; - } - - return false; - } - - /** - * Check if the capability matches the version demands of the requirement. - * Requirement can have more version demands and all must match. - * - * @param capability the capability - * @param requirement the requirement - * @return boolean, if the capability matches the version demands of the requirement. - */ - private boolean checkVersionMatching(Capability capability, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - Version capabilityVersion = capability.getAttributeValue(NsOsgiPackage.ATTRIBUTE__VERSION); - List verDemands = prepareVersionDemandsList(requirement); - //log.info("version demands size " + verDemands.size()); - - for (VersionDemand verDemand : verDemands) { - - //if one of versionCriterium do not match, return false; - if (!checkVersionDemand(verDemand, capabilityVersion)) { - //log.info("Ver demand do not match - " + verDemand.getVersion().toString() + " " + verDemand.getOperation() ); - return false; - } - } - - //log.info("All verison demands matching"); - return true; - } - - /** - * Check if one of the resource's capabilities matches requirements. - * - * @param resource the resource - * @param reqName the name of requirement - * @param requirement the requirement - * @return boolean, if one of the resource's capabilities matches requirements - */ - private boolean checkIfMatchRequirement(Resource resource, String reqName, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - - List capabilities = resource.getCapabilities(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); - for (Capability cap : capabilities) { - //check if name matches -// if (cap.getPropertyString("package").equals(reqName)) { - if (reqName != null && reqName.equals(cap.getAttributeValue(NsOsgiPackage.ATTRIBUTE__NAME)) - && checkVersionMatching(cap, requirement)) { - //check if version demands matches - //one of capabilities matches - return true; - } - - } - - return false; - - } - - /** - * Find all resources, that have a capability, that matches the requirement - * - * @param requirement the requirement - * @return repository of resources, that have a capability, that matches the requirement - */ - private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository findProviders(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { - - List matchingResources = matchingResources(requirement); - - //log.info("Matching resources size " + matchingResources.length); - - MetadataFilter include = new MetadataFilter(); - include.includeAll(); - - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository repo = - Activator.instance().getConvertorToBeans().mapRepository(matchingResources, include, null); - - return repo; - } - - /** - * {@inheritDoc} - */ - @Override - @POST - @Consumes(MediaType.APPLICATION_XML) - @Produces({MediaType.APPLICATION_XML}) - public Response providerOfCapability(String requirement) { - newRequest(); - log.debug("Request ({}) - Provider of capability request was received.", getRequestId()); - log.debug("Request ({}) - Requirement received: {}", getRequestId(), requirement); - try { - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement req = unmarshalRequirent(requirement); - log.debug("Request ({}) - Requirement was unmashaled.", getRequestId()); - - cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository repositoryBean = findProviders(req); - - Response response = Response.ok(createXML(repositoryBean)).build(); - log.debug("Request ({}) - Response was successfully created.", getRequestId()); - return response; - } catch (WebApplicationException e) { - - return e.getResponse(); - } - } - -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiPackage; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.PostProviderOfCapability; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; +import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; +import cz.zcu.kiv.crce.rest.internal.structures.VersionDemand; + +@Path("/provider-of-capability") +public class ProviderOfCapabilityResource extends ResourceParent implements PostProviderOfCapability { + + private static final Logger log = LoggerFactory.getLogger(PostProviderOfCapability.class); + + /** + * Unmarshal requirement. + * + * @param requirement XML representation of requirement + * @return requirement + * @throws WebApplicationException unmarshal of xml failed. + */ + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement unmarshalRequirent(String requirement) throws WebApplicationException { + + try { + ClassLoader cl = ObjectFactory.class.getClassLoader(); + JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl); + + Unmarshaller unmarshaller = jc.createUnmarshaller(); + + InputStream requirementStream = new ByteArrayInputStream(requirement.getBytes(DEF_ENCODING)); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(requirementStream); + Node requirementSubtree = doc.getFirstChild(); + log.info("node: " + requirementSubtree.getLocalName()); + + + Object obj = unmarshaller.unmarshal(requirementSubtree, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement.class); + + + JAXBElement jxbE = (JAXBElement) obj; + + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement req = (cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement) jxbE.getValue(); + + return req; + + } catch (UnsupportedEncodingException e) { + log.warn("Request ({}) - Unsuported encoding {}", getRequestId(), DEF_ENCODING); + log.debug(e.getMessage(), e); + throw new WebApplicationException(500); + + } catch (JAXBException e) { + log.info("Request ({}) - Post request XML unmarshal failed.", getRequestId()); + log.debug(e.getMessage(), e); + throw new WebApplicationException(400); + + } catch (ParserConfigurationException e) { + log.warn("Request ({}) - ParserConfigurationException during unmarshal", getRequestId()); + log.debug(e.getMessage(), e); + throw new WebApplicationException(500); + + } catch (IOException e) { + log.warn("Request ({}) - IOException during unmarshal", getRequestId()); + log.debug(e.getMessage(), e); + throw new WebApplicationException(500); + + } catch (SAXException e) { + log.info("Request ({}) - XMLParser exception during unmarshal - {}", getRequestId(), e.getMessage()); + log.debug(e.getMessage(), e); + throw new WebApplicationException(400); + } + + } + + /** + * Get name attribute of the requirement. + * + * @param requirement the requirement + * @return name attribute of the requirement + */ + private String getRequirementName(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + List attributes = requirement.getAttributes(); + + for (Attribute attribute : attributes) { + if (attribute.getName().equals("name")) { + return attribute.getValue(); + } + } + + return null; + } + + /** + * Return list of resources, that has capability, that matches the requirement. + * + * @param requirement the requirement + * @return list of resources, that has capability, that matches the requirement. + */ + private List matchingResources(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + String reqName = getRequirementName(requirement); + if (reqName == null) { + log.info("Request ({}) - No name found in the input requierment.", getRequestId()); + throw new WebApplicationException(400); + } + + List allResources = findAllBundles(); + //log.info("All resources size " + allResources.length); + + List matchingResources = new ArrayList<>(); + + for (Resource res : allResources) { + if (checkIfMatchRequirement(res, reqName, requirement)) { + log.debug("Request ({}) - Matching resource found - {}", getRequestId(), res.getId()); + matchingResources.add(res); + } + } + + return matchingResources; + } + + /** + * Prepare list of version demands from the requirement + * + * @param requirement the requirement + * @return list of version demands + */ + private List prepareVersionDemandsList(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + + List versionDemandsList = new ArrayList<>(); + + List attributes = requirement.getAttributes(); + for (Attribute attribute : attributes) { + if (attribute.getName().equals("version")) { + if (attribute.getValue() != null && attribute.getType() != null) { + VersionDemand verDemand = new VersionDemand(); + verDemand.setVersion(new Version(attribute.getValue())); + verDemand.setOperation(attribute.getType()); + versionDemandsList.add(verDemand); + } else { + log.warn("Request ({}) - Requirement version attribute has not set value or type and will be skipped", getRequestId()); + } + } + } + + return versionDemandsList; + } + + /** + * Check if the version demand match the capability version. + * + * @param verDemand the version demand + * @param capabilityVersion the capability version + * @return boolean, if the version demand match the capability version. + */ + private boolean checkVersionDemand(VersionDemand verDemand, Version capabilityVersion) { + String operation = verDemand.getOperation(); + + int compareVersions = capabilityVersion.compareTo(verDemand.getVersion()); + + switch (operation) { + case VersionDemand.EQUEAL: + if (compareVersions == 0) { + return true; + } + break; + case VersionDemand.GREATER_THAN: + if (compareVersions > 0) { + return true; + } + break; + case VersionDemand.LESS_THAN: + if (compareVersions < 0) { + return true; + } + break; + case VersionDemand.GREATER_EQUEAL: + if (compareVersions >= 0) { + return true; + } + break; + case VersionDemand.LESS_EQUEAL: + if (compareVersions <= 0) { + return true; + } + break; + case VersionDemand.NOT_EQUEAL: + if (compareVersions != 0) { + return true; + } + break; + default: + return false; + } + + return false; + } + + /** + * Check if the capability matches the version demands of the requirement. + * Requirement can have more version demands and all must match. + * + * @param capability the capability + * @param requirement the requirement + * @return boolean, if the capability matches the version demands of the requirement. + */ + private boolean checkVersionMatching(Capability capability, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + Version capabilityVersion = capability.getAttributeValue(NsOsgiPackage.ATTRIBUTE__VERSION); + List verDemands = prepareVersionDemandsList(requirement); + //log.info("version demands size " + verDemands.size()); + + for (VersionDemand verDemand : verDemands) { + + //if one of versionCriterium do not match, return false; + if (!checkVersionDemand(verDemand, capabilityVersion)) { + //log.info("Ver demand do not match - " + verDemand.getVersion().toString() + " " + verDemand.getOperation() ); + return false; + } + } + + //log.info("All verison demands matching"); + return true; + } + + /** + * Check if one of the resource's capabilities matches requirements. + * + * @param resource the resource + * @param reqName the name of requirement + * @param requirement the requirement + * @return boolean, if one of the resource's capabilities matches requirements + */ + private boolean checkIfMatchRequirement(Resource resource, String reqName, cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + + List capabilities = resource.getCapabilities(NsOsgiPackage.NAMESPACE__OSGI_PACKAGE); + for (Capability cap : capabilities) { + //check if name matches +// if (cap.getPropertyString("package").equals(reqName)) { + if (reqName != null && reqName.equals(cap.getAttributeValue(NsOsgiPackage.ATTRIBUTE__NAME)) + && checkVersionMatching(cap, requirement)) { + //check if version demands matches + //one of capabilities matches + return true; + } + + } + + return false; + + } + + /** + * Find all resources, that have a capability, that matches the requirement + * + * @param requirement the requirement + * @return repository of resources, that have a capability, that matches the requirement + */ + private cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository findProviders(cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement requirement) { + + List matchingResources = matchingResources(requirement); + + //log.info("Matching resources size " + matchingResources.length); + + MetadataFilter include = new MetadataFilter(); + include.includeAll(); + + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository repo = + Activator.instance().getConvertorToBeans().mapRepository(matchingResources, include, null); + + return repo; + } + + /** + * {@inheritDoc} + */ + @Override + @POST + @Consumes(MediaType.APPLICATION_XML) + @Produces({MediaType.APPLICATION_XML}) + public Response providerOfCapability(String requirement) { + newRequest(); + log.debug("Request ({}) - Provider of capability request was received.", getRequestId()); + log.debug("Request ({}) - Requirement received: {}", getRequestId(), requirement); + try { + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Requirement req = unmarshalRequirent(requirement); + log.debug("Request ({}) - Requirement was unmashaled.", getRequestId()); + + cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository repositoryBean = findProviders(req); + + Response response = Response.ok(createXML(repositoryBean)).build(); + log.debug("Request ({}) - Response was successfully created.", getRequestId()); + return response; + } catch (WebApplicationException e) { + + return e.getResponse(); + } + } + +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ReplaceBundleResource.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ReplaceBundleResource.java index 4a415720..0e5e66a2 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ReplaceBundleResource.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ReplaceBundleResource.java @@ -1,165 +1,165 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nullable; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.GetReplaceBundle; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; -import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; - -@Path("/replace-bundle") -public class ReplaceBundleResource extends ResourceParent implements GetReplaceBundle { - - private static final Logger log = LoggerFactory.getLogger(ReplaceBundleResource.class); - - public static final String UPGRADE_OP = "upgrade"; - public static final String DOWNGRADE_OP = "downgrade"; - public static final String LOWEST_OP = "lowest"; - public static final String HIGHEST_OP = "highest"; - public static final String ANY_OP = "any"; - - /** - * Find resource in repository by its id. - * - * @param id id of resource - * @return the resource - * @throws WebApplicationException the resource was not found. - */ - private Resource findResource(String id) throws WebApplicationException { - Requirement req = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - req.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); //osgi name is crce id (symbolicname-version) - - return findSingleBundleByFilter(req); - - } - - /** - * Return resource, that could replace client bundle. - * Kind of returned resource depends on operation op. - *

- * Operations: - *

    - *
  • upgrade (Default)- nearest higher version
  • - *
  • downgrade - nearest lower
  • - *
  • highest - highest version
  • - *
  • lowest - lowest version
  • - *
  • any - different than version from client
  • - *
- * If no wanted version if available (ex no higher in upgrade op), resource from client is returned to client. - * - * @param op operation - * @param clientResource resource to replace - * @return resource, that could replace client bundle. - * @throws WebApplicationException unsupported operation - */ - @Nullable - private Resource findResourceToReturn(String op, Resource clientResource) throws WebApplicationException { - Resource resourceToReturn; - CompatibilitySearchService service = Activator.instance().getCompatibilityService(); - if(service == null) { - return null; - } - - if (op != null) { - switch (op) { - case LOWEST_OP: - resourceToReturn = service.findLowestDowngrade(clientResource); - break; - case HIGHEST_OP: - resourceToReturn = service.findHighestUpgrade(clientResource); - break; - case DOWNGRADE_OP: - resourceToReturn = service.findNearestDowngrade(clientResource); - break; - case UPGRADE_OP: - resourceToReturn = service.findNearestUpgrade(clientResource); - break; - case ANY_OP: - //use highest (if there is no higher, use nearest lower) - resourceToReturn = service.findHighestUpgrade(clientResource); - if (resourceToReturn == null) { - resourceToReturn = service.findNearestDowngrade(clientResource); - } - break; - default: - log.warn("Request ({}) - Unsupported operation (op) : {}.", getRequestId(), op); - throw new WebApplicationException(300); - } - - - } else { - resourceToReturn = service.findNearestUpgrade(clientResource); - } - - return resourceToReturn; - } - - - /** - * In current version return resource with same name as in id and highest possible version. - * - * @param id - * @param op - * @return resource - */ - @GET - @Produces({MediaType.APPLICATION_XML}) - @Override - public Response replaceBundle(@QueryParam("id") String id, @QueryParam("op") String op, @Context UriInfo ui) { - newRequest(); - log.debug("Request ({}) - Get replace bundle request was received.", getRequestId()); - - try { - log.debug("Request ({}) - Replace bundle with id: {}", getRequestId(), id); - - Resource clientResource = findResource(id); - - Resource resourceToReturn = findResourceToReturn(op, clientResource); - - Response response; - if (resourceToReturn != null) { - - List resourcesToReturn = Collections.singletonList(resourceToReturn); - - MetadataFilter include = new MetadataFilter(); - include.includeAll(); - - Repository repositoryBean = Activator.instance().getConvertorToBeans().mapRepository(resourcesToReturn, include, ui); - - response = Response.ok(createXML(repositoryBean)).build(); - log.debug("Request ({}) - Response was successfully created.", getRequestId()); - - } else { - - response = Response.status(Response.Status.NOT_FOUND).build(); - log.debug("Request ({}) - no replacement found. ", getRequestId()); - - } - - return response; - - - } catch (WebApplicationException e) { - return e.getResponse(); - } - } -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.util.Collections; +import java.util.List; + +import javax.annotation.Nullable; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.GetReplaceBundle; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; +import cz.zcu.kiv.crce.rest.internal.mapping.MetadataFilter; + +@Path("/replace-bundle") +public class ReplaceBundleResource extends ResourceParent implements GetReplaceBundle { + + private static final Logger log = LoggerFactory.getLogger(ReplaceBundleResource.class); + + public static final String UPGRADE_OP = "upgrade"; + public static final String DOWNGRADE_OP = "downgrade"; + public static final String LOWEST_OP = "lowest"; + public static final String HIGHEST_OP = "highest"; + public static final String ANY_OP = "any"; + + /** + * Find resource in repository by its id. + * + * @param id id of resource + * @return the resource + * @throws WebApplicationException the resource was not found. + */ + private Resource findResource(String id) throws WebApplicationException { + Requirement req = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + req.addAttribute(NsOsgiIdentity.ATTRIBUTE__NAME, id); //osgi name is crce id (symbolicname-version) + + return findSingleBundleByFilter(req); + + } + + /** + * Return resource, that could replace client bundle. + * Kind of returned resource depends on operation op. + *

+ * Operations: + *

    + *
  • upgrade (Default)- nearest higher version
  • + *
  • downgrade - nearest lower
  • + *
  • highest - highest version
  • + *
  • lowest - lowest version
  • + *
  • any - different than version from client
  • + *
+ * If no wanted version if available (ex no higher in upgrade op), resource from client is returned to client. + * + * @param op operation + * @param clientResource resource to replace + * @return resource, that could replace client bundle. + * @throws WebApplicationException unsupported operation + */ + @Nullable + private Resource findResourceToReturn(String op, Resource clientResource) throws WebApplicationException { + Resource resourceToReturn; + CompatibilitySearchService service = Activator.instance().getCompatibilityService(); + if(service == null) { + return null; + } + + if (op != null) { + switch (op) { + case LOWEST_OP: + resourceToReturn = service.findLowestDowngrade(clientResource); + break; + case HIGHEST_OP: + resourceToReturn = service.findHighestUpgrade(clientResource); + break; + case DOWNGRADE_OP: + resourceToReturn = service.findNearestDowngrade(clientResource); + break; + case UPGRADE_OP: + resourceToReturn = service.findNearestUpgrade(clientResource); + break; + case ANY_OP: + //use highest (if there is no higher, use nearest lower) + resourceToReturn = service.findHighestUpgrade(clientResource); + if (resourceToReturn == null) { + resourceToReturn = service.findNearestDowngrade(clientResource); + } + break; + default: + log.warn("Request ({}) - Unsupported operation (op) : {}.", getRequestId(), op); + throw new WebApplicationException(300); + } + + + } else { + resourceToReturn = service.findNearestUpgrade(clientResource); + } + + return resourceToReturn; + } + + + /** + * In current version return resource with same name as in id and highest possible version. + * + * @param id + * @param op + * @return resource + */ + @GET + @Produces({MediaType.APPLICATION_XML}) + @Override + public Response replaceBundle(@QueryParam("id") String id, @QueryParam("op") String op, @Context UriInfo ui) { + newRequest(); + log.debug("Request ({}) - Get replace bundle request was received.", getRequestId()); + + try { + log.debug("Request ({}) - Replace bundle with id: {}", getRequestId(), id); + + Resource clientResource = findResource(id); + + Resource resourceToReturn = findResourceToReturn(op, clientResource); + + Response response; + if (resourceToReturn != null) { + + List resourcesToReturn = Collections.singletonList(resourceToReturn); + + MetadataFilter include = new MetadataFilter(); + include.includeAll(); + + Repository repositoryBean = Activator.instance().getConvertorToBeans().mapRepository(resourcesToReturn, include, ui); + + response = Response.ok(createXML(repositoryBean)).build(); + log.debug("Request ({}) - Response was successfully created.", getRequestId()); + + } else { + + response = Response.status(Response.Status.NOT_FOUND).build(); + log.debug("Request ({}) - no replacement found. ", getRequestId()); + + } + + return response; + + + } catch (WebApplicationException e) { + return e.getResponse(); + } + } +} diff --git a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ResourceParent.java b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ResourceParent.java index aed35d5f..2de4e793 100644 --- a/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ResourceParent.java +++ b/modules/crce-rest/src/main/java/cz/zcu/kiv/crce/rest/internal/xml/ResourceParent.java @@ -1,295 +1,295 @@ -package cz.zcu.kiv.crce.rest.internal.xml; - -import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import javax.ws.rs.WebApplicationException; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.rest.internal.Activator; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; - -/** - * Parent class for all resource classes, that implements REST operation. - * This class contains common methods, that all offsprings can use. - * - * @author Jan Reznicek - */ -public abstract class ResourceParent { - - /** - * Id of actual HTTP request - */ - private int requestId = 0; - - protected static final String DEF_ENCODING = "UTF-8"; - - private static final Logger logger = LoggerFactory.getLogger(ResourceParent.class); - - /** - * Create XML String from repository. - * - * @param repository repository contains metadata about resources - * @return XML String with exported metadata - * @throws WebApplicationException XML export failed - */ - protected String createXML(Repository repository) throws WebApplicationException { - try { -// ObjectFactory objectFactory = new ObjectFactory(); -// JAXBElement repository = objectFactory.createRepository(repositoryBean); -// Class clazz = repository.getValue().getClass(); - Class clazz = repository.getClass(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ClassLoader cl = ObjectFactory.class.getClassLoader(); - JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(), cl); - - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(repository, baos); - - return baos.toString("UTF-8"); - - } catch (JAXBException | UnsupportedEncodingException e) { - logger.error("Request ({}) - Exception while creating response.", requestId); - logger.error(e.getMessage(), e); - throw new WebApplicationException(e, 500); - } - } - - /** - * Select from array of resources the one with highest version - * - * @param storeResources array of resources - * @return resource with highest version - */ - protected Resource resourceWithHighestVersion(List storeResources) { - if (storeResources.isEmpty()) { - return null; - } - Resource resourceWithHighestVersion = storeResources.get(0); - - for (Resource res : storeResources) { - Version highestVersion = getBundleVersion(resourceWithHighestVersion); - Version resVersion = getBundleVersion(res); - - if (resVersion != null && highestVersion != null - && highestVersion.compareTo(resVersion) < 0) { - resourceWithHighestVersion = res; - } - } - - logger.debug("Request ({}) - Bundle with highest version is: {}.", requestId, resourceWithHighestVersion.getId()); - - return resourceWithHighestVersion; - } - - - /** - * Select from array of resources the one with lowest version - * - * @param storeResources array of resources - * @return resource with highest version - */ - protected Resource resourceWithLowestVersion(List storeResources) { - if (storeResources.isEmpty()) { - return null; - } - Resource resourceWithLowestVersion = storeResources.get(0); - - for (Resource res : storeResources) { - Version lowestVersion = getBundleVersion(resourceWithLowestVersion); - Version resVersion = getBundleVersion(res); - if (lowestVersion != null && resVersion != null && lowestVersion.compareTo(resVersion) > 0) { - resourceWithLowestVersion = res; - } - } - - logger.debug("Request ({}) - Bundle with lowest version is: {}.", requestId, resourceWithLowestVersion.getId()); - - return resourceWithLowestVersion; - } - - - /** - * Find a single bundle in repository by LDAP filter. - * If are more bundle found, return first of them. - * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. - * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. - * - * @param requirement Resource requirement. - * @return founded bundle. - * @throws WebApplicationException - */ - @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) - protected Resource findSingleBundleByFilter(Requirement requirement) throws WebApplicationException { - try { - List storeResources = Activator.instance().getStore().getResources(requirement); - - if (storeResources.isEmpty()) { - logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); - throw new WebApplicationException(404); - } else { - return storeResources.get(0); - } - - } catch (WebApplicationException e) { - throw e; - } catch (Exception e) { - logger.error("Request ({}) - Could not get resources from store.", requestId, e); - throw new WebApplicationException(500); - } - } - - /** - * Find a single bundle in repository by LDAP filter. - * If are more bundle found, return the one with the highest version. - * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. - * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. - * - * @param requirement Resource requirement. - * @return Found bundle. - * @throws WebApplicationException - */ - @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) - protected Resource findSingleBundleByFilterWithHighestVersion(Requirement requirement) throws WebApplicationException { - try { - List storeResources = Activator.instance().getStore().getResources(requirement); - - if (storeResources.isEmpty()) { - logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); - throw new WebApplicationException(404); - } - - Resource resource; - - if (storeResources.size() > 1) { - logger.debug("Request ({}) - More bundles was found, the one with highest version will be selected.", requestId); - resource = resourceWithHighestVersion(storeResources); - } else { - logger.debug("Request ({}) - The requested bundle was found.", requestId); - resource = storeResources.get(0); - } - - return resource; - } catch (WebApplicationException e) { - throw e; - } catch (Exception e) { - logger.error("Request ({}) - Could not get resources from store.", requestId, e); - throw new WebApplicationException(500); - } - } - - /** - * Find a single bundle in repository by LDAP filter. - * If are more bundle found, return the one with the lowest version. - * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. - * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. - * - * @param requirement Resource requirement. - * @return founded bundle. - * @throws WebApplicationException - */ - @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) - protected Resource findSingleBundleByFilterWithLowestVersion(Requirement requirement) throws WebApplicationException { - try { - List storeResources = Activator.instance().getStore().getResources(requirement); - - if (storeResources.isEmpty()) { - logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); - throw new WebApplicationException(404); - } - - Resource resource; - - if (storeResources.size() > 1) { - logger.debug("Request ({}) - More bundles was found, the one with highest version will be selected.", requestId); - resource = resourceWithLowestVersion(storeResources); - } else { - logger.debug("Request ({}) - The requested bundle was found.", requestId); - resource = storeResources.get(0); - } - - return resource; - } catch (WebApplicationException e) { - throw e; - } catch (Exception e) { - logger.error("Request ({}) - Could not get resources from store.", requestId, e); - throw new WebApplicationException(500); - } - } - - - /** - * Find bundles by filter - * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. - * - * @param requirement Resource requirement. - * @return founded bundles. - * @throws WebApplicationException - */ - protected List findBundlesByFilter(Requirement requirement) throws WebApplicationException { - try { - List storeResources = Activator.instance().getStore().getResources(requirement); - - // TODO check list size? - - return storeResources; - } catch (Exception e) { - logger.error("Request ({}) - Could not get resources from store.", requestId, e); - throw new WebApplicationException(500); - } - } - - protected List findAllBundles() throws WebApplicationException { - return Activator.instance().getStore().getResources(); - } - - /** - * Indicate that new request came to server. - * Id of new request is determined. - */ - protected void newRequest() { - requestId++; - } - - /** - * Get id of actual request - * - * @return id of actual request. - */ - protected int getRequestId() { - return requestId; - } - - // TODO the following methods are candidates for a common OSGi service - - protected Version getBundleVersion(Resource resource) { - if (resource != null) { - return Activator.instance().getMetadataService() - .getSingletonCapability(resource, NsOsgiBundle.NAMESPACE__OSGI_BUNDLE) - .getAttributeValue(NsOsgiBundle.ATTRIBUTE__VERSION); - } - return null; - } - - protected String getBundleSymbolicName(Resource resource) { - if (resource != null) { - return Activator.instance().getMetadataService() - .getSingletonCapability(resource, NsOsgiBundle.NAMESPACE__OSGI_BUNDLE) - .getAttributeValue(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME); - } - return null; - } -} +package cz.zcu.kiv.crce.rest.internal.xml; + +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; +import java.util.List; + +import javax.ws.rs.WebApplicationException; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiBundle; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.rest.internal.Activator; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.ObjectFactory; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Repository; + +/** + * Parent class for all resource classes, that implements REST operation. + * This class contains common methods, that all offsprings can use. + * + * @author Jan Reznicek + */ +public abstract class ResourceParent { + + /** + * Id of actual HTTP request + */ + private int requestId = 0; + + protected static final String DEF_ENCODING = "UTF-8"; + + private static final Logger logger = LoggerFactory.getLogger(ResourceParent.class); + + /** + * Create XML String from repository. + * + * @param repository repository contains metadata about resources + * @return XML String with exported metadata + * @throws WebApplicationException XML export failed + */ + protected String createXML(Repository repository) throws WebApplicationException { + try { +// ObjectFactory objectFactory = new ObjectFactory(); +// JAXBElement repository = objectFactory.createRepository(repositoryBean); +// Class clazz = repository.getValue().getClass(); + Class clazz = repository.getClass(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ClassLoader cl = ObjectFactory.class.getClassLoader(); + JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(), cl); + + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(repository, baos); + + return baos.toString("UTF-8"); + + } catch (JAXBException | UnsupportedEncodingException e) { + logger.error("Request ({}) - Exception while creating response.", requestId); + logger.error(e.getMessage(), e); + throw new WebApplicationException(e, 500); + } + } + + /** + * Select from array of resources the one with highest version + * + * @param storeResources array of resources + * @return resource with highest version + */ + protected Resource resourceWithHighestVersion(List storeResources) { + if (storeResources.isEmpty()) { + return null; + } + Resource resourceWithHighestVersion = storeResources.get(0); + + for (Resource res : storeResources) { + Version highestVersion = getBundleVersion(resourceWithHighestVersion); + Version resVersion = getBundleVersion(res); + + if (resVersion != null && highestVersion != null + && highestVersion.compareTo(resVersion) < 0) { + resourceWithHighestVersion = res; + } + } + + logger.debug("Request ({}) - Bundle with highest version is: {}.", requestId, resourceWithHighestVersion.getId()); + + return resourceWithHighestVersion; + } + + + /** + * Select from array of resources the one with lowest version + * + * @param storeResources array of resources + * @return resource with highest version + */ + protected Resource resourceWithLowestVersion(List storeResources) { + if (storeResources.isEmpty()) { + return null; + } + Resource resourceWithLowestVersion = storeResources.get(0); + + for (Resource res : storeResources) { + Version lowestVersion = getBundleVersion(resourceWithLowestVersion); + Version resVersion = getBundleVersion(res); + if (lowestVersion != null && resVersion != null && lowestVersion.compareTo(resVersion) > 0) { + resourceWithLowestVersion = res; + } + } + + logger.debug("Request ({}) - Bundle with lowest version is: {}.", requestId, resourceWithLowestVersion.getId()); + + return resourceWithLowestVersion; + } + + + /** + * Find a single bundle in repository by LDAP filter. + * If are more bundle found, return first of them. + * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. + * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. + * + * @param requirement Resource requirement. + * @return founded bundle. + * @throws WebApplicationException + */ + @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) + protected Resource findSingleBundleByFilter(Requirement requirement) throws WebApplicationException { + try { + List storeResources = Activator.instance().getStore().getResources(requirement); + + if (storeResources.isEmpty()) { + logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); + throw new WebApplicationException(404); + } else { + return storeResources.get(0); + } + + } catch (WebApplicationException e) { + throw e; + } catch (Exception e) { + logger.error("Request ({}) - Could not get resources from store.", requestId, e); + throw new WebApplicationException(500); + } + } + + /** + * Find a single bundle in repository by LDAP filter. + * If are more bundle found, return the one with the highest version. + * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. + * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. + * + * @param requirement Resource requirement. + * @return Found bundle. + * @throws WebApplicationException + */ + @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) + protected Resource findSingleBundleByFilterWithHighestVersion(Requirement requirement) throws WebApplicationException { + try { + List storeResources = Activator.instance().getStore().getResources(requirement); + + if (storeResources.isEmpty()) { + logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); + throw new WebApplicationException(404); + } + + Resource resource; + + if (storeResources.size() > 1) { + logger.debug("Request ({}) - More bundles was found, the one with highest version will be selected.", requestId); + resource = resourceWithHighestVersion(storeResources); + } else { + logger.debug("Request ({}) - The requested bundle was found.", requestId); + resource = storeResources.get(0); + } + + return resource; + } catch (WebApplicationException e) { + throw e; + } catch (Exception e) { + logger.error("Request ({}) - Could not get resources from store.", requestId, e); + throw new WebApplicationException(500); + } + } + + /** + * Find a single bundle in repository by LDAP filter. + * If are more bundle found, return the one with the lowest version. + * If a no bundle was found, throw {@link WebApplicationException} with status 404 - Not found. + * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. + * + * @param requirement Resource requirement. + * @return founded bundle. + * @throws WebApplicationException + */ + @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch"}) + protected Resource findSingleBundleByFilterWithLowestVersion(Requirement requirement) throws WebApplicationException { + try { + List storeResources = Activator.instance().getStore().getResources(requirement); + + if (storeResources.isEmpty()) { + logger.debug("Request ({}) - Requested bundle was not found in the repository.", requestId); + throw new WebApplicationException(404); + } + + Resource resource; + + if (storeResources.size() > 1) { + logger.debug("Request ({}) - More bundles was found, the one with highest version will be selected.", requestId); + resource = resourceWithLowestVersion(storeResources); + } else { + logger.debug("Request ({}) - The requested bundle was found.", requestId); + resource = storeResources.get(0); + } + + return resource; + } catch (WebApplicationException e) { + throw e; + } catch (Exception e) { + logger.error("Request ({}) - Could not get resources from store.", requestId, e); + throw new WebApplicationException(500); + } + } + + + /** + * Find bundles by filter + * If the syntax of the LDAP filter is wrong, throw {@link WebApplicationException} with status 400 - Bad request. + * + * @param requirement Resource requirement. + * @return founded bundles. + * @throws WebApplicationException + */ + protected List findBundlesByFilter(Requirement requirement) throws WebApplicationException { + try { + List storeResources = Activator.instance().getStore().getResources(requirement); + + // TODO check list size? + + return storeResources; + } catch (Exception e) { + logger.error("Request ({}) - Could not get resources from store.", requestId, e); + throw new WebApplicationException(500); + } + } + + protected List findAllBundles() throws WebApplicationException { + return Activator.instance().getStore().getResources(); + } + + /** + * Indicate that new request came to server. + * Id of new request is determined. + */ + protected void newRequest() { + requestId++; + } + + /** + * Get id of actual request + * + * @return id of actual request. + */ + protected int getRequestId() { + return requestId; + } + + // TODO the following methods are candidates for a common OSGi service + + protected Version getBundleVersion(Resource resource) { + if (resource != null) { + return Activator.instance().getMetadataService() + .getSingletonCapability(resource, NsOsgiBundle.NAMESPACE__OSGI_BUNDLE) + .getAttributeValue(NsOsgiBundle.ATTRIBUTE__VERSION); + } + return null; + } + + protected String getBundleSymbolicName(Resource resource) { + if (resource != null) { + return Activator.instance().getMetadataService() + .getSingletonCapability(resource, NsOsgiBundle.NAMESPACE__OSGI_BUNDLE) + .getAttributeValue(NsOsgiBundle.ATTRIBUTE__SYMBOLIC_NAME); + } + return null; + } +} diff --git a/modules/crce-rest/src/main/resources/jaxb/compatibility.xjb b/modules/crce-rest/src/main/resources/jaxb/compatibility.xjb index 3b3c2fb3..d6727264 100644 --- a/modules/crce-rest/src/main/resources/jaxb/compatibility.xjb +++ b/modules/crce-rest/src/main/resources/jaxb/compatibility.xjb @@ -1,27 +1,27 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/modules/crce-rest/src/main/webapp/WEB-INF/web.xml b/modules/crce-rest/src/main/webapp/WEB-INF/web.xml index b33a6658..d03bb5f7 100644 --- a/modules/crce-rest/src/main/webapp/WEB-INF/web.xml +++ b/modules/crce-rest/src/main/webapp/WEB-INF/web.xml @@ -1,33 +1,33 @@ - - - - - - - - - - Jersey - org.glassfish.jersey.servlet.ServletContainer - - jersey.config.server.provider.packages - cz.zcu.kiv.crce.rest.internal.xml - - - javax.ws.rs.Application - cz.zcu.kiv.crce.rest.internal.RestApplication - - 1 - - - Jersey - /* - - - + + + + + + + + + + Jersey + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + cz.zcu.kiv.crce.rest.internal.xml + + + javax.ws.rs.Application + cz.zcu.kiv.crce.rest.internal.RestApplication + + 1 + + + Jersey + /* + + + diff --git a/modules/crce-rest/src/test/java/cz/zcu/kiv/crce/rest/internal/convertor/ConvertorToBeansTest.java b/modules/crce-rest/src/test/java/cz/zcu/kiv/crce/rest/internal/convertor/ConvertorToBeansTest.java index 8e348b3d..00a12189 100644 --- a/modules/crce-rest/src/test/java/cz/zcu/kiv/crce/rest/internal/convertor/ConvertorToBeansTest.java +++ b/modules/crce-rest/src/test/java/cz/zcu/kiv/crce/rest/internal/convertor/ConvertorToBeansTest.java @@ -1,65 +1,65 @@ -package cz.zcu.kiv.crce.rest.internal.convertor; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Test; - -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability; -import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource; -import cz.zcu.kiv.crce.rest.internal.mapping.JaxbMapping; - -/** - * Test {@link JaxbMapping}. - * - * @author Jan Reznicek - */ -public class ConvertorToBeansTest { - - private static final String TEST_ID_1 = "testid-1.0.0"; - private static final String EXPECTED_UNKNOWN_STATUS = "unknown"; - private static final String CRCE_ID_CAP = "crce.identity"; - private static final String CRCE_STATUS = "status"; - - public Capability getCapability(List caps, String namespace) { - for (Capability cap : caps) { - if (namespace.equals(cap.getNamespace())) { - return cap; - } - } - - return null; - } - - public Attribute getAttribute(List list, String attrName) { - for (Attribute atr : list) { - - if (attrName.equals(atr.getName())) { - return atr; - } - } - return null; - } - - /** - * Test {@link ConvertorToBeans#getResourceWithUnknownStatus(String)}. - */ - @Test - public void testGetResourceWithUnknownStatus() { - - JaxbMapping conv = new JaxbMapping(); - - Resource res = conv.getResourceWithUnknownStatus(TEST_ID_1); - assertTrue("Wrong id", TEST_ID_1.equals(res.getId())); - - Capability crceIdentityCap = getCapability(res.getCapabilities(), CRCE_ID_CAP); - assertNotNull("Capabily " + CRCE_ID_CAP + " is missing.", crceIdentityCap); - - Attribute crceStatusAtr = getAttribute(crceIdentityCap.getAttributes(), CRCE_STATUS); - assertTrue("Wrong status (" + crceStatusAtr.getValue() + "), expected status is: " + EXPECTED_UNKNOWN_STATUS, EXPECTED_UNKNOWN_STATUS.equals(crceStatusAtr.getValue())); - } - -} +package cz.zcu.kiv.crce.rest.internal.convertor; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Test; + +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Attribute; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Capability; +import cz.zcu.kiv.crce.rest.internal.jaxb.metadata.Resource; +import cz.zcu.kiv.crce.rest.internal.mapping.JaxbMapping; + +/** + * Test {@link JaxbMapping}. + * + * @author Jan Reznicek + */ +public class ConvertorToBeansTest { + + private static final String TEST_ID_1 = "testid-1.0.0"; + private static final String EXPECTED_UNKNOWN_STATUS = "unknown"; + private static final String CRCE_ID_CAP = "crce.identity"; + private static final String CRCE_STATUS = "status"; + + public Capability getCapability(List caps, String namespace) { + for (Capability cap : caps) { + if (namespace.equals(cap.getNamespace())) { + return cap; + } + } + + return null; + } + + public Attribute getAttribute(List list, String attrName) { + for (Attribute atr : list) { + + if (attrName.equals(atr.getName())) { + return atr; + } + } + return null; + } + + /** + * Test {@link ConvertorToBeans#getResourceWithUnknownStatus(String)}. + */ + @Test + public void testGetResourceWithUnknownStatus() { + + JaxbMapping conv = new JaxbMapping(); + + Resource res = conv.getResourceWithUnknownStatus(TEST_ID_1); + assertTrue("Wrong id", TEST_ID_1.equals(res.getId())); + + Capability crceIdentityCap = getCapability(res.getCapabilities(), CRCE_ID_CAP); + assertNotNull("Capabily " + CRCE_ID_CAP + " is missing.", crceIdentityCap); + + Attribute crceStatusAtr = getAttribute(crceIdentityCap.getAttributes(), CRCE_STATUS); + assertTrue("Wrong status (" + crceStatusAtr.getValue() + "), expected status is: " + EXPECTED_UNKNOWN_STATUS, EXPECTED_UNKNOWN_STATUS.equals(crceStatusAtr.getValue())); + } + +} diff --git a/modules/crce-target/pom.xml b/modules/crce-target/pom.xml index b882d43a..55696fcd 100644 --- a/modules/crce-target/pom.xml +++ b/modules/crce-target/pom.xml @@ -1,542 +1,542 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-target - pom - - CRCE - Target - - - 3.0.3 - - - - - - org.ops4j.pax.runner - pax-runner - 1.9.0 - - - org.apache.maven - maven-aether-provider - - - org.apache.maven - maven-settings-builder - - - org.apache.maven.wagon - wagon-provider-api - - - org.apache.maven.wagon - wagon-http - - - org.eclipse.aether - aether-connector-basic - - - org.eclipse.aether - aether-spi - - - org.eclipse.aether - aether-transport-wagon - - - org.sonatype.plexus - plexus-cipher - - - - - - - - org.ops4j.pax.web - pax-web-extender-war - ${pax.version} - provided - - - org.ops4j.pax.web - pax-web-extender-whiteboard - ${pax.version} - provided - - - org.ops4j.pax.web - pax-web-jetty-bundle - ${pax.version} - provided - - - org.ops4j.pax.web - pax-web-api - ${pax.version} - provided - - - org.ops4j.pax.web - pax-web-jsp - ${pax.version} - provided - - - - org.ops4j.pax.web - pax-web-spi - ${pax.version} - provided - - - - org.ops4j.pax.logging - pax-logging-api - 1.8.2 - - - - - - - org.osgi - org.osgi.compendium - provided - - - - - - org.slf4j - osgi-over-slf4j - - - org.slf4j - log4j-over-slf4j - - - org.slf4j - jcl-over-slf4j - - - org.slf4j - jul-to-slf4j - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-classic - - - - - - - org.apache.felix - org.apache.felix.scr - provided - - - animal-sniffer-annotations - org.codehaus.mojo - - - - - org.apache.felix - org.apache.felix.dependencymanager - provided - - - org.apache.felix - org.apache.felix.dependencymanager.runtime - provided - - - org.apache.felix - org.apache.felix.dependencymanager.shell - provided - - - org.apache.felix - org.apache.felix.gogo.runtime - - - - - org.apache.felix - org.apache.felix.eventadmin - provided - - - org.apache.felix - org.apache.felix.bundlerepository - provided - - - easymock - org.easymock - - - - - org.apache.felix - org.apache.felix.configadmin - provided - - - org.apache.felix - org.apache.felix.shell - provided - - - org.apache.felix - org.apache.felix.fileinstall - provided - - - - - - asm - asm-all - provided - - - org.ow2.asm - asm-all - provided - - 5.0.3 - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.jaxp-ri - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.bcel - provided - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.commons-vfs - provided - - - commons-logging - commons-logging - - - - - commons-fileupload - commons-fileupload - provided - - - commons-io - commons-io - provided - - - commons-beanutils - commons-beanutils - provided - - - commons-logging - commons-logging - - - - - org.apache.commons - commons-lang3 - provided - - - commons-logging - commons-logging - - - - - de.twentyeleven.skysail - org.json-osgi - provided - - - json - org.json - - - - - com.h2database - h2 - provided - - - org.apache.xbean - xbean-finder - 3.13 - provided - - - org.apache.xbean - xbean-asm-util - - - - - org.apache.xbean - xbean-bundleutils - 3.13 - provided - - - - org.mybatis - mybatis - provided - - - javax.ws.rs - javax.ws.rs-api - provided - - - org.glassfish.jersey.containers - jersey-container-servlet-core - provided - - - org.glassfish.jersey.media - jersey-media-multipart - provided - - - org.glassfish.jersey.media - jersey-media-json-jackson - provided - - - - javax.annotation - javax.annotation-api - 1.2 - provided - - - - org.mongodb - mongo-java-driver - provided - - - com.fasterxml.jackson.core - jackson-annotations - provided - - - com.fasterxml.jackson.core - jackson-core - provided - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - provided - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - provided - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - provided - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-xml-provider - provided - - - javax.xml.stream - stax-api - - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - provided - - - com.fasterxml.jackson.core - jackson-databind - provided - - - - - - ${project.groupId} - crce-core - pom - runtime - - - - ${project.groupId} - crce-compatibility-api - ${project.version} - runtime - - - ${project.groupId} - crce-compatibility-dao-api - ${project.version} - runtime - - - - - - ${project.groupId} - crce-metadata-osgi-bundle - ${project.version} - runtime - - - kxml2 - net.sf.kxml - - - org.apache.felix.utils - org.apache.felix - - - - - ${project.groupId} - crce-rest-v2 - ${project.version} - war - runtime - - - ${project.groupId} - crce-vo - ${project.version} - runtime - - - ${project.groupId} - crce-webui - ${project.version} - war - runtime - - - ${project.groupId} - crce-compatibility-dao-mongodb - ${project.version} - runtime - - - ${project.groupId} - crce-concurrency - ${project.version} - runtime - - - ${project.groupId} - crce-handler-metrics - ${project.version} - runtime - - - - org.apache.felix.dependencymanager.annotation - org.apache.felix - jar - provided - - - classworlds - classworlds - - - maven-project - org.apache.maven - - - maven-artifact - org.apache.maven - - - plexus-utils - org.codehaus.plexus - - - json - org.json - - - maven-plugin-api - org.apache.maven - - - - - - - - - maven-assembly-plugin - 2.4 - - - create-target - package - - attached - - - - src/main/assembly/assembly.xml - - ${project.outputDirectory} - - - - - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-target + pom + + CRCE - Target + + + 3.0.3 + + + + + + org.ops4j.pax.runner + pax-runner + 1.9.0 + + + org.apache.maven + maven-aether-provider + + + org.apache.maven + maven-settings-builder + + + org.apache.maven.wagon + wagon-provider-api + + + org.apache.maven.wagon + wagon-http + + + org.eclipse.aether + aether-connector-basic + + + org.eclipse.aether + aether-spi + + + org.eclipse.aether + aether-transport-wagon + + + org.sonatype.plexus + plexus-cipher + + + + + + + + org.ops4j.pax.web + pax-web-extender-war + ${pax.version} + provided + + + org.ops4j.pax.web + pax-web-extender-whiteboard + ${pax.version} + provided + + + org.ops4j.pax.web + pax-web-jetty-bundle + ${pax.version} + provided + + + org.ops4j.pax.web + pax-web-api + ${pax.version} + provided + + + org.ops4j.pax.web + pax-web-jsp + ${pax.version} + provided + + + + org.ops4j.pax.web + pax-web-spi + ${pax.version} + provided + + + + org.ops4j.pax.logging + pax-logging-api + 1.8.2 + + + + + + + org.osgi + org.osgi.compendium + provided + + + + + + org.slf4j + osgi-over-slf4j + + + org.slf4j + log4j-over-slf4j + + + org.slf4j + jcl-over-slf4j + + + org.slf4j + jul-to-slf4j + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + + + + + org.apache.felix + org.apache.felix.scr + provided + + + animal-sniffer-annotations + org.codehaus.mojo + + + + + org.apache.felix + org.apache.felix.dependencymanager + provided + + + org.apache.felix + org.apache.felix.dependencymanager.runtime + provided + + + org.apache.felix + org.apache.felix.dependencymanager.shell + provided + + + org.apache.felix + org.apache.felix.gogo.runtime + + + + + org.apache.felix + org.apache.felix.eventadmin + provided + + + org.apache.felix + org.apache.felix.bundlerepository + provided + + + easymock + org.easymock + + + + + org.apache.felix + org.apache.felix.configadmin + provided + + + org.apache.felix + org.apache.felix.shell + provided + + + org.apache.felix + org.apache.felix.fileinstall + provided + + + + + + asm + asm-all + provided + + + org.ow2.asm + asm-all + provided + + 5.0.3 + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.jaxp-ri + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.bcel + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-vfs + provided + + + commons-logging + commons-logging + + + + + commons-fileupload + commons-fileupload + provided + + + commons-io + commons-io + provided + + + commons-beanutils + commons-beanutils + provided + + + commons-logging + commons-logging + + + + + org.apache.commons + commons-lang3 + provided + + + commons-logging + commons-logging + + + + + de.twentyeleven.skysail + org.json-osgi + provided + + + json + org.json + + + + + com.h2database + h2 + provided + + + org.apache.xbean + xbean-finder + 3.13 + provided + + + org.apache.xbean + xbean-asm-util + + + + + org.apache.xbean + xbean-bundleutils + 3.13 + provided + + + + org.mybatis + mybatis + provided + + + javax.ws.rs + javax.ws.rs-api + provided + + + org.glassfish.jersey.containers + jersey-container-servlet-core + provided + + + org.glassfish.jersey.media + jersey-media-multipart + provided + + + org.glassfish.jersey.media + jersey-media-json-jackson + provided + + + + javax.annotation + javax.annotation-api + 1.2 + provided + + + + org.mongodb + mongo-java-driver + provided + + + com.fasterxml.jackson.core + jackson-annotations + provided + + + com.fasterxml.jackson.core + jackson-core + provided + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + provided + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + provided + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + provided + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-xml-provider + provided + + + javax.xml.stream + stax-api + + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + provided + + + com.fasterxml.jackson.core + jackson-databind + provided + + + + + + ${project.groupId} + crce-core + pom + runtime + + + + ${project.groupId} + crce-compatibility-api + ${project.version} + runtime + + + ${project.groupId} + crce-compatibility-dao-api + ${project.version} + runtime + + + + + + ${project.groupId} + crce-metadata-osgi-bundle + ${project.version} + runtime + + + kxml2 + net.sf.kxml + + + org.apache.felix.utils + org.apache.felix + + + + + ${project.groupId} + crce-rest-v2 + ${project.version} + war + runtime + + + ${project.groupId} + crce-vo + ${project.version} + runtime + + + ${project.groupId} + crce-webui + ${project.version} + war + runtime + + + ${project.groupId} + crce-compatibility-dao-mongodb + ${project.version} + runtime + + + ${project.groupId} + crce-concurrency + ${project.version} + runtime + + + ${project.groupId} + crce-handler-metrics + ${project.version} + runtime + + + + org.apache.felix.dependencymanager.annotation + org.apache.felix + jar + provided + + + classworlds + classworlds + + + maven-project + org.apache.maven + + + maven-artifact + org.apache.maven + + + plexus-utils + org.codehaus.plexus + + + json + org.json + + + maven-plugin-api + org.apache.maven + + + + + + + + + maven-assembly-plugin + 2.4 + + + create-target + package + + attached + + + + src/main/assembly/assembly.xml + + ${project.outputDirectory} + + + + + + + \ No newline at end of file diff --git a/modules/crce-target/src/main/assembly/assembly.xml b/modules/crce-target/src/main/assembly/assembly.xml index 590988bc..e4af78c3 100644 --- a/modules/crce-target/src/main/assembly/assembly.xml +++ b/modules/crce-target/src/main/assembly/assembly.xml @@ -1,113 +1,113 @@ - - - - distribution - - dir - zip - - crce - - - - .. - - README - - . - true - - - src/main/resources/conf/ - conf - - ** - - true - - - store - store - - ** - - true - - - ../conf.default - conf - - *.cfg - *.xml - - true - - - - - - src/main/resources/run.sh - 0777 - - - src/main/resources/run.bat - 0777 - - - src/main/resources/platform.properties - - - - - false - true - crce-bundles - runtime - - *:war:* - cz.zcu.kiv.crce:crce-core - org.apache.felix:org.apache.felix.utils - - - - false - true - crce-wars - runtime - - *:war:* - - - ${artifact.artifactId}.${artifact.extension} - - - - false - false - provided - required-bundles - - *:jar:* - - - org.ops4j.pax.runner:pax-runner - org.apache.felix:org.apache.felix.dependencymanager.annotation - com.google.code.findbugs:jsr305 - org.apache.tomcat.embed:* - - - - false - false - provided - - org.ops4j.pax.runner:pax-runner - - - ${artifact.artifactId}.${artifact.extension} - - - - + + + + distribution + + dir + zip + + crce + + + + .. + + README + + . + true + + + src/main/resources/conf/ + conf + + ** + + true + + + store + store + + ** + + true + + + ../conf.default + conf + + *.cfg + *.xml + + true + + + + + + src/main/resources/run.sh + 0777 + + + src/main/resources/run.bat + 0777 + + + src/main/resources/platform.properties + + + + + false + true + crce-bundles + runtime + + *:war:* + cz.zcu.kiv.crce:crce-core + org.apache.felix:org.apache.felix.utils + + + + false + true + crce-wars + runtime + + *:war:* + + + ${artifact.artifactId}.${artifact.extension} + + + + false + false + provided + required-bundles + + *:jar:* + + + org.ops4j.pax.runner:pax-runner + org.apache.felix:org.apache.felix.dependencymanager.annotation + com.google.code.findbugs:jsr305 + org.apache.tomcat.embed:* + + + + false + false + provided + + org.ops4j.pax.runner:pax-runner + + + ${artifact.artifactId}.${artifact.extension} + + + + diff --git a/modules/crce-target/src/main/resources/platform.properties b/modules/crce-target/src/main/resources/platform.properties index 181b038e..5feef007 100644 --- a/modules/crce-target/src/main/resources/platform.properties +++ b/modules/crce-target/src/main/resources/platform.properties @@ -1,12 +1,12 @@ --Dorg.osgi.framework.bootdelegation=sun.*,com.sun.* --Dorg.osgi.service.http.port=8080 --Dorg.osgi.service.http.port.secure=8443 --Dorg.osgi.service.http.secure.enabled=false --Dfelix.fileinstall.bundles.new.start=false --Dfelix.fileinstall.poll=2000 --Dfelix.fileinstall.dir=conf --Dfelix.fileinstall.filter=.*\\.cfg --Dlogback.configurationFile=conf/logback.xml --Dorg.ops4j.pax.logging.DefaultServiceLog.level=WARN - -#-Dorg.apache.felix.http.nio=true +-Dorg.osgi.framework.bootdelegation=sun.*,com.sun.* +-Dorg.osgi.service.http.port=8080 +-Dorg.osgi.service.http.port.secure=8443 +-Dorg.osgi.service.http.secure.enabled=false +-Dfelix.fileinstall.bundles.new.start=false +-Dfelix.fileinstall.poll=2000 +-Dfelix.fileinstall.dir=conf +-Dfelix.fileinstall.filter=.*\\.cfg +-Dlogback.configurationFile=conf/logback.xml +-Dorg.ops4j.pax.logging.DefaultServiceLog.level=WARN + +#-Dorg.apache.felix.http.nio=true diff --git a/modules/crce-target/src/main/resources/run.bat b/modules/crce-target/src/main/resources/run.bat index 525f861d..236675a7 100644 --- a/modules/crce-target/src/main/resources/run.bat +++ b/modules/crce-target/src/main/resources/run.bat @@ -1,8 +1,8 @@ -@ECHO OFF -IF EXIST .\sandbox GOTO START - -MKDIR .\sandbox\conf -COPY .\conf .\sandbox\conf - -:START -CALL java -jar pax-runner.jar --ups --workingDirectory=.\sandbox scan-dir:required-bundles scan-dir:crce-bundles war:file:crce-wars/crce-webui.war scan-bundle:file:crce-wars/crce-rest-v2.war scan-file:file:platform.properties %1 %2 %3 +@ECHO OFF +IF EXIST .\sandbox GOTO START + +MKDIR .\sandbox\conf +COPY .\conf .\sandbox\conf + +:START +CALL java -jar pax-runner.jar --ups --workingDirectory=.\sandbox scan-dir:required-bundles scan-dir:crce-bundles war:file:crce-wars/crce-webui.war scan-bundle:file:crce-wars/crce-rest-v2.war scan-file:file:platform.properties %1 %2 %3 diff --git a/modules/crce-target/src/main/resources/run.sh b/modules/crce-target/src/main/resources/run.sh index 95887736..d0153687 100644 --- a/modules/crce-target/src/main/resources/run.sh +++ b/modules/crce-target/src/main/resources/run.sh @@ -1,6 +1,6 @@ -#!/bin/bash -if [ ! -d ./sandbox ]; then - mkdir ./sandbox - cp -r ./conf ./sandbox -fi -java -jar pax-runner.jar --ups --workingDirectory=./sandbox scan-dir:required-bundles scan-dir:crce-bundles war:file:crce-wars/crce-webui.war scan-bundle:file:crce-wars/crce-rest-v2.war scan-file:file:platform.properties +#!/bin/bash +if [ ! -d ./sandbox ]; then + mkdir ./sandbox + cp -r ./conf ./sandbox +fi +java -jar pax-runner.jar --ups --workingDirectory=./sandbox scan-dir:required-bundles scan-dir:crce-bundles war:file:crce-wars/crce-webui.war scan-bundle:file:crce-wars/crce-rest-v2.war scan-file:file:platform.properties diff --git a/modules/crce-vo/osgi.bnd b/modules/crce-vo/osgi.bnd index 1fc01c08..6a9ead69 100644 --- a/modules/crce-vo/osgi.bnd +++ b/modules/crce-vo/osgi.bnd @@ -1,15 +1,15 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Version>: \ - ${pom.version} - -Bundle-SymbolicName: \ - ${bundle.symbolicName} - -Bundle-Name: CRCE - VOs - -Bundle-Activator: ${bundle.namespace}.internal.Activator - - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Version>: \ + ${pom.version} + +Bundle-SymbolicName: \ + ${bundle.symbolicName} + +Bundle-Name: CRCE - VOs + +Bundle-Activator: ${bundle.namespace}.internal.Activator + + diff --git a/modules/crce-vo/pom.xml b/modules/crce-vo/pom.xml index 97eeb252..da92ef35 100644 --- a/modules/crce-vo/pom.xml +++ b/modules/crce-vo/pom.xml @@ -1,74 +1,74 @@ - - - - 4.0.0 - - - crce-modules-parent - cz.zcu.kiv.crce - 2.1.1-SNAPSHOT - ../pom - - - crce-vo - bundle - - CRCE - View Objects - - - ${namespace}.vo - ${namespace}.vo - - - - - - cz.zcu.kiv.crce - crce-metadata-api - 3.0.0 - - - cz.zcu.kiv.crce - crce-compatibility-api - ${project.version} - - - cz.zcu.kiv.crce - crce-metadata-service-api - 3.0.0 - - - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - - - net.sf.dozer - dozer-osgi - 5.5.1 - - - - commons-beanutils - commons-beanutils - - - org.apache.commons - commons-lang3 - - - - - org.mockito - mockito-core - - - - - + + + + 4.0.0 + + + crce-modules-parent + cz.zcu.kiv.crce + 2.1.1-SNAPSHOT + ../pom + + + crce-vo + bundle + + CRCE - View Objects + + + ${namespace}.vo + ${namespace}.vo + + + + + + cz.zcu.kiv.crce + crce-metadata-api + 3.0.0 + + + cz.zcu.kiv.crce + crce-compatibility-api + ${project.version} + + + cz.zcu.kiv.crce + crce-metadata-service-api + 3.0.0 + + + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + + + net.sf.dozer + dozer-osgi + 5.5.1 + + + + commons-beanutils + commons-beanutils + + + org.apache.commons + commons-lang3 + + + + + org.mockito + mockito-core + + + + + \ No newline at end of file diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/Activator.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/Activator.java index f3f3baf1..6279ce87 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/Activator.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/Activator.java @@ -1,50 +1,50 @@ -package cz.zcu.kiv.crce.vo.internal; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; - -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.vo.internal.service.MappingServiceDozer; -import cz.zcu.kiv.crce.vo.service.MappingService; - -@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") -public final class Activator extends DependencyActivatorBase { - - private static volatile Activator instance; - - /* - * Injected by Dependency Manager. - */ - private volatile MetadataService metadataService; - - public static Activator instance() { - return instance; - } - - public MetadataService getMetadataService() { - return metadataService; - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - - } - - @Override - @edu.umd.cs.findbugs.annotations - .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") - public void init(BundleContext context, DependencyManager manager) throws Exception { - instance = this; - - manager.add(createComponent() - .setInterface(MappingService.class.getName(), null) - .setImplementation(MappingServiceDozer.class) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true))); - - manager.add(createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - ); - } -} +package cz.zcu.kiv.crce.vo.internal; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.vo.internal.service.MappingServiceDozer; +import cz.zcu.kiv.crce.vo.service.MappingService; + +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Injected by dependency manager.") +public final class Activator extends DependencyActivatorBase { + + private static volatile Activator instance; + + /* + * Injected by Dependency Manager. + */ + private volatile MetadataService metadataService; + + public static Activator instance() { + return instance; + } + + public MetadataService getMetadataService() { + return metadataService; + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + + } + + @Override + @edu.umd.cs.findbugs.annotations + .SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Dependency manager workaround.") + public void init(BundleContext context, DependencyManager manager) throws Exception { + instance = this; + + manager.add(createComponent() + .setInterface(MappingService.class.getName(), null) + .setImplementation(MappingServiceDozer.class) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true))); + + manager.add(createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + ); + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/OSGiDozerClassLoader.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/OSGiDozerClassLoader.java index 78d74313..fe206e4e 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/OSGiDozerClassLoader.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/OSGiDozerClassLoader.java @@ -1,44 +1,44 @@ -package cz.zcu.kiv.crce.vo.internal.dozer; - -import java.net.URL; - -import org.dozer.util.DozerClassLoader; -import org.osgi.framework.BundleContext; - -/** - * Classloader for Dozer bean mapper which allows loading multiple - * mapping files from various OSGi bundles. - * - * Date: 18.5.15 - * - * @author http://modio.io/dozer-pojo-mapper-in-osgi/ - */ -public class OSGiDozerClassLoader implements DozerClassLoader { - private BundleContext context; - - @Override - public Class loadClass(String className) { - try { - return context.getBundle().loadClass(className); - } catch (ClassNotFoundException e) { - return null; - } - } - - @Override - public URL loadResource(String uri) { - URL url; - - url = context.getBundle().getResource(uri); - - if (url == null) { - url = DozerClassLoader.class.getClassLoader().getResource(uri); - } - - return url; - } - - public void setContext(BundleContext context) { - this.context = context; - } -} +package cz.zcu.kiv.crce.vo.internal.dozer; + +import java.net.URL; + +import org.dozer.util.DozerClassLoader; +import org.osgi.framework.BundleContext; + +/** + * Classloader for Dozer bean mapper which allows loading multiple + * mapping files from various OSGi bundles. + * + * Date: 18.5.15 + * + * @author http://modio.io/dozer-pojo-mapper-in-osgi/ + */ +public class OSGiDozerClassLoader implements DozerClassLoader { + private BundleContext context; + + @Override + public Class loadClass(String className) { + try { + return context.getBundle().loadClass(className); + } catch (ClassNotFoundException e) { + return null; + } + } + + @Override + public URL loadResource(String uri) { + URL url; + + url = context.getBundle().getResource(uri); + + if (url == null) { + url = DozerClassLoader.class.getClassLoader().getResource(uri); + } + + return url; + } + + public void setContext(BundleContext context) { + this.context = context; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertor.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertor.java index c3d0352e..a6e0402c 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertor.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertor.java @@ -1,69 +1,69 @@ -package cz.zcu.kiv.crce.vo.internal.dozer.convertor; - -import org.dozer.DozerConverter; -import org.dozer.Mapper; -import org.dozer.MapperAware; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO; - -/** - * Convertor of Resource instances into a value object (BasicResourceVO) with only elementary - * information about the resource. - * - * Date: 10.5.15 - * - * @author Jakub Danek - */ -public class BasicResourceConvertor extends DozerConverter implements MapperAware { - - private MetadataService metadataService; - private Mapper mapper; - - public BasicResourceConvertor() { - super(Resource.class, BasicResourceVO.class); - } - - public BasicResourceConvertor(MetadataService metadataService) { - this(); - this.metadataService = metadataService; - } - - @Override - public BasicResourceVO convertTo(Resource source, BasicResourceVO destination) { - if(metadataService == null) { - throw new UnsupportedOperationException("Converter doesn't work without metadataService!"); - } - Capability identity = metadataService.getIdentity(source); - - String id = source.getId(); - - IdentityCapabilityVO idVO = mapper.map(identity, IdentityCapabilityVO.class); - - if(destination == null) { - destination = new BasicResourceVO(id, idVO); - } else { - destination.setId(id); - destination.setIdentity(idVO); - } - - return destination; - } - - @Override - public Resource convertFrom(BasicResourceVO source, Resource destination) { - return null; - } - - @Override - public void setMapper(Mapper mapper) { - this.mapper = mapper; - } - - public void setMetadataService(MetadataService metadataService) { - this.metadataService = metadataService; - } -} +package cz.zcu.kiv.crce.vo.internal.dozer.convertor; + +import org.dozer.DozerConverter; +import org.dozer.Mapper; +import org.dozer.MapperAware; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO; + +/** + * Convertor of Resource instances into a value object (BasicResourceVO) with only elementary + * information about the resource. + * + * Date: 10.5.15 + * + * @author Jakub Danek + */ +public class BasicResourceConvertor extends DozerConverter implements MapperAware { + + private MetadataService metadataService; + private Mapper mapper; + + public BasicResourceConvertor() { + super(Resource.class, BasicResourceVO.class); + } + + public BasicResourceConvertor(MetadataService metadataService) { + this(); + this.metadataService = metadataService; + } + + @Override + public BasicResourceVO convertTo(Resource source, BasicResourceVO destination) { + if(metadataService == null) { + throw new UnsupportedOperationException("Converter doesn't work without metadataService!"); + } + Capability identity = metadataService.getIdentity(source); + + String id = source.getId(); + + IdentityCapabilityVO idVO = mapper.map(identity, IdentityCapabilityVO.class); + + if(destination == null) { + destination = new BasicResourceVO(id, idVO); + } else { + destination.setId(id); + destination.setIdentity(idVO); + } + + return destination; + } + + @Override + public Resource convertFrom(BasicResourceVO source, Resource destination) { + return null; + } + + @Override + public void setMapper(Mapper mapper) { + this.mapper = mapper; + } + + public void setMetadataService(MetadataService metadataService) { + this.metadataService = metadataService; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverter.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverter.java index 45631109..d800d9c3 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverter.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverter.java @@ -1,98 +1,98 @@ -package cz.zcu.kiv.crce.vo.internal.dozer.convertor; - -import org.dozer.DozerConverter; -import org.dozer.Mapper; -import org.dozer.MapperAware; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO; -import cz.zcu.kiv.crce.vo.model.metadata.GenericRequirementVO; -import cz.zcu.kiv.crce.vo.model.metadata.PropertyVO; - -/** - * Convertor of Resource instances into DetailedResourceVO, which basically copies the - * generic metadata API model. - * - * Date: 1.6.15 - * - * @author Jakub Danek - */ -public class DetailedResourceConverter extends DozerConverter implements MapperAware { - - private Mapper mapper; - private MetadataService metadataService; - private BasicResourceConvertor basicConvertor; - - private DetailedResourceConverter() { - super(Resource.class, DetailedResourceVO.class); - } - - public DetailedResourceConverter(MetadataService metadataService) { - this(); - - if(metadataService == null) { - throw new UnsupportedOperationException("Converter doesn't work without metadataService!"); - } - this.metadataService = metadataService; - this.basicConvertor = new BasicResourceConvertor(this.metadataService); - - } - - @Override - public DetailedResourceVO convertTo(Resource resource, DetailedResourceVO destination) { - if (destination == null) { - destination = new DetailedResourceVO(); - } - - //convert identity - destination = (DetailedResourceVO) basicConvertor.convertTo(resource, destination); - - mapCapabilities(resource, destination); - mapRequirements(resource, destination); - mapProperties(resource, destination); - - return destination; - } - - private void mapCapabilities(Resource src, DetailedResourceVO dest) { - boolean filtered = false; - for (Capability capability : src.getRootCapabilities()) { - if(filtered || capability.getNamespace().equals(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY)) { - //identity capability already converted - filtered = true; - continue; - } - - dest.getCapabilities().add(mapper.map(capability, GenericCapabilityVO.class)); - } - } - - private void mapRequirements(Resource src, DetailedResourceVO dest) { - for (Requirement req : src.getRequirements()) { - dest.getRequirements().add(mapper.map(req, GenericRequirementVO.class)); - } - } - - private void mapProperties(Resource src, DetailedResourceVO dest) { - for (Property property : src.getProperties()) { - dest.getProperties().add(mapper.map(property, PropertyVO.class)); - } - } - - @Override - public Resource convertFrom(DetailedResourceVO detailedResourceVO, Resource resource) { - return null; - } - - @Override - public void setMapper(Mapper mapper) { - this.mapper = mapper; - this.basicConvertor.setMapper(mapper); - } -} +package cz.zcu.kiv.crce.vo.internal.dozer.convertor; + +import org.dozer.DozerConverter; +import org.dozer.Mapper; +import org.dozer.MapperAware; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO; +import cz.zcu.kiv.crce.vo.model.metadata.GenericRequirementVO; +import cz.zcu.kiv.crce.vo.model.metadata.PropertyVO; + +/** + * Convertor of Resource instances into DetailedResourceVO, which basically copies the + * generic metadata API model. + * + * Date: 1.6.15 + * + * @author Jakub Danek + */ +public class DetailedResourceConverter extends DozerConverter implements MapperAware { + + private Mapper mapper; + private MetadataService metadataService; + private BasicResourceConvertor basicConvertor; + + private DetailedResourceConverter() { + super(Resource.class, DetailedResourceVO.class); + } + + public DetailedResourceConverter(MetadataService metadataService) { + this(); + + if(metadataService == null) { + throw new UnsupportedOperationException("Converter doesn't work without metadataService!"); + } + this.metadataService = metadataService; + this.basicConvertor = new BasicResourceConvertor(this.metadataService); + + } + + @Override + public DetailedResourceVO convertTo(Resource resource, DetailedResourceVO destination) { + if (destination == null) { + destination = new DetailedResourceVO(); + } + + //convert identity + destination = (DetailedResourceVO) basicConvertor.convertTo(resource, destination); + + mapCapabilities(resource, destination); + mapRequirements(resource, destination); + mapProperties(resource, destination); + + return destination; + } + + private void mapCapabilities(Resource src, DetailedResourceVO dest) { + boolean filtered = false; + for (Capability capability : src.getRootCapabilities()) { + if(filtered || capability.getNamespace().equals(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY)) { + //identity capability already converted + filtered = true; + continue; + } + + dest.getCapabilities().add(mapper.map(capability, GenericCapabilityVO.class)); + } + } + + private void mapRequirements(Resource src, DetailedResourceVO dest) { + for (Requirement req : src.getRequirements()) { + dest.getRequirements().add(mapper.map(req, GenericRequirementVO.class)); + } + } + + private void mapProperties(Resource src, DetailedResourceVO dest) { + for (Property property : src.getProperties()) { + dest.getProperties().add(mapper.map(property, PropertyVO.class)); + } + } + + @Override + public Resource convertFrom(DetailedResourceVO detailedResourceVO, Resource resource) { + return null; + } + + @Override + public void setMapper(Mapper mapper) { + this.mapper = mapper; + this.basicConvertor.setMapper(mapper); + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/IdentityCapabilityConvertor.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/IdentityCapabilityConvertor.java index aefd3e79..e67cebfc 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/IdentityCapabilityConvertor.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/IdentityCapabilityConvertor.java @@ -1,63 +1,63 @@ -package cz.zcu.kiv.crce.vo.internal.dozer.convertor; - -import java.util.List; - -import org.dozer.DozerConverter; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO; - -/** - * Convertor of a CRCE identity Capability into special VO which is easier - * to use within clients (UI, web services) than the generic Capability API. - * - * Date: 25.5.15 - * - * @author Jakub Danek - */ -public class IdentityCapabilityConvertor extends DozerConverter { - - public IdentityCapabilityConvertor() { - super(Capability.class, IdentityCapabilityVO.class); - } - - @Override - public IdentityCapabilityVO convertTo(Capability identity, IdentityCapabilityVO destination) { - String id = identity.getId(); - - String externalId = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID); - if(externalId == null) { - externalId = "-"; - } - - String name = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); - if(name == null) { - name = "-"; - } - - Version v = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION); - String version = v != null ? v.toString() : "-"; - - IdentityCapabilityVO idVO = new IdentityCapabilityVO(id, externalId, name, version); - Long size = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE); - if(size != null) { - idVO.setSize(size); - } - - List cats = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); - if(cats != null) { - for (String c : cats) { - idVO.addCategory(c); - } - } - - return idVO; - } - - @Override - public Capability convertFrom(IdentityCapabilityVO identityCapabilityVO, Capability capability) { - return null; - } -} +package cz.zcu.kiv.crce.vo.internal.dozer.convertor; + +import java.util.List; + +import org.dozer.DozerConverter; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO; + +/** + * Convertor of a CRCE identity Capability into special VO which is easier + * to use within clients (UI, web services) than the generic Capability API. + * + * Date: 25.5.15 + * + * @author Jakub Danek + */ +public class IdentityCapabilityConvertor extends DozerConverter { + + public IdentityCapabilityConvertor() { + super(Capability.class, IdentityCapabilityVO.class); + } + + @Override + public IdentityCapabilityVO convertTo(Capability identity, IdentityCapabilityVO destination) { + String id = identity.getId(); + + String externalId = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID); + if(externalId == null) { + externalId = "-"; + } + + String name = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME); + if(name == null) { + name = "-"; + } + + Version v = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION); + String version = v != null ? v.toString() : "-"; + + IdentityCapabilityVO idVO = new IdentityCapabilityVO(id, externalId, name, version); + Long size = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE); + if(size != null) { + idVO.setSize(size); + } + + List cats = identity.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES); + if(cats != null) { + for (String c : cats) { + idVO.addCategory(c); + } + } + + return idVO; + } + + @Override + public Capability convertFrom(IdentityCapabilityVO identityCapabilityVO, Capability capability) { + return null; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/service/MappingServiceDozer.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/service/MappingServiceDozer.java index 5fc07697..8b423519 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/service/MappingServiceDozer.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/internal/service/MappingServiceDozer.java @@ -1,143 +1,143 @@ -package cz.zcu.kiv.crce.vo.internal.service; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import org.dozer.CustomConverter; -import org.dozer.DozerBeanMapper; -import org.dozer.config.BeanContainer; -import org.osgi.framework.FrameworkUtil; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.vo.internal.dozer.OSGiDozerClassLoader; -import cz.zcu.kiv.crce.vo.internal.dozer.convertor.BasicResourceConvertor; -import cz.zcu.kiv.crce.vo.internal.dozer.convertor.DetailedResourceConverter; -import cz.zcu.kiv.crce.vo.internal.dozer.convertor.IdentityCapabilityConvertor; -import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; -import cz.zcu.kiv.crce.vo.service.MappingService; - -/** - * Dozer implementation of MappingService interface. - * - * Date: 15.5.15 - * - * @author Jakub Danek - */ -@ParametersAreNonnullByDefault -public class MappingServiceDozer implements MappingService { - - private DozerBeanMapper mapper; - private MetadataService metadataService; - - - @Override - public BasicResourceVO mapBasic(@Nullable Resource resource) { - if(resource == null) { - return null; - } - return mapper.map(resource, BasicResourceVO.class); - } - - @Nonnull - @Override - public List mapBasic(List resources) { - List vos = new ArrayList<>(resources.size()); - - BasicResourceVO v; - for (Resource resource : resources) { - v = mapBasic(resource); - if (v != null) { - vos.add(v); - } - } - - return vos; - } - - @Nullable - @Override - public DetailedResourceVO mapFull(@Nullable Resource resource) { - if(resource == null) { - return null; - } - return mapper.map(resource, DetailedResourceVO.class); - } - - @Nonnull - @Override - public List mapFull(List resources) { - List list = new ArrayList<>(); - - DetailedResourceVO v; - for (Resource resource : resources) { - v = mapFull(resource); - if(v != null) { - list.add(v); - } - } - - return list; - } - - @Nonnull - @Override - public List mapCompatibility(List diffs) { - List list = new LinkedList<>(); - - CompatibilityVO vo; - for (Compatibility diff : diffs) { - vo = mapCompatibility(diff); - if(vo != null) { - list.add(vo); - } - } - - return list; - } - - @Nullable - @Override - public CompatibilityVO mapCompatibility(@Nullable Compatibility diff) { - if(diff == null) { - return null; - } - return mapper.map(diff, CompatibilityVO.class); - } - - /** - * Called by OSGi - */ - public void init() { - //workaround for Dozer OSGi unsuitability - OSGiDozerClassLoader cl = new OSGiDozerClassLoader(); - cl.setContext(FrameworkUtil.getBundle(this.getClass()).getBundleContext()); - BeanContainer.getInstance().setClassLoader(cl); - - List mappings = new LinkedList<>(); - mappings.add("mappings.xml"); - mapper = new DozerBeanMapper(mappings); - - List converters = new LinkedList<>(); - converters.add(new BasicResourceConvertor(metadataService)); - converters.add(new DetailedResourceConverter(metadataService)); - converters.add(new IdentityCapabilityConvertor()); - mapper.setCustomConverters(converters); - - // Force loading of the dozer.xml now instead of loading it - // upon the first mapping call - mapper.getMappingMetadata(); - } - - public void setMetadataService(MetadataService metadataService) { - this.metadataService = metadataService; - } -} +package cz.zcu.kiv.crce.vo.internal.service; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import org.dozer.CustomConverter; +import org.dozer.DozerBeanMapper; +import org.dozer.config.BeanContainer; +import org.osgi.framework.FrameworkUtil; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.vo.internal.dozer.OSGiDozerClassLoader; +import cz.zcu.kiv.crce.vo.internal.dozer.convertor.BasicResourceConvertor; +import cz.zcu.kiv.crce.vo.internal.dozer.convertor.DetailedResourceConverter; +import cz.zcu.kiv.crce.vo.internal.dozer.convertor.IdentityCapabilityConvertor; +import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; +import cz.zcu.kiv.crce.vo.service.MappingService; + +/** + * Dozer implementation of MappingService interface. + * + * Date: 15.5.15 + * + * @author Jakub Danek + */ +@ParametersAreNonnullByDefault +public class MappingServiceDozer implements MappingService { + + private DozerBeanMapper mapper; + private MetadataService metadataService; + + + @Override + public BasicResourceVO mapBasic(@Nullable Resource resource) { + if(resource == null) { + return null; + } + return mapper.map(resource, BasicResourceVO.class); + } + + @Nonnull + @Override + public List mapBasic(List resources) { + List vos = new ArrayList<>(resources.size()); + + BasicResourceVO v; + for (Resource resource : resources) { + v = mapBasic(resource); + if (v != null) { + vos.add(v); + } + } + + return vos; + } + + @Nullable + @Override + public DetailedResourceVO mapFull(@Nullable Resource resource) { + if(resource == null) { + return null; + } + return mapper.map(resource, DetailedResourceVO.class); + } + + @Nonnull + @Override + public List mapFull(List resources) { + List list = new ArrayList<>(); + + DetailedResourceVO v; + for (Resource resource : resources) { + v = mapFull(resource); + if(v != null) { + list.add(v); + } + } + + return list; + } + + @Nonnull + @Override + public List mapCompatibility(List diffs) { + List list = new LinkedList<>(); + + CompatibilityVO vo; + for (Compatibility diff : diffs) { + vo = mapCompatibility(diff); + if(vo != null) { + list.add(vo); + } + } + + return list; + } + + @Nullable + @Override + public CompatibilityVO mapCompatibility(@Nullable Compatibility diff) { + if(diff == null) { + return null; + } + return mapper.map(diff, CompatibilityVO.class); + } + + /** + * Called by OSGi + */ + public void init() { + //workaround for Dozer OSGi unsuitability + OSGiDozerClassLoader cl = new OSGiDozerClassLoader(); + cl.setContext(FrameworkUtil.getBundle(this.getClass()).getBundleContext()); + BeanContainer.getInstance().setClassLoader(cl); + + List mappings = new LinkedList<>(); + mappings.add("mappings.xml"); + mapper = new DozerBeanMapper(mappings); + + List converters = new LinkedList<>(); + converters.add(new BasicResourceConvertor(metadataService)); + converters.add(new DetailedResourceConverter(metadataService)); + converters.add(new IdentityCapabilityConvertor()); + mapper.setCustomConverters(converters); + + // Force loading of the dozer.xml now instead of loading it + // upon the first mapping call + mapper.getMappingMetadata(); + } + + public void setMetadataService(MetadataService metadataService) { + this.metadataService = metadataService; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/ValueObject.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/ValueObject.java index dd35dca0..d330772e 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/ValueObject.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/ValueObject.java @@ -1,51 +1,51 @@ -package cz.zcu.kiv.crce.vo.model; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAttribute; - -/** - * - * Parent object for all CRCE value objects. - * - * Marked as Serializable and contains id and namespace properties. - * - * Date: 18.5.15 - * - * @author Jakub Danek - */ -public class ValueObject implements Serializable { - - private String id; - private String namespace; - - public ValueObject() { - } - - public ValueObject(String id) { - this.id = id; - } - - public ValueObject(String id, String namespace) { - this.id = id; - this.namespace = namespace; - } - - @XmlAttribute(name = "uuid") - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @XmlAttribute(name = "namespace") - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } -} +package cz.zcu.kiv.crce.vo.model; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlAttribute; + +/** + * + * Parent object for all CRCE value objects. + * + * Marked as Serializable and contains id and namespace properties. + * + * Date: 18.5.15 + * + * @author Jakub Danek + */ +public class ValueObject implements Serializable { + + private String id; + private String namespace; + + public ValueObject() { + } + + public ValueObject(String id) { + this.id = id; + } + + public ValueObject(String id, String namespace) { + this.id = id; + this.namespace = namespace; + } + + @XmlAttribute(name = "uuid") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @XmlAttribute(name = "namespace") + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/CompatibilityVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/CompatibilityVO.java index 3041e80d..44992b4d 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/CompatibilityVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/CompatibilityVO.java @@ -1,129 +1,129 @@ -package cz.zcu.kiv.crce.vo.model.compatibility; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.compatibility.Contract; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * Date: 4.9.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "compatibility") -public class CompatibilityVO extends ValueObject { - - /** - * Name of the resource (crce.identity namespace) which has been compared to the Base resource - */ - private String otherExternalId; - /** - * Version of the resource which was compared to the Base resource. - *

- * Implemented according to the OSGi versioning scheme: - * major.minor.micor-qualifier - */ - private String otherVersion; - /** - * Name of the resource (crce.identity namespace) which was the reference Resource - */ - private String baseExternalId; - /** - * Version of the resource which the resource has been compared to. - *

- * Implemented according to the OSGi versioning scheme: - * major.minor.micor-qualifier - */ - private String baseVersion; - /** - * Difference value for the two resources aggregated from the DiffDetails. - */ - private Difference diffValue; - /** - * contract the compatibility instance is related to - */ - private Contract contract; - /** - * Complete diff of the two resources. - */ - private List diffs; - - public CompatibilityVO() { - this.setNamespace(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); - } - - public CompatibilityVO(String id) { - super(id, NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); - } - - @XmlAttribute(name = "externalId") - public String getOtherExternalId() { - return otherExternalId; - } - - public void setOtherExternalId(String otherExternalId) { - this.otherExternalId = otherExternalId; - } - - @XmlAttribute(name = "version") - public String getOtherVersion() { - return otherVersion; - } - - public void setOtherVersion(String otherVersion) { - this.otherVersion = otherVersion; - } - - @XmlAttribute(name = "baseExternalId") - public String getBaseExternalId() { - return baseExternalId; - } - - public void setBaseExternalId(String baseExternalId) { - this.baseExternalId = baseExternalId; - } - - @XmlAttribute(name = "baseVersion") - public String getBaseVersion() { - return baseVersion; - } - - public void setBaseVersion(String baseVersion) { - this.baseVersion = baseVersion; - } - - @XmlAttribute(name = "diff") - public Difference getDiffValue() { - return diffValue; - } - - public void setDiffValue(Difference diffValue) { - this.diffValue = diffValue; - } - - @XmlAttribute(name= "contract") - public Contract getContract() { - return contract; - } - - public void setContract(Contract contract) { - this.contract = contract; - } - - @Nonnull - @XmlElementRef - public List getDiffs() { - return diffs; - } - - public void setDiffs(List diffs) { - this.diffs = diffs; - } -} +package cz.zcu.kiv.crce.vo.model.compatibility; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.compatibility.Contract; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * Date: 4.9.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "compatibility") +public class CompatibilityVO extends ValueObject { + + /** + * Name of the resource (crce.identity namespace) which has been compared to the Base resource + */ + private String otherExternalId; + /** + * Version of the resource which was compared to the Base resource. + *

+ * Implemented according to the OSGi versioning scheme: + * major.minor.micor-qualifier + */ + private String otherVersion; + /** + * Name of the resource (crce.identity namespace) which was the reference Resource + */ + private String baseExternalId; + /** + * Version of the resource which the resource has been compared to. + *

+ * Implemented according to the OSGi versioning scheme: + * major.minor.micor-qualifier + */ + private String baseVersion; + /** + * Difference value for the two resources aggregated from the DiffDetails. + */ + private Difference diffValue; + /** + * contract the compatibility instance is related to + */ + private Contract contract; + /** + * Complete diff of the two resources. + */ + private List diffs; + + public CompatibilityVO() { + this.setNamespace(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); + } + + public CompatibilityVO(String id) { + super(id, NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY); + } + + @XmlAttribute(name = "externalId") + public String getOtherExternalId() { + return otherExternalId; + } + + public void setOtherExternalId(String otherExternalId) { + this.otherExternalId = otherExternalId; + } + + @XmlAttribute(name = "version") + public String getOtherVersion() { + return otherVersion; + } + + public void setOtherVersion(String otherVersion) { + this.otherVersion = otherVersion; + } + + @XmlAttribute(name = "baseExternalId") + public String getBaseExternalId() { + return baseExternalId; + } + + public void setBaseExternalId(String baseExternalId) { + this.baseExternalId = baseExternalId; + } + + @XmlAttribute(name = "baseVersion") + public String getBaseVersion() { + return baseVersion; + } + + public void setBaseVersion(String baseVersion) { + this.baseVersion = baseVersion; + } + + @XmlAttribute(name = "diff") + public Difference getDiffValue() { + return diffValue; + } + + public void setDiffValue(Difference diffValue) { + this.diffValue = diffValue; + } + + @XmlAttribute(name= "contract") + public Contract getContract() { + return contract; + } + + public void setContract(Contract contract) { + this.contract = contract; + } + + @Nonnull + @XmlElementRef + public List getDiffs() { + return diffs; + } + + public void setDiffs(List diffs) { + this.diffs = diffs; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/DiffVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/DiffVO.java index d4ec7c7b..443d32e5 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/DiffVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/compatibility/DiffVO.java @@ -1,110 +1,110 @@ -package cz.zcu.kiv.crce.vo.model.compatibility; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.DifferenceRole; -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * Date: 4.9.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "diff") -public class DiffVO extends ValueObject { - /** - * DifferenceLevel represents particular part of bundle this - * diff is related to. E.g. whole package, class or just a method or a field. - * - */ - private DifferenceLevel level; - /** - * Name of the element this diff is related to. E.g. a class name. - */ - private String name; - /** - * Difference value represent the type of change made. - */ - private Difference value; - /** - * Role represents meaning of the item this diff is about. - *

- * Capability (e.g. exported packages) or requirement. - */ - private DifferenceRole role; - /** - * Language syntax this diff represents. E.g. java. - */ - private String syntax; - /** - * Children represent more detailed difference data. - *

- * E.g. for a package, children would list modified classes. - */ - private List children; - - - public DiffVO() { - super(null); - } - - @XmlAttribute(name = "level") - public DifferenceLevel getLevel() { - return level; - } - - public void setLevel(DifferenceLevel level) { - this.level = level; - } - - @XmlAttribute(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlAttribute(name = "diff") - public Difference getValue() { - return value; - } - - public void setValue(Difference value) { - this.value = value; - } - - @XmlAttribute(name = "role") - public DifferenceRole getRole() { - return role; - } - - public void setRole(DifferenceRole role) { - this.role = role; - } - - @XmlAttribute(name = "syntax") - public String getSyntax() { - return syntax; - } - - public void setSyntax(String syntax) { - this.syntax = syntax; - } - - @XmlElementRef - public List getChildren() { - return children; - } - - public void setChildren(List children) { - this.children = children; - } -} +package cz.zcu.kiv.crce.vo.model.compatibility; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.DifferenceRole; +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * Date: 4.9.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "diff") +public class DiffVO extends ValueObject { + /** + * DifferenceLevel represents particular part of bundle this + * diff is related to. E.g. whole package, class or just a method or a field. + * + */ + private DifferenceLevel level; + /** + * Name of the element this diff is related to. E.g. a class name. + */ + private String name; + /** + * Difference value represent the type of change made. + */ + private Difference value; + /** + * Role represents meaning of the item this diff is about. + *

+ * Capability (e.g. exported packages) or requirement. + */ + private DifferenceRole role; + /** + * Language syntax this diff represents. E.g. java. + */ + private String syntax; + /** + * Children represent more detailed difference data. + *

+ * E.g. for a package, children would list modified classes. + */ + private List children; + + + public DiffVO() { + super(null); + } + + @XmlAttribute(name = "level") + public DifferenceLevel getLevel() { + return level; + } + + public void setLevel(DifferenceLevel level) { + this.level = level; + } + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlAttribute(name = "diff") + public Difference getValue() { + return value; + } + + public void setValue(Difference value) { + this.value = value; + } + + @XmlAttribute(name = "role") + public DifferenceRole getRole() { + return role; + } + + public void setRole(DifferenceRole role) { + this.role = role; + } + + @XmlAttribute(name = "syntax") + public String getSyntax() { + return syntax; + } + + public void setSyntax(String syntax) { + this.syntax = syntax; + } + + @XmlElementRef + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/AttributeVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/AttributeVO.java index bad5f3dd..cc90caba 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/AttributeVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/AttributeVO.java @@ -1,75 +1,75 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * - * Value object for {@link cz.zcu.kiv.crce.metadata.Attribute} - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "attribute") -public class AttributeVO extends ValueObject { - - /** - * Attribute name. - */ - private String name; - /** - * Attribute value. - */ - private String value; - /** - * Attribute type. - */ - private String type; - - public AttributeVO() { - } - - public AttributeVO(String name, String value) { - this.name = name; - this.value = value; - this.type = value.getClass().getName(); - } - - public AttributeVO(String name, String value, Class type) { - this.name = name; - this.value = value; - this.type = type.getName(); - } - - @XmlAttribute(name = "name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlAttribute(name = "value") - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @XmlAttribute(name = "type") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * + * Value object for {@link cz.zcu.kiv.crce.metadata.Attribute} + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "attribute") +public class AttributeVO extends ValueObject { + + /** + * Attribute name. + */ + private String name; + /** + * Attribute value. + */ + private String value; + /** + * Attribute type. + */ + private String type; + + public AttributeVO() { + } + + public AttributeVO(String name, String value) { + this.name = name; + this.value = value; + this.type = value.getClass().getName(); + } + + public AttributeVO(String name, String value, Class type) { + this.name = name; + this.value = value; + this.type = type.getName(); + } + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlAttribute(name = "value") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @XmlAttribute(name = "type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/BasicResourceVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/BasicResourceVO.java index 659b030c..2774a1a1 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/BasicResourceVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/BasicResourceVO.java @@ -1,48 +1,48 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * - * Value object for {@link cz.zcu.kiv.crce.metadata.Resource} - * Contains only resource's identity view. - * - * For use in simple listings. - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "resource") -public class BasicResourceVO extends ValueObject { - - /** - * Identity of the resource. - */ - private IdentityCapabilityVO identity; - - public BasicResourceVO() { - } - - public BasicResourceVO(String id, IdentityCapabilityVO identity) { - super(id); - this.identity = identity; - } - - public BasicResourceVO(IdentityCapabilityVO identity) { - this(null, identity); - } - - @XmlElementRef(required = true) - public IdentityCapabilityVO getIdentity() { - return identity; - } - - public void setIdentity(IdentityCapabilityVO identity) { - this.identity = identity; - } -} - +package cz.zcu.kiv.crce.vo.model.metadata; + +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * + * Value object for {@link cz.zcu.kiv.crce.metadata.Resource} + * Contains only resource's identity view. + * + * For use in simple listings. + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "resource") +public class BasicResourceVO extends ValueObject { + + /** + * Identity of the resource. + */ + private IdentityCapabilityVO identity; + + public BasicResourceVO() { + } + + public BasicResourceVO(String id, IdentityCapabilityVO identity) { + super(id); + this.identity = identity; + } + + public BasicResourceVO(IdentityCapabilityVO identity) { + this(null, identity); + } + + @XmlElementRef(required = true) + public IdentityCapabilityVO getIdentity() { + return identity; + } + + public void setIdentity(IdentityCapabilityVO identity) { + this.identity = identity; + } +} + diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/DetailedResourceVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/DetailedResourceVO.java index b5841d4c..c8a1cddf 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/DetailedResourceVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/DetailedResourceVO.java @@ -1,66 +1,66 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * VO containing full information about a resource. - * - * List of all its capabilities, requirements, properties, etc. - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "resource") -public class DetailedResourceVO extends BasicResourceVO { - - private List capabilities = new ArrayList<>(); - private List properties = new ArrayList<>(); - private List requirements = new ArrayList<>(); - - public DetailedResourceVO() { - } - - public DetailedResourceVO(String id, IdentityCapabilityVO identity) { - super(id, identity); - } - - public DetailedResourceVO(IdentityCapabilityVO identity) { - super(identity); - } - - @Nonnull - @XmlElementRef - public List getCapabilities() { - return capabilities; - } - - public void setCapabilities(List capabilities) { - this.capabilities = capabilities; - } - - @Nonnull - @XmlElementRef - public List getRequirements() { - return requirements; - } - - public void setRequirements(List requirements) { - this.requirements = requirements; - } - - @Nonnull - @XmlElementRef - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * VO containing full information about a resource. + * + * List of all its capabilities, requirements, properties, etc. + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "resource") +public class DetailedResourceVO extends BasicResourceVO { + + private List capabilities = new ArrayList<>(); + private List properties = new ArrayList<>(); + private List requirements = new ArrayList<>(); + + public DetailedResourceVO() { + } + + public DetailedResourceVO(String id, IdentityCapabilityVO identity) { + super(id, identity); + } + + public DetailedResourceVO(IdentityCapabilityVO identity) { + super(identity); + } + + @Nonnull + @XmlElementRef + public List getCapabilities() { + return capabilities; + } + + public void setCapabilities(List capabilities) { + this.capabilities = capabilities; + } + + @Nonnull + @XmlElementRef + public List getRequirements() { + return requirements; + } + + public void setRequirements(List requirements) { + this.requirements = requirements; + } + + @Nonnull + @XmlElementRef + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericCapabilityVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericCapabilityVO.java index fa7fd9ff..6b951de5 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericCapabilityVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericCapabilityVO.java @@ -1,92 +1,92 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * - * Generic capability for {@link cz.zcu.kiv.crce.metadata.Capability} - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "capability") -public class GenericCapabilityVO extends ValueObject { - - /** - * List of capability attributes. - */ - private List attributes = new ArrayList<>(); - /** - * List of subcapabilities. - */ - private List capabilities = new ArrayList<>(); - /** - * List of capability's properties. - */ - private List properties = new ArrayList<>(); - /** - * List of capability's requirements. - */ - private List requirements = new ArrayList<>(); - - - public GenericCapabilityVO() { - } - - public GenericCapabilityVO(String namespace) { - this("", namespace); - } - - public GenericCapabilityVO(String id, String namespace) { - super(id, namespace); - } - - - @Nonnull - @XmlElementRef - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - - @Nonnull - @XmlElementRef - public List getCapabilities() { - return capabilities; - } - - public void setCapabilities(List capabilities) { - this.capabilities = capabilities; - } - - @Nonnull - @XmlElementRef - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - @Nonnull - @XmlElementRef - public List getRequirements() { - return requirements; - } - - public void setRequirements(List requirements) { - this.requirements = requirements; - } -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * + * Generic capability for {@link cz.zcu.kiv.crce.metadata.Capability} + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "capability") +public class GenericCapabilityVO extends ValueObject { + + /** + * List of capability attributes. + */ + private List attributes = new ArrayList<>(); + /** + * List of subcapabilities. + */ + private List capabilities = new ArrayList<>(); + /** + * List of capability's properties. + */ + private List properties = new ArrayList<>(); + /** + * List of capability's requirements. + */ + private List requirements = new ArrayList<>(); + + + public GenericCapabilityVO() { + } + + public GenericCapabilityVO(String namespace) { + this("", namespace); + } + + public GenericCapabilityVO(String id, String namespace) { + super(id, namespace); + } + + + @Nonnull + @XmlElementRef + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + @Nonnull + @XmlElementRef + public List getCapabilities() { + return capabilities; + } + + public void setCapabilities(List capabilities) { + this.capabilities = capabilities; + } + + @Nonnull + @XmlElementRef + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + @Nonnull + @XmlElementRef + public List getRequirements() { + return requirements; + } + + public void setRequirements(List requirements) { + this.requirements = requirements; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericRequirementVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericRequirementVO.java index 8393ddaa..5cd0b49b 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericRequirementVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/GenericRequirementVO.java @@ -1,50 +1,50 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * Generic VO for {@link cz.zcu.kiv.crce.metadata.Requirement} - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "requirement") -public class GenericRequirementVO extends ValueObject { - - /** - * List of requirement attributes. - */ - private List attributes = new ArrayList<>(); - /** - * List of requirement's sub-requirements. - */ - private List children = new ArrayList<>(); - - @Nonnull - @XmlElementRef - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - - @Nonnull - @XmlElementRef - public List getChildren() { - return children; - } - - public void setChildren(List children) { - this.children = children; - } -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * Generic VO for {@link cz.zcu.kiv.crce.metadata.Requirement} + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "requirement") +public class GenericRequirementVO extends ValueObject { + + /** + * List of requirement attributes. + */ + private List attributes = new ArrayList<>(); + /** + * List of requirement's sub-requirements. + */ + private List children = new ArrayList<>(); + + @Nonnull + @XmlElementRef + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + @Nonnull + @XmlElementRef + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/IdentityCapabilityVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/IdentityCapabilityVO.java index 43634446..ec313aad 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/IdentityCapabilityVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/IdentityCapabilityVO.java @@ -1,253 +1,253 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import org.apache.commons.lang3.StringUtils; - -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * - * Easy-to-use view of CRCE Identity Capability instances. - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@ParametersAreNonnullByDefault -@XmlRootElement(name = "capability") -public class IdentityCapabilityVO extends ValueObject { - - /** - * CRCE external id - identificator from the external system. - * - * E.g. osgi symbolic name. - */ - private AttributeVO externalId; - /** - * CRCE Readable name. E.g. osgi presentation name. - */ - private AttributeVO name; - /** - * Resource version string representation - */ - private AttributeVO version; - /** - * Original version of the resource (if CRCE calculates - * the version itself). - */ - private AttributeVO originalVersion; - /** - * Size of the resource binary. - */ - private AttributeVO size; - /** - * List of resource Type tags - */ - private AttributeVO types; - /** - * List of resource Category tags. - */ - private AttributeVO categories; - - public IdentityCapabilityVO() { - this(""); - } - - public IdentityCapabilityVO(String id) { - super(id, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - } - - public IdentityCapabilityVO(String id, String externalId, String name, String version) { - this(id); - this.externalId = new AttributeVO(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID.getName(), externalId); - this.name = new AttributeVO(NsCrceIdentity.ATTRIBUTE__NAME.getName(), name); - this.version = new AttributeVO(NsCrceIdentity.ATTRIBUTE__VERSION.getName(), version); - } - - /* - ################MAPPING INTERFACE ######################### - */ - - @XmlElementRef - AttributeVO getExternalIdAt() { - return externalId; - } - - void setExternalIdAt(AttributeVO externalId) { - this.externalId = externalId; - } - - @XmlElementRef - AttributeVO getNameAt() { - return name; - } - - void setNameAt(AttributeVO nameAt) { - this.name = nameAt; - } - - @XmlElementRef - AttributeVO getVersionAt() { - return version; - } - - void setVersionAt(AttributeVO versionAt) { - this.version = versionAt; - } - - @XmlElementRef - AttributeVO getOriginalVersionAt() { - return originalVersion; - } - - void setOriginalVersionAt(AttributeVO originalVersionAt) { - this.originalVersion = originalVersionAt; - } - - @XmlElementRef - AttributeVO getSizeAt() { - return size; - } - - void setSizeAt(AttributeVO sizeAt) { - this.size = sizeAt; - } - - @XmlElementRef - AttributeVO getTypesAt() { - return types; - } - - void setTypesAt(AttributeVO typesAt) { - this.types = typesAt; - } - - @XmlElementRef - AttributeVO getCategoriesAt() { - return categories; - } - - void setCategoriesAt(AttributeVO categoriesAt) { - this.categories = categoriesAt; - } - - /* - ################### PUBLIC INTERFACE ######################### - */ - - @Nonnull - public String getExternalId() { - return externalId.getValue(); - } - - protected void setExternalId(String externalId) { - this.externalId.setValue(externalId); - } - - @Nonnull - public String getName() { - return name.getValue(); - } - - protected void setName(String name) { - this.name.setValue(name); - } - - @Nonnull - public String getVersion() { - return version.getValue(); - } - - protected void setVersion(String version) { - this.version.setValue(version); - } - - @Nullable - public String getOriginalVersion() { - if(originalVersion == null) { - return null; - } - return originalVersion.getValue(); - } - - public void setOriginalVersion(String originalVersion) { - if(this.originalVersion == null) { - this.originalVersion = new AttributeVO(NsCrceIdentity.ATTRIBUTE__VERSION.getName(), originalVersion); - } else { - this.originalVersion.setValue(originalVersion); - } - } - - @Nullable - @XmlTransient - public Long getSize() { - if(size == null) { - return null; - } - return Long.parseLong(size.getValue()); - } - - public void setSize(Long size) { - if(this.size == null) { - this.size = new AttributeVO(NsCrceIdentity.ATTRIBUTE__SIZE.getName(), size.toString()); - } else { - this.size.setValue(size.toString()); - } - } - - @Nonnull - public List getTypes() { - if(this.types == null) { - return new ArrayList<>(); - } - return Arrays.asList(types.getValue().split(",")); - } - - protected void setTypes(@Nonnull List types) { - String value = StringUtils.join(types, ","); - if(this.types == null) { - this.types = new AttributeVO(NsCrceIdentity.ATTRIBUTE__TYPES.getName(), value); - } else { - this.types.setValue(value); - } - } - - @Nonnull - public List getCategories() { - if(categories == null) { - return new ArrayList<>(); - } - return Arrays.asList(categories.getValue().split(",")); - } - - public void addCategory(String cat) { - if(categories == null) { - this.categories = new AttributeVO(NsCrceIdentity.ATTRIBUTE__CATEGORIES.getName(), cat); - } else { - String oldVal = this.categories.getValue(); - oldVal = oldVal.concat("," + cat); - this.categories.setValue(oldVal); - } - } - - - protected void setCategories(@Nonnull List categories) { - String value = StringUtils.join(categories, ","); - if(this.categories == null) { - this.categories = new AttributeVO(NsCrceIdentity.ATTRIBUTE__CATEGORIES.getName(), value); - } else { - this.categories.setValue(value); - } - } -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlTransient; + +import org.apache.commons.lang3.StringUtils; + +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * + * Easy-to-use view of CRCE Identity Capability instances. + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@ParametersAreNonnullByDefault +@XmlRootElement(name = "capability") +public class IdentityCapabilityVO extends ValueObject { + + /** + * CRCE external id - identificator from the external system. + * + * E.g. osgi symbolic name. + */ + private AttributeVO externalId; + /** + * CRCE Readable name. E.g. osgi presentation name. + */ + private AttributeVO name; + /** + * Resource version string representation + */ + private AttributeVO version; + /** + * Original version of the resource (if CRCE calculates + * the version itself). + */ + private AttributeVO originalVersion; + /** + * Size of the resource binary. + */ + private AttributeVO size; + /** + * List of resource Type tags + */ + private AttributeVO types; + /** + * List of resource Category tags. + */ + private AttributeVO categories; + + public IdentityCapabilityVO() { + this(""); + } + + public IdentityCapabilityVO(String id) { + super(id, NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + } + + public IdentityCapabilityVO(String id, String externalId, String name, String version) { + this(id); + this.externalId = new AttributeVO(NsCrceIdentity.ATTRIBUTE__EXTERNAL_ID.getName(), externalId); + this.name = new AttributeVO(NsCrceIdentity.ATTRIBUTE__NAME.getName(), name); + this.version = new AttributeVO(NsCrceIdentity.ATTRIBUTE__VERSION.getName(), version); + } + + /* + ################MAPPING INTERFACE ######################### + */ + + @XmlElementRef + AttributeVO getExternalIdAt() { + return externalId; + } + + void setExternalIdAt(AttributeVO externalId) { + this.externalId = externalId; + } + + @XmlElementRef + AttributeVO getNameAt() { + return name; + } + + void setNameAt(AttributeVO nameAt) { + this.name = nameAt; + } + + @XmlElementRef + AttributeVO getVersionAt() { + return version; + } + + void setVersionAt(AttributeVO versionAt) { + this.version = versionAt; + } + + @XmlElementRef + AttributeVO getOriginalVersionAt() { + return originalVersion; + } + + void setOriginalVersionAt(AttributeVO originalVersionAt) { + this.originalVersion = originalVersionAt; + } + + @XmlElementRef + AttributeVO getSizeAt() { + return size; + } + + void setSizeAt(AttributeVO sizeAt) { + this.size = sizeAt; + } + + @XmlElementRef + AttributeVO getTypesAt() { + return types; + } + + void setTypesAt(AttributeVO typesAt) { + this.types = typesAt; + } + + @XmlElementRef + AttributeVO getCategoriesAt() { + return categories; + } + + void setCategoriesAt(AttributeVO categoriesAt) { + this.categories = categoriesAt; + } + + /* + ################### PUBLIC INTERFACE ######################### + */ + + @Nonnull + public String getExternalId() { + return externalId.getValue(); + } + + protected void setExternalId(String externalId) { + this.externalId.setValue(externalId); + } + + @Nonnull + public String getName() { + return name.getValue(); + } + + protected void setName(String name) { + this.name.setValue(name); + } + + @Nonnull + public String getVersion() { + return version.getValue(); + } + + protected void setVersion(String version) { + this.version.setValue(version); + } + + @Nullable + public String getOriginalVersion() { + if(originalVersion == null) { + return null; + } + return originalVersion.getValue(); + } + + public void setOriginalVersion(String originalVersion) { + if(this.originalVersion == null) { + this.originalVersion = new AttributeVO(NsCrceIdentity.ATTRIBUTE__VERSION.getName(), originalVersion); + } else { + this.originalVersion.setValue(originalVersion); + } + } + + @Nullable + @XmlTransient + public Long getSize() { + if(size == null) { + return null; + } + return Long.parseLong(size.getValue()); + } + + public void setSize(Long size) { + if(this.size == null) { + this.size = new AttributeVO(NsCrceIdentity.ATTRIBUTE__SIZE.getName(), size.toString()); + } else { + this.size.setValue(size.toString()); + } + } + + @Nonnull + public List getTypes() { + if(this.types == null) { + return new ArrayList<>(); + } + return Arrays.asList(types.getValue().split(",")); + } + + protected void setTypes(@Nonnull List types) { + String value = StringUtils.join(types, ","); + if(this.types == null) { + this.types = new AttributeVO(NsCrceIdentity.ATTRIBUTE__TYPES.getName(), value); + } else { + this.types.setValue(value); + } + } + + @Nonnull + public List getCategories() { + if(categories == null) { + return new ArrayList<>(); + } + return Arrays.asList(categories.getValue().split(",")); + } + + public void addCategory(String cat) { + if(categories == null) { + this.categories = new AttributeVO(NsCrceIdentity.ATTRIBUTE__CATEGORIES.getName(), cat); + } else { + String oldVal = this.categories.getValue(); + oldVal = oldVal.concat("," + cat); + this.categories.setValue(oldVal); + } + } + + + protected void setCategories(@Nonnull List categories) { + String value = StringUtils.join(categories, ","); + if(this.categories == null) { + this.categories = new AttributeVO(NsCrceIdentity.ATTRIBUTE__CATEGORIES.getName(), value); + } else { + this.categories.setValue(value); + } + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/PropertyVO.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/PropertyVO.java index 54456ed0..99606385 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/PropertyVO.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/model/metadata/PropertyVO.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.vo.model.metadata; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import cz.zcu.kiv.crce.vo.model.ValueObject; - -/** - * Value object for {@link cz.zcu.kiv.crce.metadata.Property} - * - * Date: 1.6.15 - * - * @author Jakub Danek - */ -@XmlRootElement(name = "property") -public class PropertyVO extends ValueObject { - - private List attributes = new ArrayList<>(); - - public PropertyVO() { - } - - @Nonnull - @XmlElementRef - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } -} +package cz.zcu.kiv.crce.vo.model.metadata; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; + +import cz.zcu.kiv.crce.vo.model.ValueObject; + +/** + * Value object for {@link cz.zcu.kiv.crce.metadata.Property} + * + * Date: 1.6.15 + * + * @author Jakub Danek + */ +@XmlRootElement(name = "property") +public class PropertyVO extends ValueObject { + + private List attributes = new ArrayList<>(); + + public PropertyVO() { + } + + @Nonnull + @XmlElementRef + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } +} diff --git a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/service/MappingService.java b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/service/MappingService.java index d5be616e..cb8807fb 100644 --- a/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/service/MappingService.java +++ b/modules/crce-vo/src/main/java/cz/zcu/kiv/crce/vo/service/MappingService.java @@ -1,78 +1,78 @@ -package cz.zcu.kiv.crce.vo.service; - -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; - -/** - * - * Service for mapping CRCE inner representation APIs into - * value objects. - * - * Date: 5.5.15 - * - * @author Jakub Danek - */ -@ParametersAreNonnullByDefault -public interface MappingService { - - /** - * Maps single resource into BasicResourceVO which contains - * only identity information about the resource. - * @param resource - * @return - */ - @Nullable - BasicResourceVO mapBasic(@Nullable Resource resource); - - /** - * Maps list of resources into BasicResourceVos which - * contain only identity of the resources. - * @param resources - * @return - */ - @Nonnull - List mapBasic(List resources); - - /** - * Maps resource into VO including all details. - * - * @param resource - * @return - */ - @Nullable - DetailedResourceVO mapFull(@Nullable Resource resource); - - /** - * Maps list of resource into VOs including all details. - * - * @param resources - * @return - */ - @Nonnull - List mapFull(List resources); - - /** - * Maps list of compatibility metadata into VOs - * @param diffs metadata to be mapped - * @return - */ - @Nonnull - List mapCompatibility(List diffs); - - /** - * Maps single piece of compatibility meta-data into VO - * @param diff piece of meta-data to be mapped - * @return - */ - @Nullable - CompatibilityVO mapCompatibility(@Nullable Compatibility diff); -} +package cz.zcu.kiv.crce.vo.service; + +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; + +/** + * + * Service for mapping CRCE inner representation APIs into + * value objects. + * + * Date: 5.5.15 + * + * @author Jakub Danek + */ +@ParametersAreNonnullByDefault +public interface MappingService { + + /** + * Maps single resource into BasicResourceVO which contains + * only identity information about the resource. + * @param resource + * @return + */ + @Nullable + BasicResourceVO mapBasic(@Nullable Resource resource); + + /** + * Maps list of resources into BasicResourceVos which + * contain only identity of the resources. + * @param resources + * @return + */ + @Nonnull + List mapBasic(List resources); + + /** + * Maps resource into VO including all details. + * + * @param resource + * @return + */ + @Nullable + DetailedResourceVO mapFull(@Nullable Resource resource); + + /** + * Maps list of resource into VOs including all details. + * + * @param resources + * @return + */ + @Nonnull + List mapFull(List resources); + + /** + * Maps list of compatibility metadata into VOs + * @param diffs metadata to be mapped + * @return + */ + @Nonnull + List mapCompatibility(List diffs); + + /** + * Maps single piece of compatibility meta-data into VO + * @param diff piece of meta-data to be mapped + * @return + */ + @Nullable + CompatibilityVO mapCompatibility(@Nullable Compatibility diff); +} diff --git a/modules/crce-vo/src/main/resources/mappings.xml b/modules/crce-vo/src/main/resources/mappings.xml index 72d891f0..b6228a60 100644 --- a/modules/crce-vo/src/main/resources/mappings.xml +++ b/modules/crce-vo/src/main/resources/mappings.xml @@ -1,68 +1,68 @@ - - - - - true - true - - - - - cz.zcu.kiv.crce.metadata.Resource - cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO - - - - cz.zcu.kiv.crce.metadata.Resource - cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO - - - - cz.zcu.kiv.crce.metadata.Capability - cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO - - - - - - - cz.zcu.kiv.crce.metadata.Capability - cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO - - children - capabilities - cz.zcu.kiv.crce.metadata.Capability - cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO - - - - - cz.zcu.kiv.crce.compatibility.Compatibility - cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO - - - resourceName - otherExternalId - - - resourceVersion - otherVersion - - - baseResourceName - baseExternalId - - - baseResourceVersion - baseVersion - - - diffDetails - diffs - - - - + + + + + true + true + + + + + cz.zcu.kiv.crce.metadata.Resource + cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO + + + + cz.zcu.kiv.crce.metadata.Resource + cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO + + + + cz.zcu.kiv.crce.metadata.Capability + cz.zcu.kiv.crce.vo.model.metadata.IdentityCapabilityVO + + + + + + + cz.zcu.kiv.crce.metadata.Capability + cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO + + children + capabilities + cz.zcu.kiv.crce.metadata.Capability + cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO + + + + + cz.zcu.kiv.crce.compatibility.Compatibility + cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO + + + resourceName + otherExternalId + + + resourceVersion + otherVersion + + + baseResourceName + baseExternalId + + + baseResourceVersion + baseVersion + + + diffDetails + diffs + + + + diff --git a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/DozerMapperTest.java b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/DozerMapperTest.java index 62995e64..c648978a 100644 --- a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/DozerMapperTest.java +++ b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/DozerMapperTest.java @@ -1,129 +1,129 @@ -package cz.zcu.kiv.crce.vo.internal.dozer; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.util.LinkedList; -import java.util.List; - -import org.dozer.DozerBeanMapper; -import org.dozer.Mapper; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mockito; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.Contract; -import cz.zcu.kiv.crce.compatibility.Diff; -import cz.zcu.kiv.crce.compatibility.Difference; -import cz.zcu.kiv.crce.compatibility.DifferenceLevel; -import cz.zcu.kiv.crce.compatibility.DifferenceRole; -import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; -import cz.zcu.kiv.crce.vo.model.compatibility.DiffVO; - -/** - * Date: 4.9.15 - * - * @author Jakub Danek - */ -public class DozerMapperTest { - - - private static Mapper mapper; - - @BeforeClass - public static void setUpClass() throws Exception { - List mappings = new LinkedList<>(); - mappings.add("mappings.xml"); - mapper = new DozerBeanMapper(mappings); - } - - @Test - public void testCompatibilityTo() throws Exception { - Compatibility mock = initCompatibilityMock(); - CompatibilityVO vo = mapper.map(mock, CompatibilityVO.class); - - assertEquals(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY, vo.getNamespace()); - assertEquals(mock.getId(), vo.getId()); - assertEquals(mock.getResourceName(), vo.getOtherExternalId()); - assertEquals(mock.getBaseResourceName(), vo.getBaseExternalId()); - assertEquals(mock.getResourceVersion(), new Version(vo.getOtherVersion())); - assertEquals(mock.getBaseResourceVersion(), new Version(vo.getBaseVersion())); - assertEquals(mock.getContract(), vo.getContract()); - assertEquals(mock.getDiffValue(), vo.getDiffValue()); - - int i = 0; - //noinspection ConstantConditions - for (Diff diff : mock.getDiffDetails()) { - DiffVO dvo = vo.getDiffs().get(i); - compareDiffs(diff, dvo); - i++; - } - - } - - @Test - @Ignore("not implemented yet") - public void testCompatibilityFrom() throws Exception { - - - } - - private void compareDiffs(Diff diff, DiffVO dvo) { - assertEquals(diff.getLevel(), dvo.getLevel()); - assertEquals(diff.getName(), dvo.getName()); - assertEquals(diff.getRole(), dvo.getRole()); - assertEquals(diff.getSyntax(), dvo.getSyntax()); - assertEquals(diff.getValue(), dvo.getValue()); - assertEquals(diff.getNamespace(), dvo.getNamespace()); - - int i = 0; - for (Diff d : diff.getChildren()) { - DiffVO dv = dvo.getChildren().get(i); - compareDiffs(d, dv); - i++; - } - } - - private Compatibility initCompatibilityMock() { - Compatibility cmp = Mockito.mock(Compatibility.class); - - when(cmp.getId()).thenReturn("UUID-UUID-UUID"); - when(cmp.getBaseResourceName()).thenReturn("test.component.bundle"); - when(cmp.getBaseResourceVersion()).thenReturn(new Version(1,0,4, "qualifier")); - when(cmp.getDiffValue()).thenReturn(Difference.DEL); - when(cmp.getContract()).thenReturn(Contract.SYNTAX); - when(cmp.getResourceName()).thenReturn("test.component.bundle"); - when(cmp.getResourceVersion()).thenReturn(new Version(2,0,1,"ololo")); - - List diffs = new LinkedList<>(); - diffs.add(initDiff("cz.kiv.pokus.a", DifferenceLevel.PACKAGE, Difference.DEL, true)); - diffs.add(initDiff("cz.kiv.pokus.b", DifferenceLevel.PACKAGE, Difference.NON, true)); - when(cmp.getDiffDetails()).thenReturn(diffs); - - return cmp; - } - - private Diff initDiff(String name, DifferenceLevel level, Difference val, boolean includeChildren) { - Diff diff = Mockito.mock(Diff.class); - - when(diff.getName()).thenReturn(name); - when(diff.getValue()).thenReturn(val); - when(diff.getLevel()).thenReturn(level); - when(diff.getRole()).thenReturn(DifferenceRole.CAPABILITY); - when(diff.getSyntax()).thenReturn(NsCrceCompatibility.DIFF_SYNTAX_JAVA); - - List diffs = new LinkedList<>(); - if(includeChildren) { - diffs.add(initDiff("Foo", DifferenceLevel.TYPE, val, false)); - diffs.add(initDiff("Bar", DifferenceLevel.TYPE, Difference.NON, false)); - - } - when(diff.getChildren()).thenReturn(diffs); - - return diff; - } -} +package cz.zcu.kiv.crce.vo.internal.dozer; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.LinkedList; +import java.util.List; + +import org.dozer.DozerBeanMapper; +import org.dozer.Mapper; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.Contract; +import cz.zcu.kiv.crce.compatibility.Diff; +import cz.zcu.kiv.crce.compatibility.Difference; +import cz.zcu.kiv.crce.compatibility.DifferenceLevel; +import cz.zcu.kiv.crce.compatibility.DifferenceRole; +import cz.zcu.kiv.crce.compatibility.namespace.NsCrceCompatibility; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.vo.model.compatibility.CompatibilityVO; +import cz.zcu.kiv.crce.vo.model.compatibility.DiffVO; + +/** + * Date: 4.9.15 + * + * @author Jakub Danek + */ +public class DozerMapperTest { + + + private static Mapper mapper; + + @BeforeClass + public static void setUpClass() throws Exception { + List mappings = new LinkedList<>(); + mappings.add("mappings.xml"); + mapper = new DozerBeanMapper(mappings); + } + + @Test + public void testCompatibilityTo() throws Exception { + Compatibility mock = initCompatibilityMock(); + CompatibilityVO vo = mapper.map(mock, CompatibilityVO.class); + + assertEquals(NsCrceCompatibility.NAMESPACE__CRCE_COMPATIBILITY, vo.getNamespace()); + assertEquals(mock.getId(), vo.getId()); + assertEquals(mock.getResourceName(), vo.getOtherExternalId()); + assertEquals(mock.getBaseResourceName(), vo.getBaseExternalId()); + assertEquals(mock.getResourceVersion(), new Version(vo.getOtherVersion())); + assertEquals(mock.getBaseResourceVersion(), new Version(vo.getBaseVersion())); + assertEquals(mock.getContract(), vo.getContract()); + assertEquals(mock.getDiffValue(), vo.getDiffValue()); + + int i = 0; + //noinspection ConstantConditions + for (Diff diff : mock.getDiffDetails()) { + DiffVO dvo = vo.getDiffs().get(i); + compareDiffs(diff, dvo); + i++; + } + + } + + @Test + @Ignore("not implemented yet") + public void testCompatibilityFrom() throws Exception { + + + } + + private void compareDiffs(Diff diff, DiffVO dvo) { + assertEquals(diff.getLevel(), dvo.getLevel()); + assertEquals(diff.getName(), dvo.getName()); + assertEquals(diff.getRole(), dvo.getRole()); + assertEquals(diff.getSyntax(), dvo.getSyntax()); + assertEquals(diff.getValue(), dvo.getValue()); + assertEquals(diff.getNamespace(), dvo.getNamespace()); + + int i = 0; + for (Diff d : diff.getChildren()) { + DiffVO dv = dvo.getChildren().get(i); + compareDiffs(d, dv); + i++; + } + } + + private Compatibility initCompatibilityMock() { + Compatibility cmp = Mockito.mock(Compatibility.class); + + when(cmp.getId()).thenReturn("UUID-UUID-UUID"); + when(cmp.getBaseResourceName()).thenReturn("test.component.bundle"); + when(cmp.getBaseResourceVersion()).thenReturn(new Version(1,0,4, "qualifier")); + when(cmp.getDiffValue()).thenReturn(Difference.DEL); + when(cmp.getContract()).thenReturn(Contract.SYNTAX); + when(cmp.getResourceName()).thenReturn("test.component.bundle"); + when(cmp.getResourceVersion()).thenReturn(new Version(2,0,1,"ololo")); + + List diffs = new LinkedList<>(); + diffs.add(initDiff("cz.kiv.pokus.a", DifferenceLevel.PACKAGE, Difference.DEL, true)); + diffs.add(initDiff("cz.kiv.pokus.b", DifferenceLevel.PACKAGE, Difference.NON, true)); + when(cmp.getDiffDetails()).thenReturn(diffs); + + return cmp; + } + + private Diff initDiff(String name, DifferenceLevel level, Difference val, boolean includeChildren) { + Diff diff = Mockito.mock(Diff.class); + + when(diff.getName()).thenReturn(name); + when(diff.getValue()).thenReturn(val); + when(diff.getLevel()).thenReturn(level); + when(diff.getRole()).thenReturn(DifferenceRole.CAPABILITY); + when(diff.getSyntax()).thenReturn(NsCrceCompatibility.DIFF_SYNTAX_JAVA); + + List diffs = new LinkedList<>(); + if(includeChildren) { + diffs.add(initDiff("Foo", DifferenceLevel.TYPE, val, false)); + diffs.add(initDiff("Bar", DifferenceLevel.TYPE, Difference.NON, false)); + + } + when(diff.getChildren()).thenReturn(diffs); + + return diff; + } +} diff --git a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertorTest.java b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertorTest.java index 5cc00d4a..fac01815 100644 --- a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertorTest.java +++ b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/BasicResourceConvertorTest.java @@ -1,95 +1,95 @@ -package cz.zcu.kiv.crce.vo.internal.dozer.convertor; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.dozer.DozerBeanMapper; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; - -/** - * Test for {@link BasicResourceConvertor} class. - * - * Date: 15.5.15 - * - * @author Jakub Danek - */ -public class BasicResourceConvertorTest { - - private BasicResourceConvertor convertor; - - /* - ##### MOCKS ##### - */ - @Mock - private MetadataService metadataService; - @Mock - private Resource resource; - - @Before - public void setUp() throws Exception { - initMocks(); - initDozer(); - } - - private void initMocks() { - MockitoAnnotations.initMocks(this); - reset(metadataService, resource); - } - - - private void initDozer() { - convertor = new BasicResourceConvertor(); - convertor.setMetadataService(metadataService); - convertor.setMapper(new DozerBeanMapper(Arrays.asList("mappings.xml"))); - } - - /** - * Tests conversion from Resource to BasicResourceVO. - * - * @throws Exception - */ - @Test - public void testConvertTo() throws Exception { - Capability c = Mockito.mock(Capability.class); - when(c.getNamespace()).thenReturn(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - - String name = "cz.zcu.kiv.vo.test.Component"; - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME)).thenReturn(name); - - Version version = new Version(2,1,1); - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION)).thenReturn(version); - - Long size = 1024l; - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE)) .thenReturn(size); - - List categories = new ArrayList<>(); - categories.add("osgi"); - categories.add("jar"); - categories.add("test"); - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES)).thenReturn(categories); - - when(metadataService.getIdentity(resource)).thenReturn(c); - - BasicResourceVO vo = convertor.convertTo(resource, null); - assertEquals(name, vo.getIdentity().getName()); - assertEquals(version.toString(), vo.getIdentity().getVersion()); - assertEquals(size, vo.getIdentity().getSize()); - assertEquals(categories, vo.getIdentity().getCategories()); - } +package cz.zcu.kiv.crce.vo.internal.dozer.convertor; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.dozer.DozerBeanMapper; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.vo.model.metadata.BasicResourceVO; + +/** + * Test for {@link BasicResourceConvertor} class. + * + * Date: 15.5.15 + * + * @author Jakub Danek + */ +public class BasicResourceConvertorTest { + + private BasicResourceConvertor convertor; + + /* + ##### MOCKS ##### + */ + @Mock + private MetadataService metadataService; + @Mock + private Resource resource; + + @Before + public void setUp() throws Exception { + initMocks(); + initDozer(); + } + + private void initMocks() { + MockitoAnnotations.initMocks(this); + reset(metadataService, resource); + } + + + private void initDozer() { + convertor = new BasicResourceConvertor(); + convertor.setMetadataService(metadataService); + convertor.setMapper(new DozerBeanMapper(Arrays.asList("mappings.xml"))); + } + + /** + * Tests conversion from Resource to BasicResourceVO. + * + * @throws Exception + */ + @Test + public void testConvertTo() throws Exception { + Capability c = Mockito.mock(Capability.class); + when(c.getNamespace()).thenReturn(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + + String name = "cz.zcu.kiv.vo.test.Component"; + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME)).thenReturn(name); + + Version version = new Version(2,1,1); + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION)).thenReturn(version); + + Long size = 1024l; + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE)) .thenReturn(size); + + List categories = new ArrayList<>(); + categories.add("osgi"); + categories.add("jar"); + categories.add("test"); + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES)).thenReturn(categories); + + when(metadataService.getIdentity(resource)).thenReturn(c); + + BasicResourceVO vo = convertor.convertTo(resource, null); + assertEquals(name, vo.getIdentity().getName()); + assertEquals(version.toString(), vo.getIdentity().getVersion()); + assertEquals(size, vo.getIdentity().getSize()); + assertEquals(categories, vo.getIdentity().getCategories()); + } } \ No newline at end of file diff --git a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverterTest.java b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverterTest.java index cf313151..076f1ceb 100644 --- a/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverterTest.java +++ b/modules/crce-vo/src/test/java/cz/zcu/kiv/crce/vo/internal/dozer/convertor/DetailedResourceConverterTest.java @@ -1,256 +1,256 @@ -package cz.zcu.kiv.crce.vo.internal.dozer.convertor; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.dozer.DozerBeanMapper; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import cz.zcu.kiv.crce.metadata.Attribute; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.vo.model.metadata.AttributeVO; -import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; -import cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO; -import cz.zcu.kiv.crce.vo.model.metadata.GenericRequirementVO; -import cz.zcu.kiv.crce.vo.model.metadata.PropertyVO; - -/** - * Test class of {@link DetailedResourceConverter}. - * - * Date: 5.6.15 - * - * @author Jakub Danek - */ -public class DetailedResourceConverterTest { - - private static final String CUSTOM_CAPABILITY_NS = "custom.namespace"; - private static final String CUSTOM_ATTR_NAME = "custom.attribute"; - private static final String CUSTOM_ATTR_VALUE = "custom.attr.value"; - private static final String CUSTOM_PROPERTY_NS = "custom.prop.ns"; - private static final String CUSTOM_REQUIREMENT_NS = "custom.req.ns"; - private static final String CUSTOM_ID = "id"; - private static final String CMP_NAME = "cz.zcu.kiv.vo.test.Component"; - - private DetailedResourceConverter convertor; - - /* - ##### MOCKS ##### - */ - @Mock - private MetadataService metadataService; - @Mock - private Resource resource; - - /* - TEST DATA - */ - private Version version; - private Long size; - private List categories; - - - @Before - public void setUp() throws Exception { - initMocks(); - initDozer(); - } - - private void initMocks() { - MockitoAnnotations.initMocks(this); - reset(metadataService, resource); - } - - - private void initDozer() { - convertor = new DetailedResourceConverter(metadataService); - convertor.setMapper(new DozerBeanMapper(Arrays.asList("mappings.xml"))); - } - - /** - * Test of conversion from Resource to DetailedResourceVO - * @throws Exception - */ - @Test - public void testConvertTo() throws Exception { - initIdentity(resource); - - List roots = Arrays.asList(initCustomCapabilityTree(resource, null)); - when(resource.getRootCapabilities()).thenReturn(roots); - List props = Arrays.asList(initCustomProperty()); - when(resource.getProperties()).thenReturn(props); - - DetailedResourceVO vo = new DetailedResourceVO(); - convertor.convertTo(resource, vo); - - //test basic mapping - assertEquals(CMP_NAME, vo.getIdentity().getName()); - assertEquals(version.toString(), vo.getIdentity().getVersion()); - assertEquals(size, vo.getIdentity().getSize()); - assertEquals(categories, vo.getIdentity().getCategories()); - - //test detailed mapping - - //capabilities - assertEquals(1, vo.getCapabilities().size()); - GenericCapabilityVO cap = vo.getCapabilities().get(0); - testCapability(cap); - - //test child capability - assertEquals(1, cap.getCapabilities().size()); //has child capability - cap = cap.getCapabilities().get(0); - testCapability(cap); - - //test resource requirements - assertEquals(1, vo.getRequirements().size()); - testRequirement(vo.getRequirements().get(0)); - - //test resource properties - assertEquals(1, vo.getProperties().size()); - testProperty(vo.getProperties().get(0)); - } - - @Test - @Ignore("Not implemented yet.") - public void testConvertFrom() throws Exception { - - } - - /* - DATA INITS AND HELPERS - */ - - private void testCapability(GenericCapabilityVO cap) { - assertEquals(CUSTOM_ID, cap.getId()); - assertEquals(CUSTOM_CAPABILITY_NS, cap.getNamespace()); - - //capability attribute - assertEquals(1, cap.getAttributes().size()); - AttributeVO at = cap.getAttributes().get(0); - testAttribute(at); - - //capability property - assertEquals(1, cap.getProperties().size()); - PropertyVO prop = cap.getProperties().get(0); - testProperty(prop); - - //property attribute - assertEquals(1, prop.getAttributes().size()); - at = prop.getAttributes().get(0); - testAttribute(at); - - //capability requirement - assertEquals(1, cap.getRequirements().size()); - GenericRequirementVO req = cap.getRequirements().get(0); - testRequirement(req); - } - - private void testRequirement(GenericRequirementVO req) { - assertEquals(CUSTOM_ID, req.getId()); - assertEquals(CUSTOM_REQUIREMENT_NS, req.getNamespace()); - assertEquals(1, req.getAttributes().size()); - testAttribute(req.getAttributes().get(0)); - } - - private void testAttribute(AttributeVO at) { - assertEquals(CUSTOM_ATTR_NAME, at.getName()); - assertEquals(CUSTOM_ATTR_VALUE, at.getValue()); - } - - private void testProperty(PropertyVO prop) { - assertEquals(CUSTOM_ID, prop.getId()); - assertEquals(CUSTOM_PROPERTY_NS, prop.getNamespace()); - } - - private void initIdentity(Resource resource) { - Capability c = Mockito.mock(Capability.class); - when(c.getNamespace()).thenReturn(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); - - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME)).thenReturn(CMP_NAME); - - version = new Version(2,1,1); - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION)).thenReturn(version); - - size = 1024l; - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE)) .thenReturn(size); - - categories = new ArrayList<>(); - categories.add("osgi"); - categories.add("jar"); - categories.add("test"); - when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES)).thenReturn(categories); - - when(metadataService.getIdentity(resource)).thenReturn(c); - } - - private Capability initCustomCapabilityTree(Resource resource, Capability root) { - Capability c = Mockito.mock(Capability.class); - when(c.getId()).thenReturn(CUSTOM_ID); - when(c.getNamespace()).thenReturn(CUSTOM_CAPABILITY_NS); - - List list = Arrays.asList(initCustomAttribute()); - when(c.getAttributes()).thenReturn(list); - list = Arrays.asList(initCustomProperty()); - when(c.getProperties()).thenReturn(list); - list = Arrays.asList(initCustomRequirement(resource)); - when(c.getRequirements()).thenReturn(list); - - if (root == null) { - list = Arrays.asList(initCustomCapabilityTree(resource, c)); - when(c.getChildren()).thenReturn(list); - } - - return c; - } - - private Property initCustomProperty() { - Property p = Mockito.mock(Property.class); - - when(p.getId()).thenReturn(CUSTOM_ID); - when(p.getNamespace()).thenReturn(CUSTOM_PROPERTY_NS); - - List list = Arrays.asList(initCustomAttribute()); - when(p.getAttributes()).thenReturn(list); - - return p; - } - - private Attribute initCustomAttribute() { - Attribute a = Mockito.mock(Attribute.class); - when(a.getName()).thenReturn(CUSTOM_ATTR_NAME); - when(a.getValue()).thenReturn(CUSTOM_ATTR_VALUE); - - return a; - } - - private Requirement initCustomRequirement(Resource resource) { - Requirement r = Mockito.mock(Requirement.class); - when(r.getNamespace()).thenReturn(CUSTOM_REQUIREMENT_NS); - when(r.getId()).thenReturn(CUSTOM_ID); - - List list = Arrays.asList(initCustomAttribute()); - when(r.getAttributes()).thenReturn(list); - - if(resource != null) { - when(resource.getRequirements()).thenReturn(Collections.singletonList(r)); - } - - return r; - } +package cz.zcu.kiv.crce.vo.internal.dozer.convertor; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.dozer.DozerBeanMapper; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import cz.zcu.kiv.crce.metadata.Attribute; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.vo.model.metadata.AttributeVO; +import cz.zcu.kiv.crce.vo.model.metadata.DetailedResourceVO; +import cz.zcu.kiv.crce.vo.model.metadata.GenericCapabilityVO; +import cz.zcu.kiv.crce.vo.model.metadata.GenericRequirementVO; +import cz.zcu.kiv.crce.vo.model.metadata.PropertyVO; + +/** + * Test class of {@link DetailedResourceConverter}. + * + * Date: 5.6.15 + * + * @author Jakub Danek + */ +public class DetailedResourceConverterTest { + + private static final String CUSTOM_CAPABILITY_NS = "custom.namespace"; + private static final String CUSTOM_ATTR_NAME = "custom.attribute"; + private static final String CUSTOM_ATTR_VALUE = "custom.attr.value"; + private static final String CUSTOM_PROPERTY_NS = "custom.prop.ns"; + private static final String CUSTOM_REQUIREMENT_NS = "custom.req.ns"; + private static final String CUSTOM_ID = "id"; + private static final String CMP_NAME = "cz.zcu.kiv.vo.test.Component"; + + private DetailedResourceConverter convertor; + + /* + ##### MOCKS ##### + */ + @Mock + private MetadataService metadataService; + @Mock + private Resource resource; + + /* + TEST DATA + */ + private Version version; + private Long size; + private List categories; + + + @Before + public void setUp() throws Exception { + initMocks(); + initDozer(); + } + + private void initMocks() { + MockitoAnnotations.initMocks(this); + reset(metadataService, resource); + } + + + private void initDozer() { + convertor = new DetailedResourceConverter(metadataService); + convertor.setMapper(new DozerBeanMapper(Arrays.asList("mappings.xml"))); + } + + /** + * Test of conversion from Resource to DetailedResourceVO + * @throws Exception + */ + @Test + public void testConvertTo() throws Exception { + initIdentity(resource); + + List roots = Arrays.asList(initCustomCapabilityTree(resource, null)); + when(resource.getRootCapabilities()).thenReturn(roots); + List props = Arrays.asList(initCustomProperty()); + when(resource.getProperties()).thenReturn(props); + + DetailedResourceVO vo = new DetailedResourceVO(); + convertor.convertTo(resource, vo); + + //test basic mapping + assertEquals(CMP_NAME, vo.getIdentity().getName()); + assertEquals(version.toString(), vo.getIdentity().getVersion()); + assertEquals(size, vo.getIdentity().getSize()); + assertEquals(categories, vo.getIdentity().getCategories()); + + //test detailed mapping + + //capabilities + assertEquals(1, vo.getCapabilities().size()); + GenericCapabilityVO cap = vo.getCapabilities().get(0); + testCapability(cap); + + //test child capability + assertEquals(1, cap.getCapabilities().size()); //has child capability + cap = cap.getCapabilities().get(0); + testCapability(cap); + + //test resource requirements + assertEquals(1, vo.getRequirements().size()); + testRequirement(vo.getRequirements().get(0)); + + //test resource properties + assertEquals(1, vo.getProperties().size()); + testProperty(vo.getProperties().get(0)); + } + + @Test + @Ignore("Not implemented yet.") + public void testConvertFrom() throws Exception { + + } + + /* + DATA INITS AND HELPERS + */ + + private void testCapability(GenericCapabilityVO cap) { + assertEquals(CUSTOM_ID, cap.getId()); + assertEquals(CUSTOM_CAPABILITY_NS, cap.getNamespace()); + + //capability attribute + assertEquals(1, cap.getAttributes().size()); + AttributeVO at = cap.getAttributes().get(0); + testAttribute(at); + + //capability property + assertEquals(1, cap.getProperties().size()); + PropertyVO prop = cap.getProperties().get(0); + testProperty(prop); + + //property attribute + assertEquals(1, prop.getAttributes().size()); + at = prop.getAttributes().get(0); + testAttribute(at); + + //capability requirement + assertEquals(1, cap.getRequirements().size()); + GenericRequirementVO req = cap.getRequirements().get(0); + testRequirement(req); + } + + private void testRequirement(GenericRequirementVO req) { + assertEquals(CUSTOM_ID, req.getId()); + assertEquals(CUSTOM_REQUIREMENT_NS, req.getNamespace()); + assertEquals(1, req.getAttributes().size()); + testAttribute(req.getAttributes().get(0)); + } + + private void testAttribute(AttributeVO at) { + assertEquals(CUSTOM_ATTR_NAME, at.getName()); + assertEquals(CUSTOM_ATTR_VALUE, at.getValue()); + } + + private void testProperty(PropertyVO prop) { + assertEquals(CUSTOM_ID, prop.getId()); + assertEquals(CUSTOM_PROPERTY_NS, prop.getNamespace()); + } + + private void initIdentity(Resource resource) { + Capability c = Mockito.mock(Capability.class); + when(c.getNamespace()).thenReturn(NsCrceIdentity.NAMESPACE__CRCE_IDENTITY); + + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__NAME)).thenReturn(CMP_NAME); + + version = new Version(2,1,1); + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__VERSION)).thenReturn(version); + + size = 1024l; + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__SIZE)) .thenReturn(size); + + categories = new ArrayList<>(); + categories.add("osgi"); + categories.add("jar"); + categories.add("test"); + when(c.getAttributeValue(NsCrceIdentity.ATTRIBUTE__CATEGORIES)).thenReturn(categories); + + when(metadataService.getIdentity(resource)).thenReturn(c); + } + + private Capability initCustomCapabilityTree(Resource resource, Capability root) { + Capability c = Mockito.mock(Capability.class); + when(c.getId()).thenReturn(CUSTOM_ID); + when(c.getNamespace()).thenReturn(CUSTOM_CAPABILITY_NS); + + List list = Arrays.asList(initCustomAttribute()); + when(c.getAttributes()).thenReturn(list); + list = Arrays.asList(initCustomProperty()); + when(c.getProperties()).thenReturn(list); + list = Arrays.asList(initCustomRequirement(resource)); + when(c.getRequirements()).thenReturn(list); + + if (root == null) { + list = Arrays.asList(initCustomCapabilityTree(resource, c)); + when(c.getChildren()).thenReturn(list); + } + + return c; + } + + private Property initCustomProperty() { + Property p = Mockito.mock(Property.class); + + when(p.getId()).thenReturn(CUSTOM_ID); + when(p.getNamespace()).thenReturn(CUSTOM_PROPERTY_NS); + + List list = Arrays.asList(initCustomAttribute()); + when(p.getAttributes()).thenReturn(list); + + return p; + } + + private Attribute initCustomAttribute() { + Attribute a = Mockito.mock(Attribute.class); + when(a.getName()).thenReturn(CUSTOM_ATTR_NAME); + when(a.getValue()).thenReturn(CUSTOM_ATTR_VALUE); + + return a; + } + + private Requirement initCustomRequirement(Resource resource) { + Requirement r = Mockito.mock(Requirement.class); + when(r.getNamespace()).thenReturn(CUSTOM_REQUIREMENT_NS); + when(r.getId()).thenReturn(CUSTOM_ID); + + List list = Arrays.asList(initCustomAttribute()); + when(r.getAttributes()).thenReturn(list); + + if(resource != null) { + when(resource.getRequirements()).thenReturn(Collections.singletonList(r)); + } + + return r; + } } \ No newline at end of file diff --git a/modules/crce-webservices-indexer/osgi.bnd b/modules/crce-webservices-indexer/osgi.bnd index 9def42ab..7e344e19 100644 --- a/modules/crce-webservices-indexer/osgi.bnd +++ b/modules/crce-webservices-indexer/osgi.bnd @@ -1,9 +1,9 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Private-Package: ${bundle.namespace}.internal, ${bundle.namespace}.structures.* - +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Private-Package: ${bundle.namespace}.internal, ${bundle.namespace}.structures.* + Export-Package: ${bundle.namespace} \ No newline at end of file diff --git a/modules/crce-webservices-indexer/pom.xml b/modules/crce-webservices-indexer/pom.xml index 0f2ae495..eeb73bf6 100644 --- a/modules/crce-webservices-indexer/pom.xml +++ b/modules/crce-webservices-indexer/pom.xml @@ -1,50 +1,50 @@ - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-webservices-indexer - bundle - - CRCE - Webservices Indexer - - - UTF-8 - ${namespace}.webservices.indexer - ${namespace}.webservices.indexer - true - - - - - junit - junit - test - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.apache.felix - org.apache.felix.bundlerepository - - - ${project.groupId} - crce-core - pom - - - ${project.groupId} - crce-concurrency - 2.1.0-SNAPSHOT - jar - - - + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-webservices-indexer + bundle + + CRCE - Webservices Indexer + + + UTF-8 + ${namespace}.webservices.indexer + ${namespace}.webservices.indexer + true + + + + + junit + junit + test + + + org.apache.felix + org.apache.felix.dependencymanager + + + org.apache.felix + org.apache.felix.bundlerepository + + + ${project.groupId} + crce-core + pom + + + ${project.groupId} + crce-concurrency + 2.1.0-SNAPSHOT + jar + + + diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/Activator.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/Activator.java index d99611c2..ceda2948 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/Activator.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/Activator.java @@ -1,56 +1,56 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; - -import org.osgi.framework.BundleContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.plugin.PluginManager; - -/** - * Activator of this bundle. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class Activator extends DependencyActivatorBase { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - /** - * This function is being called upon initialization of this bundle. - * - * @param context - * @param manager - * @throws Exception - */ - @Override - public void init(BundleContext context, final DependencyManager manager) throws Exception { - logger.debug("Initializing Webservices Indexer module."); - - // Plugin interface is implemented only in order for this indexer to appear in a chain of used indexers. - manager.add(createComponent() - .setInterface(Plugin.class.getName(), null) - .setImplementation(WebserviceDescriptionResourceIndexer.class) - .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) - .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) - .add(createServiceDependency().setRequired(true).setService(PluginManager.class))); - } - - /** - * This function is being called upon destruction of this bundle. - * - * @param context - * @param manager - * @throws Exception - */ - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - logger.debug("Destroying Webservices Indexer module."); - } -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; + +import org.osgi.framework.BundleContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.plugin.PluginManager; + +/** + * Activator of this bundle. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class Activator extends DependencyActivatorBase { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + /** + * This function is being called upon initialization of this bundle. + * + * @param context + * @param manager + * @throws Exception + */ + @Override + public void init(BundleContext context, final DependencyManager manager) throws Exception { + logger.debug("Initializing Webservices Indexer module."); + + // Plugin interface is implemented only in order for this indexer to appear in a chain of used indexers. + manager.add(createComponent() + .setInterface(Plugin.class.getName(), null) + .setImplementation(WebserviceDescriptionResourceIndexer.class) + .add(createServiceDependency().setRequired(true).setService(MetadataFactory.class)) + .add(createServiceDependency().setRequired(true).setService(MetadataService.class)) + .add(createServiceDependency().setRequired(true).setService(PluginManager.class))); + } + + /** + * This function is being called upon destruction of this bundle. + * + * @param context + * @param manager + * @throws Exception + */ + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + logger.debug("Destroying Webservices Indexer module."); + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceDescriptionResourceIndexer.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceDescriptionResourceIndexer.java index f8c3472a..894efc8c 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceDescriptionResourceIndexer.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceDescriptionResourceIndexer.java @@ -1,136 +1,136 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Scanner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is able to parse content of IDL document (originally stored at remote location) and store information about webservice descriptions found in IDL - * right into metadata of CRCE {@link cz.zcu.kiv.crce.metadata.Resource}. It is a part of standard indexers chain. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceDescriptionResourceIndexer extends AbstractResourceIndexer{ - - private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); - - // injected by dependency manager - private volatile MetadataFactory metadataFactory; - private volatile MetadataService metadataService; - - List definedWebserviceTypes; - - public final static String MAIN_CATEGORY = "ws-schema"; - - /** - * Constructor - * - */ - public WebserviceDescriptionResourceIndexer() { - // any new type of specialized IDL handling class that extends WebserviceType should be added here just once and nowhere else - definedWebserviceTypes = new ArrayList<>(); - definedWebserviceTypes.add(WebserviceTypeJsonWsp.class); - definedWebserviceTypes.add(WebserviceTypeWsdl.class); - definedWebserviceTypes.add(WebserviceTypeWadl.class); - } - - @Override - public List index(InputStream input, Resource resource) { - - ////////////////////////////////////// - // read the IDL content to a string // - ////////////////////////////////////// - Scanner s = new Scanner(input); - String idl = s.useDelimiter("\\Z").next(); // read entire file - - //////////////////////// - // recognize IDL type // - //////////////////////// - logger.debug("Attempting to recognize IDL type."); - - // create specialized IDL handling classes for all web service types - List webserviceTypes = getWebserviceTypes(); - - // recognize IDL type - WebserviceType recognizedWebserviceType = null; - for (WebserviceType webserviceType : webserviceTypes) { - if (webserviceType.recognizeIDL(idl)) { - logger.debug("IDL type recognized as {}.", webserviceType.getSpecificIdlCategory()); - recognizedWebserviceType = webserviceType; - break; // end the search, we have found out what type of IDL are we dealing with - } - } - if (recognizedWebserviceType == null) { - logger.error("IDL type unrecognizable."); - return Collections.emptyList(); - } - - ////////////////////////////////////// - // parse IDL according to it's type // - ////////////////////////////////////// - logger.debug("Attempting to parse IDL (recognized as {} type).", recognizedWebserviceType.getSpecificIdlCategory()); - int parsed_ws = recognizedWebserviceType.parseIDL(idl, resource); // parse IDL according to it's type - logger.debug("IDL parsed ({} webservice descriptions found).", parsed_ws); - - // uncomment this in order to test generation of IDL right after parsing. To see if inverseT(T(x)) = x (i.e. generation of parsed IDL results into IDL) - // is the easiest way to test if you wrote your IDL parsing class correctly. Just make sure that both methods are implemented. - //logger.debug(" * * * * * * * * * GENERATED IDL * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); - //logger.debug(recognizedWebserviceType.generateIDL(resource)); - //logger.debug(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); - - // label the resource with categories and other common attributes - metadataService.addCategory(resource, MAIN_CATEGORY); // assign main category tag - metadataService.addCategory(resource, recognizedWebserviceType.getSpecificIdlCategory()); // add specific category for this type of web service - Capability capability = resource.getCapabilities(WebserviceTypeBase.NAMESPACE__WEBSERVICESCHEMA_IDENTITY).get(0); // get webserviceschema.identity capability - capability.setAttribute(WebserviceTypeBase.ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__TIMESTAMP, new Date().getTime()); // save timestamp of when the websevice was parsed - - //////////////////////////////////////////////////////////// - // all done; return parsed IDL in form of a CRCE Resource // - //////////////////////////////////////////////////////////// - logger.debug("IDL successfully parsed (recognized as {} type).", recognizedWebserviceType.getSpecificIdlCategory()); - - return Collections.singletonList(MAIN_CATEGORY); - } - - @Override - public List getProvidedCategories() { - List categories = new ArrayList<>(); - categories.add(MAIN_CATEGORY); - List webserviceTypes = getWebserviceTypes(); - for (WebserviceType webserviceType : webserviceTypes) { - categories.add(webserviceType.getSpecificIdlCategory()); - } - return categories; - } - - /** - * This function reads the list of class references, creates instances of them and return those instances in another list. - * - */ - private List getWebserviceTypes() { - List webserviceTypes = new ArrayList<>(); - for (Class definedWebserviceType : definedWebserviceTypes) { - WebserviceTypeBase wtb = null; - try { - wtb = (WebserviceTypeBase)definedWebserviceType.getDeclaredConstructor(MetadataFactory.class, MetadataService.class).newInstance(metadataFactory, metadataService); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { - logger.debug("Error while initializing WebserviceType instance.", ex); - } - if (wtb instanceof WebserviceType) { - webserviceTypes.add((WebserviceType)wtb); - } - } - return webserviceTypes; - } -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.indexer.AbstractResourceIndexer; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Scanner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is able to parse content of IDL document (originally stored at remote location) and store information about webservice descriptions found in IDL + * right into metadata of CRCE {@link cz.zcu.kiv.crce.metadata.Resource}. It is a part of standard indexers chain. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceDescriptionResourceIndexer extends AbstractResourceIndexer{ + + private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); + + // injected by dependency manager + private volatile MetadataFactory metadataFactory; + private volatile MetadataService metadataService; + + List definedWebserviceTypes; + + public final static String MAIN_CATEGORY = "ws-schema"; + + /** + * Constructor + * + */ + public WebserviceDescriptionResourceIndexer() { + // any new type of specialized IDL handling class that extends WebserviceType should be added here just once and nowhere else + definedWebserviceTypes = new ArrayList<>(); + definedWebserviceTypes.add(WebserviceTypeJsonWsp.class); + definedWebserviceTypes.add(WebserviceTypeWsdl.class); + definedWebserviceTypes.add(WebserviceTypeWadl.class); + } + + @Override + public List index(InputStream input, Resource resource) { + + ////////////////////////////////////// + // read the IDL content to a string // + ////////////////////////////////////// + Scanner s = new Scanner(input); + String idl = s.useDelimiter("\\Z").next(); // read entire file + + //////////////////////// + // recognize IDL type // + //////////////////////// + logger.debug("Attempting to recognize IDL type."); + + // create specialized IDL handling classes for all web service types + List webserviceTypes = getWebserviceTypes(); + + // recognize IDL type + WebserviceType recognizedWebserviceType = null; + for (WebserviceType webserviceType : webserviceTypes) { + if (webserviceType.recognizeIDL(idl)) { + logger.debug("IDL type recognized as {}.", webserviceType.getSpecificIdlCategory()); + recognizedWebserviceType = webserviceType; + break; // end the search, we have found out what type of IDL are we dealing with + } + } + if (recognizedWebserviceType == null) { + logger.error("IDL type unrecognizable."); + return Collections.emptyList(); + } + + ////////////////////////////////////// + // parse IDL according to it's type // + ////////////////////////////////////// + logger.debug("Attempting to parse IDL (recognized as {} type).", recognizedWebserviceType.getSpecificIdlCategory()); + int parsed_ws = recognizedWebserviceType.parseIDL(idl, resource); // parse IDL according to it's type + logger.debug("IDL parsed ({} webservice descriptions found).", parsed_ws); + + // uncomment this in order to test generation of IDL right after parsing. To see if inverseT(T(x)) = x (i.e. generation of parsed IDL results into IDL) + // is the easiest way to test if you wrote your IDL parsing class correctly. Just make sure that both methods are implemented. + //logger.debug(" * * * * * * * * * GENERATED IDL * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); + //logger.debug(recognizedWebserviceType.generateIDL(resource)); + //logger.debug(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); + + // label the resource with categories and other common attributes + metadataService.addCategory(resource, MAIN_CATEGORY); // assign main category tag + metadataService.addCategory(resource, recognizedWebserviceType.getSpecificIdlCategory()); // add specific category for this type of web service + Capability capability = resource.getCapabilities(WebserviceTypeBase.NAMESPACE__WEBSERVICESCHEMA_IDENTITY).get(0); // get webserviceschema.identity capability + capability.setAttribute(WebserviceTypeBase.ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__TIMESTAMP, new Date().getTime()); // save timestamp of when the websevice was parsed + + //////////////////////////////////////////////////////////// + // all done; return parsed IDL in form of a CRCE Resource // + //////////////////////////////////////////////////////////// + logger.debug("IDL successfully parsed (recognized as {} type).", recognizedWebserviceType.getSpecificIdlCategory()); + + return Collections.singletonList(MAIN_CATEGORY); + } + + @Override + public List getProvidedCategories() { + List categories = new ArrayList<>(); + categories.add(MAIN_CATEGORY); + List webserviceTypes = getWebserviceTypes(); + for (WebserviceType webserviceType : webserviceTypes) { + categories.add(webserviceType.getSpecificIdlCategory()); + } + return categories; + } + + /** + * This function reads the list of class references, creates instances of them and return those instances in another list. + * + */ + private List getWebserviceTypes() { + List webserviceTypes = new ArrayList<>(); + for (Class definedWebserviceType : definedWebserviceTypes) { + WebserviceTypeBase wtb = null; + try { + wtb = (WebserviceTypeBase)definedWebserviceType.getDeclaredConstructor(MetadataFactory.class, MetadataService.class).newInstance(metadataFactory, metadataService); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { + logger.debug("Error while initializing WebserviceType instance.", ex); + } + if (wtb instanceof WebserviceType) { + webserviceTypes.add((WebserviceType)wtb); + } + } + return webserviceTypes; + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceType.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceType.java index 5e77225c..e8600814 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceType.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceType.java @@ -1,53 +1,53 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import cz.zcu.kiv.crce.metadata.Resource; - -/** - * This interface serves as a basic API for processing of IDLs of different types of web services. Any class implementing this interface should represent one - * particular type of web service standard (e.g. SOAP, JSON-WSP, etc...). - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public interface WebserviceType { - - /** - * Determines whether given IDL satisfies all conditions in order to be valid representation of a web service. For example if SOAP was implemented as web - * service type of this interface. This method would check whether given IDL is a valid WSDL document. - * - * @param idl Textual representation of webservice IDL. - * @return Returns true if given IDL was recognized as the type of implemented web service standard. Returns false otherwise. - */ - boolean recognizeIDL(String idl); - - /** - * Processes given IDL into CRCE {@link cz.zcu.kiv.crce.metadata.Resource} representation of a webservices capabilities represented by the given - * IDL. - * - * @param idl Textual representation of webservice IDL. - * @param resource CRCE {@link cz.zcu.kiv.crce.metadata.Resource} to which the meta-data will be stored to. - * @return Returns number of successfully parsed representations of webservice descriptions in given IDL. In case of any error -1 is returned instead. - */ - int parseIDL(String idl, Resource resource); - - /** - * Generates IDL from CRCE {@link cz.zcu.kiv.crce.metadata.Resource} representation of a webservices capabilities. - * - *

Please note, that due to the webservice descriptions being stored at CRCE repository in a unified way, some information that is specific for a - * particular webservice schema might not be (and often is not) stored at the moment. As a result webservice schema document that is being generated by this - * method often does not result in a valid document according to the corresponding webservice schema specification. All the information in a generated - * document are correctly formatted according to relevant webservice schema specs., but that does not ensure it's validity (e.g. document might contain - * references to missing parts). - * - * @param resource CRCE {@link cz.zcu.kiv.crce.metadata.Resource} from which the meta-data will be read. - * @return Textual representation of webservice IDL. - */ - String generateIDL(Resource resource); - - /** - * Returns name of specific IDL of which class that implements this interface deals with. E.g. "json-wsp", "soap", "wadl", etc... - * - * @return Name of specific IDL of which class that implements this interface deals with. - */ - String getSpecificIdlCategory(); - -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import cz.zcu.kiv.crce.metadata.Resource; + +/** + * This interface serves as a basic API for processing of IDLs of different types of web services. Any class implementing this interface should represent one + * particular type of web service standard (e.g. SOAP, JSON-WSP, etc...). + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public interface WebserviceType { + + /** + * Determines whether given IDL satisfies all conditions in order to be valid representation of a web service. For example if SOAP was implemented as web + * service type of this interface. This method would check whether given IDL is a valid WSDL document. + * + * @param idl Textual representation of webservice IDL. + * @return Returns true if given IDL was recognized as the type of implemented web service standard. Returns false otherwise. + */ + boolean recognizeIDL(String idl); + + /** + * Processes given IDL into CRCE {@link cz.zcu.kiv.crce.metadata.Resource} representation of a webservices capabilities represented by the given + * IDL. + * + * @param idl Textual representation of webservice IDL. + * @param resource CRCE {@link cz.zcu.kiv.crce.metadata.Resource} to which the meta-data will be stored to. + * @return Returns number of successfully parsed representations of webservice descriptions in given IDL. In case of any error -1 is returned instead. + */ + int parseIDL(String idl, Resource resource); + + /** + * Generates IDL from CRCE {@link cz.zcu.kiv.crce.metadata.Resource} representation of a webservices capabilities. + * + *

Please note, that due to the webservice descriptions being stored at CRCE repository in a unified way, some information that is specific for a + * particular webservice schema might not be (and often is not) stored at the moment. As a result webservice schema document that is being generated by this + * method often does not result in a valid document according to the corresponding webservice schema specification. All the information in a generated + * document are correctly formatted according to relevant webservice schema specs., but that does not ensure it's validity (e.g. document might contain + * references to missing parts). + * + * @param resource CRCE {@link cz.zcu.kiv.crce.metadata.Resource} from which the meta-data will be read. + * @return Textual representation of webservice IDL. + */ + String generateIDL(Resource resource); + + /** + * Returns name of specific IDL of which class that implements this interface deals with. E.g. "json-wsp", "soap", "wadl", etc... + * + * @return Name of specific IDL of which class that implements this interface deals with. + */ + String getSpecificIdlCategory(); + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeBase.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeBase.java index 65a334aa..cfea9d57 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeBase.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeBase.java @@ -1,157 +1,157 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import cz.zcu.kiv.crce.metadata.AttributeType; -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; -import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -/** - * This class can be extended by any class implementing {@link cz.zcu.kiv.crce.webservices.indexer.internal.WebserviceType} interface. Since - * {@link cz.zcu.kiv.crce.webservices.indexer.internal.WebserviceType} interface defines strictly only necessary functionality towards external usage this class - * defines convenient common functionality that is often internally needed when implementing class for parsing of specific webservice IDL type. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public abstract class WebserviceTypeBase { - - // in order to work with metadata these services are needed - protected MetadataFactory metadataFactory; - protected MetadataService metadataService; - - //////////////// - // NAMESPACES // - //////////////// - - // list of all namespaces used by this module for Capabilities - public static final String NAMESPACE__CRCE_IDENTITY = NsCrceIdentity.NAMESPACE__CRCE_IDENTITY; - public static final String NAMESPACE__WEBSERVICESCHEMA_IDENTITY = WebserviceDescriptionResourceIndexer.MAIN_CATEGORY + ".identity"; - public static final String NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE = WebserviceDescriptionResourceIndexer.MAIN_CATEGORY + ".ws"; - public static final String NAMESPACE__WEBSERVICE_ENDPOINT = NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE + ".endpoint"; - public static final String NAMESPACE__WEBSERVICE_TYPE = NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE + ".type"; - - // list of all namespaces used by this module for Properties - public static final String NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER = NAMESPACE__WEBSERVICE_ENDPOINT + ".parameter"; - public static final String NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE = NAMESPACE__WEBSERVICE_ENDPOINT + ".response"; - - //////////////// - // ATTRIBUTES // - //////////////// - - // list of attributes used by this module for NAMESPACE__CRCE_IDENTITY Capability - public static final AttributeType ATTRIBUTE__CRCE_IDENTITY__MIME = new SimpleAttributeType<>("mime", String.class); - public static final AttributeType ATTRIBUTE__CRCE_IDENTITY__HASH = new SimpleAttributeType<>("hash", String.class); - - // list of attributes used by this module for NAMESPACE__WEBSERVICESCHEMA_IDENTITY Capability - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION = new SimpleAttributeType<>("idl-version", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__TIMESTAMP = new SimpleAttributeType<>("parsedAtTimestamp", Long.class); - - // list of attributes used by this module for NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE Capability - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME = new SimpleAttributeType<>("name", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE = new SimpleAttributeType<>("type", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI = new SimpleAttributeType<>("uri", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__IDL_URI = new SimpleAttributeType<>("idl-uri", String.class); - - // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT Capability - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME = new SimpleAttributeType<>("name", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT__URL = new SimpleAttributeType<>("url", String.class); - - // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER Property - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME = new SimpleAttributeType<>("name", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE = new SimpleAttributeType<>("type", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER = new SimpleAttributeType<>("order", Long.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL = new SimpleAttributeType<>("isOptional", Long.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY = new SimpleAttributeType<>("isArray", Long.class); - - // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE Property - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE = new SimpleAttributeType<>("type", String.class); - public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY = new SimpleAttributeType<>("isArray", Long.class); - - - - /** - * This constructor sets up references to all necessary services for metadata manipulation. - * - * @param mf - * @param ms - */ - public WebserviceTypeBase(MetadataFactory mf, MetadataService ms) { - metadataFactory = mf; - metadataService = ms; - } - - /** - * Returns specific communication pattern used by implemented webservice type. E.g. "rpc", "messaging" or "rest". - * - * @return Specific communication pattern used by implemented webservice type. - */ - public abstract String getSpecificWebserviceType(); - - /** - * This function simply takes input string and encode in into SHA-256 hash. - * - * @param idl Content of IDL document. - * @return SHA-256 encrypted hash. - */ - public static String getIdlHash(String idl) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] hash = digest.digest(idl.getBytes("UTF-8")); - StringBuilder hexString = new StringBuilder(); - - for (int i = 0; i < hash.length; i++) { - String hex = Integer.toHexString(0xff & hash[i]); - if (hex.length() == 1) { - hexString.append('0'); - } - hexString.append(hex); - } - - return hexString.toString(); - } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { - throw new RuntimeException(ex); - } - } - - /** - * This function sets attribute of {@link cz.zcu.kiv.crce.metadata.Capability} to a value provided that passed value - * is not null. - * - * @param Datatype of attribute-value pair. - * @param capability {@link cz.zcu.kiv.crce.metadata.Capability} for which attribute will be set. - * @param attribute attribute to set. - * @param value value to set. - * @return Returns true if value was set. Returns false otherwise. - */ - protected static boolean setIfSet(Capability capability, AttributeType attribute, T value) { - if (capability != null && value != null) { - capability.setAttribute(attribute, value); - return true; - } - return false; - } - - /** - * This function sets attribute of {@link cz.zcu.kiv.crce.metadata.Property} to a value provided that passed value - * is not null. - * - * @param Datatype of attribute-value pair. - * @param property {@link cz.zcu.kiv.crce.metadata.Property} for which attribute will be set. - * @param attribute attribute to set. - * @param value value to set. - * @return Returns true if value was set. Returns false otherwise. - */ - protected static boolean setIfSet(Property property, AttributeType attribute, T value) { - if (property != null && value != null) { - property.setAttribute(attribute, value); - return true; - } - return false; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import cz.zcu.kiv.crce.metadata.AttributeType; +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.impl.SimpleAttributeType; +import cz.zcu.kiv.crce.metadata.namespace.NsCrceIdentity; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * This class can be extended by any class implementing {@link cz.zcu.kiv.crce.webservices.indexer.internal.WebserviceType} interface. Since + * {@link cz.zcu.kiv.crce.webservices.indexer.internal.WebserviceType} interface defines strictly only necessary functionality towards external usage this class + * defines convenient common functionality that is often internally needed when implementing class for parsing of specific webservice IDL type. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public abstract class WebserviceTypeBase { + + // in order to work with metadata these services are needed + protected MetadataFactory metadataFactory; + protected MetadataService metadataService; + + //////////////// + // NAMESPACES // + //////////////// + + // list of all namespaces used by this module for Capabilities + public static final String NAMESPACE__CRCE_IDENTITY = NsCrceIdentity.NAMESPACE__CRCE_IDENTITY; + public static final String NAMESPACE__WEBSERVICESCHEMA_IDENTITY = WebserviceDescriptionResourceIndexer.MAIN_CATEGORY + ".identity"; + public static final String NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE = WebserviceDescriptionResourceIndexer.MAIN_CATEGORY + ".ws"; + public static final String NAMESPACE__WEBSERVICE_ENDPOINT = NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE + ".endpoint"; + public static final String NAMESPACE__WEBSERVICE_TYPE = NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE + ".type"; + + // list of all namespaces used by this module for Properties + public static final String NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER = NAMESPACE__WEBSERVICE_ENDPOINT + ".parameter"; + public static final String NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE = NAMESPACE__WEBSERVICE_ENDPOINT + ".response"; + + //////////////// + // ATTRIBUTES // + //////////////// + + // list of attributes used by this module for NAMESPACE__CRCE_IDENTITY Capability + public static final AttributeType ATTRIBUTE__CRCE_IDENTITY__MIME = new SimpleAttributeType<>("mime", String.class); + public static final AttributeType ATTRIBUTE__CRCE_IDENTITY__HASH = new SimpleAttributeType<>("hash", String.class); + + // list of attributes used by this module for NAMESPACE__WEBSERVICESCHEMA_IDENTITY Capability + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION = new SimpleAttributeType<>("idl-version", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__TIMESTAMP = new SimpleAttributeType<>("parsedAtTimestamp", Long.class); + + // list of attributes used by this module for NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE Capability + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME = new SimpleAttributeType<>("name", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE = new SimpleAttributeType<>("type", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI = new SimpleAttributeType<>("uri", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__IDL_URI = new SimpleAttributeType<>("idl-uri", String.class); + + // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT Capability + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME = new SimpleAttributeType<>("name", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT__URL = new SimpleAttributeType<>("url", String.class); + + // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER Property + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME = new SimpleAttributeType<>("name", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE = new SimpleAttributeType<>("type", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER = new SimpleAttributeType<>("order", Long.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL = new SimpleAttributeType<>("isOptional", Long.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY = new SimpleAttributeType<>("isArray", Long.class); + + // list of attributes used by this module for NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE Property + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE = new SimpleAttributeType<>("type", String.class); + public static final AttributeType ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY = new SimpleAttributeType<>("isArray", Long.class); + + + + /** + * This constructor sets up references to all necessary services for metadata manipulation. + * + * @param mf + * @param ms + */ + public WebserviceTypeBase(MetadataFactory mf, MetadataService ms) { + metadataFactory = mf; + metadataService = ms; + } + + /** + * Returns specific communication pattern used by implemented webservice type. E.g. "rpc", "messaging" or "rest". + * + * @return Specific communication pattern used by implemented webservice type. + */ + public abstract String getSpecificWebserviceType(); + + /** + * This function simply takes input string and encode in into SHA-256 hash. + * + * @param idl Content of IDL document. + * @return SHA-256 encrypted hash. + */ + public static String getIdlHash(String idl) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(idl.getBytes("UTF-8")); + StringBuilder hexString = new StringBuilder(); + + for (int i = 0; i < hash.length; i++) { + String hex = Integer.toHexString(0xff & hash[i]); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + + return hexString.toString(); + } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { + throw new RuntimeException(ex); + } + } + + /** + * This function sets attribute of {@link cz.zcu.kiv.crce.metadata.Capability} to a value provided that passed value + * is not null. + * + * @param Datatype of attribute-value pair. + * @param capability {@link cz.zcu.kiv.crce.metadata.Capability} for which attribute will be set. + * @param attribute attribute to set. + * @param value value to set. + * @return Returns true if value was set. Returns false otherwise. + */ + protected static boolean setIfSet(Capability capability, AttributeType attribute, T value) { + if (capability != null && value != null) { + capability.setAttribute(attribute, value); + return true; + } + return false; + } + + /** + * This function sets attribute of {@link cz.zcu.kiv.crce.metadata.Property} to a value provided that passed value + * is not null. + * + * @param Datatype of attribute-value pair. + * @param property {@link cz.zcu.kiv.crce.metadata.Property} for which attribute will be set. + * @param attribute attribute to set. + * @param value value to set. + * @return Returns true if value was set. Returns false otherwise. + */ + protected static boolean setIfSet(Property property, AttributeType attribute, T value) { + if (property != null && value != null) { + property.setAttribute(attribute, value); + return true; + } + return false; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeJsonWsp.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeJsonWsp.java index af0b0114..21e90044 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeJsonWsp.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeJsonWsp.java @@ -1,396 +1,396 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointResponse; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - *

This class can recognize and parse remote IDL documents representing JSON-WSP description objects - * (see https://en.wikipedia.org/wiki/JSON-WSP#Description_object). - * - *

Parsed JSON-WSP description object describing webservice is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a - * {@link cz.zcu.kiv.crce.metadata.Resource}. - * - *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly - * mentioned here is not being processed by this class. - * - *

IDL aspects parsed by this class: - *

    - *
  • MIME format (json-wsp/description)
  • - *
  • IDL version
  • - *
  • webservice name
  • - *
  • webservice url
  • - *
  • webservice endpoints:
  • - *
      - *
    • endpoint name
    • - *
    • parameters (for each parameter it's name, type, order, whether it's array and whether it's optional is being processed)
    • - *
    • type of returned response
    • - *
    - *
- * - *

Defined non-primitive types are NOT PROCESSED by this class at the moment. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeJsonWsp extends WebserviceTypeBase implements WebserviceType { - - private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); - - private final static String JSON_WSP_TYPE = "type"; - private final static String JSON_WSP_TYPE_VALUE = "jsonwsp/description"; - - private final static String JSON_WSP_VERSION = "version"; - private final static String JSON_WSP_SERVICENAME = "servicename"; - private final static String JSON_WSP_URL = "url"; - private final static String JSON_WSP_TYPES = "types"; - private final static String JSON_WSP_METHODS = "methods"; - private final static String JSON_WSP_METHOD_PARAMETERS = "params"; - private final static String JSON_WSP_METHOD_PARAMETER_TYPE = "type"; - private final static String JSON_WSP_METHOD_PARAMETER_ORDER = "def_order"; - private final static String JSON_WSP_METHOD_PARAMETER_OPTIONAL = "optional"; - private final static String JSON_WSP_METHOD_RESPONSE = "ret_info"; - private final static String JSON_WSP_METHOD_RESPONSE_TYPE = "type"; - - /** - * Constructor - * - * @param mf - * @param ms - */ - public WebserviceTypeJsonWsp(MetadataFactory mf, MetadataService ms) { - super(mf, ms); - } - - @Override - public String getSpecificIdlCategory() { - return "json-wsp"; - } - - @Override - public String getSpecificWebserviceType() { - return "rpc"; - } - - @Override - public boolean recognizeIDL(String idl) { - - // check whether IDL is a valid JSON object - JSONObject jsonObj = null; - try { - jsonObj = new JSONObject(idl); - } catch (JSONException ex) { - logger.debug("IDL is not a valid JSON object", ex); - } - if (jsonObj == null) { - return false; - } - - // check whether "type" key is defined and has a proper value of "jsonwsp/description" - try { - if (!(jsonObj.getString(JSON_WSP_TYPE).compareTo(JSON_WSP_TYPE_VALUE) == 0)) { - logger.debug("IDL's \"{}\" key does not have proper value of \"{}\".", JSON_WSP_TYPE, JSON_WSP_TYPE_VALUE); - return false; - } - } catch (JSONException ex) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPE, ex); - return false; - } - - //check for other required root elements of JSON-WSP description object - if (!jsonObj.has(JSON_WSP_VERSION)) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_VERSION); - return false; - } - if (!jsonObj.has(JSON_WSP_SERVICENAME)) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_SERVICENAME); - return false; - } - if (!jsonObj.has(JSON_WSP_URL)) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_URL); - return false; - } - if (!jsonObj.has(JSON_WSP_TYPES)) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPES); - return false; - } - if (!jsonObj.has(JSON_WSP_METHODS)) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_METHODS); - return false; - } - - // check whether there is at least one method defined - try { - if (jsonObj.getJSONObject(JSON_WSP_METHODS).length() == 0) { - logger.debug("IDL's \"{}\" key does not have at least one member (i.e. method).", JSON_WSP_METHODS); - } - } catch (JSONException ex) { - logger.debug("IDL does not have \"{}\" key defined in root JSON structure or \"{}\" key is not a valid JSON object.", JSON_WSP_METHODS, JSON_WSP_METHODS, ex); - } - - // at this point we can safely declare that we have detected JSON-WSP description object - return true; - } - - @Override - public int parseIDL(String idl, Resource resource) { - - //////////////////////////////////////////// - // process idl and get all necessary info // - //////////////////////////////////////////// - - // process idl into jsonObject - JSONObject jsonObj = null; - try { - jsonObj = new JSONObject(idl); - } catch (JSONException ex) { - logger.error("IDL is not a valid JSON object", ex); - } - if (jsonObj == null) { - return -1; - } - - // get webservice name - String webserviceName = null; - try { - webserviceName = jsonObj.getString(JSON_WSP_SERVICENAME); - } catch (JSONException ex) { - logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_SERVICENAME, ex); - } - - // get webservice url - String webserviceUrl = null; - try { - webserviceUrl = jsonObj.getString(JSON_WSP_URL); - } catch (JSONException ex) { - logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_URL, ex); - } - - // get webservice mime format - String webserviceMime = null; - try { - webserviceMime = jsonObj.getString(JSON_WSP_TYPE); - } catch (JSONException ex) { - logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPE, ex); - } - - // get webservice idl version - String webserviceIdlVersion = null; - try { - webserviceIdlVersion = jsonObj.getString(JSON_WSP_VERSION); - } catch (JSONException ex) { - logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_VERSION, ex); - } - - // process idl endpoints (i.e. methods) - List processedEndpoints = new ArrayList<>(); - if (jsonObj.has(JSON_WSP_METHODS)) { - try { - JSONObject jsonEndpoints = jsonObj.getJSONObject(JSON_WSP_METHODS); - Iterator enpoints = jsonEndpoints.keys(); - - // iterate through all endpoints (i.e. methods) - while (enpoints.hasNext()) { - String endpointName = (String)enpoints.next(); // get endpoint name - JSONObject jsonEndpoint = jsonEndpoints.getJSONObject(endpointName); - - // get endpoint parameters - JSONObject jsonParams = jsonEndpoint.getJSONObject(JSON_WSP_METHOD_PARAMETERS); - Iterator params = jsonParams.keys(); - - // iterate through all parameters of current endpoint - List processedParams = new ArrayList<>(); - while(params.hasNext()) { - try { - // get info about parameter - String paramName = (String)params.next(); - JSONObject jsonParam = jsonParams.getJSONObject(paramName); - String paramType; - boolean paramArray; - if (jsonParam.optJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE) == null){ - paramType = jsonParam.getString(JSON_WSP_METHOD_PARAMETER_TYPE); - paramArray = false; - } else { - JSONArray jsonArray = jsonParam.getJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE); - paramType = jsonArray.getString(0); - paramArray = true; - } - long paramOrder = jsonParam.getLong(JSON_WSP_METHOD_PARAMETER_ORDER); - boolean paramOptional = jsonParam.getBoolean(JSON_WSP_METHOD_PARAMETER_OPTIONAL); - - // save parameter info into list - processedParams.add(new WebserviceEndpointParameter(paramName, paramType, paramOrder, paramOptional, paramArray)); - } catch (JSONException ex) { - logger.warn("Error while processing parameters of endpoint \"{}\".", endpointName, ex); - } - } - - // get endpoint response - JSONObject jsonEndpointResponse = jsonEndpoint.getJSONObject(JSON_WSP_METHOD_RESPONSE); - String responseType; - boolean responseArray; - if (jsonEndpointResponse.optJSONArray(JSON_WSP_METHOD_RESPONSE_TYPE) == null){ - responseType = jsonEndpointResponse.getString(JSON_WSP_METHOD_PARAMETER_TYPE); - responseArray = false; - } else { - JSONArray jsonArray = jsonEndpointResponse.getJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE); - responseType = jsonArray.getString(0); - responseArray = true; - } - WebserviceEndpointResponse processedResponse = new WebserviceEndpointResponse(responseType, responseArray); - - // add endpoint info into list - processedEndpoints.add(new WebserviceEndpoint(endpointName, null, processedParams, processedResponse)); - - } - } catch (JSONException ex) { - logger.warn("Error while processing endpoints.", ex); - } - } - else { - logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_METHODS); - } - - - - //////////////////////////////////////////////////////////////////////////// - // create CRCE metadata structures and fill it by retrieved info from idl // - //////////////////////////////////////////////////////////////////////////// - - // create new variables for holding references to current capabilities - Capability capability, endpoint_capability; - - // Capability - CRCE Identity - capability = metadataService.getIdentity(resource); - metadataService.setPresentationName(resource, webserviceName); - metadataService.setSize(resource, idl.length()); - capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__MIME, webserviceMime); - capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); - - // Capability - Webserviceschema Identity - capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION, webserviceIdlVersion); - resource.addCapability(capability); - resource.addRootCapability(capability); - - // Capability - Webserviceschema Webservice - capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, webserviceName); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, getSpecificWebserviceType()); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI, webserviceUrl); - resource.addCapability(capability); - resource.addRootCapability(capability); - - // Capabilities - Webservice Endpoint - for (int i = 0; i < processedEndpoints.size(); i++) { - endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); - endpoint_capability.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); - - // Properties - Webservice Enpoint Parameter - List processedParams = processedEndpoints.get(i).getParameters(); - for (int j = 0; j < processedParams.size(); j++) { - Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER, processedParams.get(j).getOrder()); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL, (long)(processedParams.get(j).isOptional() ? 1 : 0)); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY, (long)(processedParams.get(j).isArray() ? 1 : 0)); - endpoint_capability.addProperty(property); - } - - // Property - Webservice Endpoint Response - Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE, processedEndpoints.get(i).getResponse().getType()); - property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY, (long)(processedEndpoints.get(i).getResponse().isArray() ? 1 : 0)); - endpoint_capability.addProperty(property); - - resource.addCapability(endpoint_capability); - capability.addChild(endpoint_capability); - } - - // return "1" as a number of parsed WSs, since JSON-WSP description document can describe exactly one webservice at once - return 1; - } - - @Override - public String generateIDL(Resource resource) { - final String INDENT = " "; - StringBuilder sb = new StringBuilder(); - - // get all neccesary info from resource and it's capabilities - Capability capability = metadataService.getIdentity(resource); - String mime = capability.getAttributeStringValue(ATTRIBUTE__CRCE_IDENTITY__MIME); - capability = resource.getRootCapabilities(NAMESPACE__WEBSERVICESCHEMA_IDENTITY).get(0); - String idlVersion = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION); - capability = resource.getRootCapabilities(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE).get(0); - String webserviceName = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME); - String webserviceUrl = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI); - List endpoints = capability.getChildren(); - - // construct IDL from retrieved info according to the JSON-WSP description object specification - sb.append("{\n"); - sb.append(INDENT).append("\"type\": \"").append(mime).append("\",\n"); - sb.append(INDENT).append("\"version\": \"").append(idlVersion).append("\",\n"); - sb.append(INDENT).append("\"servicename\": \"").append(webserviceName).append("\",\n"); - sb.append(INDENT).append("\"url\": \"").append(webserviceUrl).append("\",\n"); - sb.append(INDENT).append("\"types\": {},\n"); // complex types are not currently being stored in CRCE - sb.append(INDENT).append("\"methods\": {\n"); - for (int i = 0; i < endpoints.size(); i++) { // endpoints - sb.append(INDENT).append(INDENT).append("\"").append(endpoints.get(i).getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME)).append("\": {\n"); - List params = endpoints.get(i).getProperties(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); - sb.append(INDENT).append(INDENT).append(INDENT).append("\"params\": {\n"); - for (int j = 0; j < params.size(); j++) { // params - Property param = params.get(j); - String paramType = param.getAttributeStringValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE); - if (param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY) == 1) { - paramType = "[" + paramType + "]"; - } - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"").append(param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME)).append("\": {\n"); - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"def_order\": ").append(param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER)).append(",\n"); - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"type\": \"").append(paramType).append("\",\n"); - if (param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL) == 1) { - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"optional\": true\n"); - } else { - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"optional\": false\n"); - } - if (params.size() != j + 1) { - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("},\n"); - } else { - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("}\n"); - } - } - Property response = endpoints.get(i).getProperties(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE).get(0); - String responseType = response.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE); - if (response.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY) == 1) { - responseType = "[" + responseType + "]"; - } - sb.append(INDENT).append(INDENT).append(INDENT).append("},\n"); - sb.append(INDENT).append(INDENT).append(INDENT).append("\"ret_info\": {\n"); - sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"type\": \"").append(responseType).append("\"\n"); - sb.append(INDENT).append(INDENT).append(INDENT).append("}\n"); - if (endpoints.size() != i + 1) { - sb.append(INDENT).append(INDENT).append("},\n"); - } else { - sb.append(INDENT).append(INDENT).append("}\n"); - } - } - sb.append(INDENT).append("}\n"); - sb.append("}\n"); - - // return generated IDL - return sb.toString(); - } - -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointResponse; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *

This class can recognize and parse remote IDL documents representing JSON-WSP description objects + * (see https://en.wikipedia.org/wiki/JSON-WSP#Description_object). + * + *

Parsed JSON-WSP description object describing webservice is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a + * {@link cz.zcu.kiv.crce.metadata.Resource}. + * + *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly + * mentioned here is not being processed by this class. + * + *

IDL aspects parsed by this class: + *

    + *
  • MIME format (json-wsp/description)
  • + *
  • IDL version
  • + *
  • webservice name
  • + *
  • webservice url
  • + *
  • webservice endpoints:
  • + *
      + *
    • endpoint name
    • + *
    • parameters (for each parameter it's name, type, order, whether it's array and whether it's optional is being processed)
    • + *
    • type of returned response
    • + *
    + *
+ * + *

Defined non-primitive types are NOT PROCESSED by this class at the moment. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeJsonWsp extends WebserviceTypeBase implements WebserviceType { + + private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); + + private final static String JSON_WSP_TYPE = "type"; + private final static String JSON_WSP_TYPE_VALUE = "jsonwsp/description"; + + private final static String JSON_WSP_VERSION = "version"; + private final static String JSON_WSP_SERVICENAME = "servicename"; + private final static String JSON_WSP_URL = "url"; + private final static String JSON_WSP_TYPES = "types"; + private final static String JSON_WSP_METHODS = "methods"; + private final static String JSON_WSP_METHOD_PARAMETERS = "params"; + private final static String JSON_WSP_METHOD_PARAMETER_TYPE = "type"; + private final static String JSON_WSP_METHOD_PARAMETER_ORDER = "def_order"; + private final static String JSON_WSP_METHOD_PARAMETER_OPTIONAL = "optional"; + private final static String JSON_WSP_METHOD_RESPONSE = "ret_info"; + private final static String JSON_WSP_METHOD_RESPONSE_TYPE = "type"; + + /** + * Constructor + * + * @param mf + * @param ms + */ + public WebserviceTypeJsonWsp(MetadataFactory mf, MetadataService ms) { + super(mf, ms); + } + + @Override + public String getSpecificIdlCategory() { + return "json-wsp"; + } + + @Override + public String getSpecificWebserviceType() { + return "rpc"; + } + + @Override + public boolean recognizeIDL(String idl) { + + // check whether IDL is a valid JSON object + JSONObject jsonObj = null; + try { + jsonObj = new JSONObject(idl); + } catch (JSONException ex) { + logger.debug("IDL is not a valid JSON object", ex); + } + if (jsonObj == null) { + return false; + } + + // check whether "type" key is defined and has a proper value of "jsonwsp/description" + try { + if (!(jsonObj.getString(JSON_WSP_TYPE).compareTo(JSON_WSP_TYPE_VALUE) == 0)) { + logger.debug("IDL's \"{}\" key does not have proper value of \"{}\".", JSON_WSP_TYPE, JSON_WSP_TYPE_VALUE); + return false; + } + } catch (JSONException ex) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPE, ex); + return false; + } + + //check for other required root elements of JSON-WSP description object + if (!jsonObj.has(JSON_WSP_VERSION)) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_VERSION); + return false; + } + if (!jsonObj.has(JSON_WSP_SERVICENAME)) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_SERVICENAME); + return false; + } + if (!jsonObj.has(JSON_WSP_URL)) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_URL); + return false; + } + if (!jsonObj.has(JSON_WSP_TYPES)) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPES); + return false; + } + if (!jsonObj.has(JSON_WSP_METHODS)) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_METHODS); + return false; + } + + // check whether there is at least one method defined + try { + if (jsonObj.getJSONObject(JSON_WSP_METHODS).length() == 0) { + logger.debug("IDL's \"{}\" key does not have at least one member (i.e. method).", JSON_WSP_METHODS); + } + } catch (JSONException ex) { + logger.debug("IDL does not have \"{}\" key defined in root JSON structure or \"{}\" key is not a valid JSON object.", JSON_WSP_METHODS, JSON_WSP_METHODS, ex); + } + + // at this point we can safely declare that we have detected JSON-WSP description object + return true; + } + + @Override + public int parseIDL(String idl, Resource resource) { + + //////////////////////////////////////////// + // process idl and get all necessary info // + //////////////////////////////////////////// + + // process idl into jsonObject + JSONObject jsonObj = null; + try { + jsonObj = new JSONObject(idl); + } catch (JSONException ex) { + logger.error("IDL is not a valid JSON object", ex); + } + if (jsonObj == null) { + return -1; + } + + // get webservice name + String webserviceName = null; + try { + webserviceName = jsonObj.getString(JSON_WSP_SERVICENAME); + } catch (JSONException ex) { + logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_SERVICENAME, ex); + } + + // get webservice url + String webserviceUrl = null; + try { + webserviceUrl = jsonObj.getString(JSON_WSP_URL); + } catch (JSONException ex) { + logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_URL, ex); + } + + // get webservice mime format + String webserviceMime = null; + try { + webserviceMime = jsonObj.getString(JSON_WSP_TYPE); + } catch (JSONException ex) { + logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_TYPE, ex); + } + + // get webservice idl version + String webserviceIdlVersion = null; + try { + webserviceIdlVersion = jsonObj.getString(JSON_WSP_VERSION); + } catch (JSONException ex) { + logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_VERSION, ex); + } + + // process idl endpoints (i.e. methods) + List processedEndpoints = new ArrayList<>(); + if (jsonObj.has(JSON_WSP_METHODS)) { + try { + JSONObject jsonEndpoints = jsonObj.getJSONObject(JSON_WSP_METHODS); + Iterator enpoints = jsonEndpoints.keys(); + + // iterate through all endpoints (i.e. methods) + while (enpoints.hasNext()) { + String endpointName = (String)enpoints.next(); // get endpoint name + JSONObject jsonEndpoint = jsonEndpoints.getJSONObject(endpointName); + + // get endpoint parameters + JSONObject jsonParams = jsonEndpoint.getJSONObject(JSON_WSP_METHOD_PARAMETERS); + Iterator params = jsonParams.keys(); + + // iterate through all parameters of current endpoint + List processedParams = new ArrayList<>(); + while(params.hasNext()) { + try { + // get info about parameter + String paramName = (String)params.next(); + JSONObject jsonParam = jsonParams.getJSONObject(paramName); + String paramType; + boolean paramArray; + if (jsonParam.optJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE) == null){ + paramType = jsonParam.getString(JSON_WSP_METHOD_PARAMETER_TYPE); + paramArray = false; + } else { + JSONArray jsonArray = jsonParam.getJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE); + paramType = jsonArray.getString(0); + paramArray = true; + } + long paramOrder = jsonParam.getLong(JSON_WSP_METHOD_PARAMETER_ORDER); + boolean paramOptional = jsonParam.getBoolean(JSON_WSP_METHOD_PARAMETER_OPTIONAL); + + // save parameter info into list + processedParams.add(new WebserviceEndpointParameter(paramName, paramType, paramOrder, paramOptional, paramArray)); + } catch (JSONException ex) { + logger.warn("Error while processing parameters of endpoint \"{}\".", endpointName, ex); + } + } + + // get endpoint response + JSONObject jsonEndpointResponse = jsonEndpoint.getJSONObject(JSON_WSP_METHOD_RESPONSE); + String responseType; + boolean responseArray; + if (jsonEndpointResponse.optJSONArray(JSON_WSP_METHOD_RESPONSE_TYPE) == null){ + responseType = jsonEndpointResponse.getString(JSON_WSP_METHOD_PARAMETER_TYPE); + responseArray = false; + } else { + JSONArray jsonArray = jsonEndpointResponse.getJSONArray(JSON_WSP_METHOD_PARAMETER_TYPE); + responseType = jsonArray.getString(0); + responseArray = true; + } + WebserviceEndpointResponse processedResponse = new WebserviceEndpointResponse(responseType, responseArray); + + // add endpoint info into list + processedEndpoints.add(new WebserviceEndpoint(endpointName, null, processedParams, processedResponse)); + + } + } catch (JSONException ex) { + logger.warn("Error while processing endpoints.", ex); + } + } + else { + logger.warn("IDL does not have \"{}\" key defined in root JSON structure.", JSON_WSP_METHODS); + } + + + + //////////////////////////////////////////////////////////////////////////// + // create CRCE metadata structures and fill it by retrieved info from idl // + //////////////////////////////////////////////////////////////////////////// + + // create new variables for holding references to current capabilities + Capability capability, endpoint_capability; + + // Capability - CRCE Identity + capability = metadataService.getIdentity(resource); + metadataService.setPresentationName(resource, webserviceName); + metadataService.setSize(resource, idl.length()); + capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__MIME, webserviceMime); + capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); + + // Capability - Webserviceschema Identity + capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION, webserviceIdlVersion); + resource.addCapability(capability); + resource.addRootCapability(capability); + + // Capability - Webserviceschema Webservice + capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, webserviceName); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, getSpecificWebserviceType()); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI, webserviceUrl); + resource.addCapability(capability); + resource.addRootCapability(capability); + + // Capabilities - Webservice Endpoint + for (int i = 0; i < processedEndpoints.size(); i++) { + endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); + endpoint_capability.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); + + // Properties - Webservice Enpoint Parameter + List processedParams = processedEndpoints.get(i).getParameters(); + for (int j = 0; j < processedParams.size(); j++) { + Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER, processedParams.get(j).getOrder()); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL, (long)(processedParams.get(j).isOptional() ? 1 : 0)); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY, (long)(processedParams.get(j).isArray() ? 1 : 0)); + endpoint_capability.addProperty(property); + } + + // Property - Webservice Endpoint Response + Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE, processedEndpoints.get(i).getResponse().getType()); + property.setAttribute(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY, (long)(processedEndpoints.get(i).getResponse().isArray() ? 1 : 0)); + endpoint_capability.addProperty(property); + + resource.addCapability(endpoint_capability); + capability.addChild(endpoint_capability); + } + + // return "1" as a number of parsed WSs, since JSON-WSP description document can describe exactly one webservice at once + return 1; + } + + @Override + public String generateIDL(Resource resource) { + final String INDENT = " "; + StringBuilder sb = new StringBuilder(); + + // get all neccesary info from resource and it's capabilities + Capability capability = metadataService.getIdentity(resource); + String mime = capability.getAttributeStringValue(ATTRIBUTE__CRCE_IDENTITY__MIME); + capability = resource.getRootCapabilities(NAMESPACE__WEBSERVICESCHEMA_IDENTITY).get(0); + String idlVersion = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION); + capability = resource.getRootCapabilities(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE).get(0); + String webserviceName = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME); + String webserviceUrl = capability.getAttributeStringValue(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI); + List endpoints = capability.getChildren(); + + // construct IDL from retrieved info according to the JSON-WSP description object specification + sb.append("{\n"); + sb.append(INDENT).append("\"type\": \"").append(mime).append("\",\n"); + sb.append(INDENT).append("\"version\": \"").append(idlVersion).append("\",\n"); + sb.append(INDENT).append("\"servicename\": \"").append(webserviceName).append("\",\n"); + sb.append(INDENT).append("\"url\": \"").append(webserviceUrl).append("\",\n"); + sb.append(INDENT).append("\"types\": {},\n"); // complex types are not currently being stored in CRCE + sb.append(INDENT).append("\"methods\": {\n"); + for (int i = 0; i < endpoints.size(); i++) { // endpoints + sb.append(INDENT).append(INDENT).append("\"").append(endpoints.get(i).getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME)).append("\": {\n"); + List params = endpoints.get(i).getProperties(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); + sb.append(INDENT).append(INDENT).append(INDENT).append("\"params\": {\n"); + for (int j = 0; j < params.size(); j++) { // params + Property param = params.get(j); + String paramType = param.getAttributeStringValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE); + if (param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ARRAY) == 1) { + paramType = "[" + paramType + "]"; + } + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"").append(param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME)).append("\": {\n"); + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"def_order\": ").append(param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER)).append(",\n"); + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"type\": \"").append(paramType).append("\",\n"); + if (param.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL) == 1) { + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"optional\": true\n"); + } else { + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"optional\": false\n"); + } + if (params.size() != j + 1) { + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("},\n"); + } else { + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("}\n"); + } + } + Property response = endpoints.get(i).getProperties(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE).get(0); + String responseType = response.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE); + if (response.getAttributeValue(ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__ARRAY) == 1) { + responseType = "[" + responseType + "]"; + } + sb.append(INDENT).append(INDENT).append(INDENT).append("},\n"); + sb.append(INDENT).append(INDENT).append(INDENT).append("\"ret_info\": {\n"); + sb.append(INDENT).append(INDENT).append(INDENT).append(INDENT).append("\"type\": \"").append(responseType).append("\"\n"); + sb.append(INDENT).append(INDENT).append(INDENT).append("}\n"); + if (endpoints.size() != i + 1) { + sb.append(INDENT).append(INDENT).append("},\n"); + } else { + sb.append(INDENT).append(INDENT).append("}\n"); + } + } + sb.append(INDENT).append("}\n"); + sb.append("}\n"); + + // return generated IDL + return sb.toString(); + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWadl.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWadl.java index 61c9a686..e9495b95 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWadl.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWadl.java @@ -1,361 +1,361 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; - -/** - *

This class can recognize and parse remote IDL documents representing WADL (Web Application Description Language) - * (see http://www.w3.org/Submission/wadl/#x3-70002.2). - * - *

Parsed WADL description object describing webservice is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a - * {@link cz.zcu.kiv.crce.metadata.Resource}. - * - *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly - * mentioned here is not being processed by this class. - * - *

IDL aspects parsed by this class: - *

    - *
  • webservice endpoints (WADL "method" elements):
  • - *
      - *
    • endpoint name
    • - *
    • endpoint type (GET, POST, DELETE, ...)
    • - *
    • path to the endpoint (absolute path constructed from relative paths of parent "resource" elements)
    • - *
    • parameters (for each parameter it's name, type and whether it's optional is being processed)
    • - *
    - *
- * - *

Endpoint (WADL "method" element) responses and any "method", "representation" and "param" elements in root element ("application" element) are NOT - * PROCESSED by this class at the moment. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWadl extends WebserviceTypeBase implements WebserviceType { - - private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); - - private static final String WADL_WEBSERVICE_NAME = "REST webservice"; // WADL does not define any WS name, so we use a default generic one - private static final String WADL_MIME = "application/wadl+xml"; - - private static final String WADL_APPLICATION = "application"; - private static final String WADL_RESOURCES = "resources"; - private static final String WADL_RESOURCE = "resource"; - private static final String WADL_RESOURCE_PARAM = "param"; - private static final String WADL_RESOURCE_METHOD = "method"; - private static final String WADL_RESOURCE_METHOD_REQUEST = "request"; - @SuppressWarnings("unused") - private static final String WADL_RESOURCE_METHOD_RESPONSE = "response"; - - /** - * Constructor - * - * @param mf - * @param ms - */ - public WebserviceTypeWadl(MetadataFactory mf, MetadataService ms) { - super(mf, ms); - } - - @Override - public String getSpecificIdlCategory() { - return "wadl"; - } - - @Override - public String getSpecificWebserviceType() { - return "rest"; - } - - @Override - public boolean recognizeIDL(String idl) { - - // check whether IDL is a valid XML - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - Document document = null; - try { - builder = factory.newDocumentBuilder(); - document = builder.parse(new InputSource(new StringReader(idl))); - } catch (ParserConfigurationException | SAXException | IOException ex) { - logger.debug("IDL is not a valid XML object", ex); - } - if (document == null) { - return false; - } - - // check whether IDL has a valid WSDL structure - Element root = document.getDocumentElement(); - stripOfNamespaceRecursive(root); - if (!root.getNodeName().equalsIgnoreCase(WADL_APPLICATION)) { - logger.debug("IDL is not a valid WADL. Does not have a root element \"{}\"", WADL_APPLICATION); - return false; - } - - // check whether WSDL has at least one resource set defined - if (root.getElementsByTagName(WADL_RESOURCES).getLength() < 1) { - logger.debug("WADL does not have any \"{}\" elements defined i.e. no webservice IDL endpoints to parse.", WADL_RESOURCES); - return false; - } - - return true; - } - - @Override - public int parseIDL(String idl, Resource resource) { - - //////////////////////////////////////////// - // process idl and get all necessary info // - //////////////////////////////////////////// - - // check whether IDL is a valid XML - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - Document document = null; - try { - builder = factory.newDocumentBuilder(); - document = builder.parse(new InputSource(new StringReader(idl))); - } catch (ParserConfigurationException | SAXException | IOException ex) { - logger.debug("IDL is not a valid XML object", ex); - } - if (document == null) { - return -1; - } - - // check whether IDL has a valid WADL structure - Element root = document.getDocumentElement(); - stripOfNamespaceRecursive(root); - if (!root.getNodeName().equalsIgnoreCase(WADL_APPLICATION)) { - logger.debug("IDL is not a valid WADL. Does not have a root element \"{}\"", WADL_APPLICATION); - return -1; - } - - // TODO WADL can define multiple "method", "representation" and "param" elements in its root element and then point to these abstract elements from - // particular ones (see http://www.w3.org/Submission/wadl/#x3-70002.2). Process those elements and then use them while parsing concrete representations. - - // process all resource sets defined in this WADL - List processedEndpoints = new ArrayList<>(); - NodeList resourceSets = root.getElementsByTagName(WADL_RESOURCES); - for (int i = 0; i < resourceSets.getLength(); i++) { - Node resourceSet = resourceSets.item(i); - String resourceSetBaseUrl = resourceSet.getAttributes().getNamedItem("base").getNodeValue(); - NodeList resources = resourceSet.getChildNodes(); - processWadlResourcesRecursive(resources, resourceSetBaseUrl, processedEndpoints); - } - - //////////////////////////////////////////////////////////////////////////// - // create CRCE metadata structures and fill it by retrieved info from idl // - //////////////////////////////////////////////////////////////////////////// - - // create new variables for holding references to current capabilities - Capability capability, endpoint_capability; - - // Capability - CRCE Identity - capability = metadataService.getIdentity(resource); - metadataService.setPresentationName(resource, WADL_WEBSERVICE_NAME); - metadataService.setSize(resource, idl.length()); - capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__MIME, WADL_MIME); - capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); - - // Capability - Webserviceschema Identity - capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); - resource.addCapability(capability); - resource.addRootCapability(capability); - - // Capability - Webserviceschema Webservice - capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, WADL_WEBSERVICE_NAME); - capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, getSpecificWebserviceType()); - resource.addCapability(capability); - resource.addRootCapability(capability); - - // Capabilities - Webservice Endpoint - for (int i = 0; i < processedEndpoints.size(); i++) { - endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); - setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); - setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__URL, processedEndpoints.get(i).getUrl()); - - // Properties - Webservice Enpoint Parameter - List processedParams = processedEndpoints.get(i).getParameters(); - for (int j = 0; j < processedParams.size(); j++) { - Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); - if (processedParams.get(j).isOptional() != null) { - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL, (long)(processedParams.get(j).isOptional() ? 1 : 0)); - } - endpoint_capability.addProperty(property); - } - - resource.addCapability(endpoint_capability); - capability.addChild(endpoint_capability); - } - - // return "1" as a number of parsed WSs, since WADL description document can describe exactly one webservice at once - return 1; - } - - /** - * Each WADL "resource" element can contain arbitrary number of "resource", "method" and "param" elements. This function process this structure recursively - * (by processing "resource" elements nested to each other) and creates {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint} from every - * "method" element along the way with parameters as all known "params" elements known at a current scope. - * - * @param resources Represent set of "resource", "method" and "param" elements on each level of recursion. - * @param baseUrl With each recursive call this parameter gets longer. It is a path used for all "method" elements and it's pieces are defined - * hierarchically in parent "resource" elements. - * @param processedEndpoints Passed {@link java.util.List} of {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint} discovered so far. - */ - private void processWadlResourcesRecursive(NodeList resources, String baseUrl, List processedEndpoints) { - - // process all parameters, methods and sub-resources defined in this resource - List processedResourceParameters = new ArrayList<>(); - for (int j = 0; j < resources.getLength(); j++) { - Node node = resources.item(j); - if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE)) { - - // process sub-resource - String resourcePath = node.getAttributes().getNamedItem("path").getNodeValue(); - NodeList subnodes = node.getChildNodes(); - processWadlResourcesRecursive(subnodes, baseUrl + resourcePath, processedEndpoints); - - } else if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE_PARAM)) { - - // process parameter - processedResourceParameters.add(processParameter(node.getAttributes())); - - } else if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD)) { - - // process method - NamedNodeMap resourceAttributes = node.getAttributes(); - String methodId = null; - if (resourceAttributes.getNamedItem("id") != null) { - methodId = resourceAttributes.getNamedItem("id").getNodeValue(); - } - String methodName = null; - if (resourceAttributes.getNamedItem("name") != null) { - methodName = resourceAttributes.getNamedItem("name").getNodeValue(); - } - - // process all requests and response of this method - List processedMethodParameters = new ArrayList<>(); - NodeList subsubnodes = node.getChildNodes(); - for (int l = 0; l < subsubnodes.getLength(); l++) { - Node subsubnode = subsubnodes.item(l); - - if (subsubnode.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD_REQUEST)) { - - // proces request - NodeList params = subsubnode.getChildNodes(); - - // process all aditional params of this method request - for (int m = 0; m < params.getLength(); m++) { - Node param = params.item(m); - if (param.getNodeName().equalsIgnoreCase("param")) { - NamedNodeMap paramAttributes = param.getAttributes(); - - // process parameter - processedMethodParameters.add(processParameter(paramAttributes)); - } - } - - } /*else if (subsubnode.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD_REQUEST)) { - // process response - // TODO WADL method can define multiple responses, each with multiple representations, refactoring will be needed in order to represent them. - }*/ - } - - // create new endpoint - String endpointName; - methodName = "(" + methodName + ")"; - if (methodId == null) { - endpointName = methodName; - } else { - endpointName = methodId + " " + methodName; - } - String endpointUrl = baseUrl; - processedMethodParameters.addAll(processedResourceParameters); - processedEndpoints.add(new WebserviceEndpoint(endpointName, endpointUrl, processedMethodParameters, null)); - - } - } - - } - - /** - * Processes attributes of WADL "param" element into {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter}. - * - * @param nodeAttributes Attributes of WADL "param" element. - * @return - */ - private WebserviceEndpointParameter processParameter(NamedNodeMap nodeAttributes) { - String paramName = null; - if (nodeAttributes.getNamedItem("name") != null) { - paramName = nodeAttributes.getNamedItem("name").getNodeValue(); - } - String paramType = null; - if (nodeAttributes.getNamedItem("type") != null) { - paramType = nodeAttributes.getNamedItem("type").getNodeValue(); - } - Boolean paramRequired = null; - if (nodeAttributes.getNamedItem("required") != null) { - if (nodeAttributes.getNamedItem("required").getNodeValue().equalsIgnoreCase("true")) { - paramRequired = true; - } else if (nodeAttributes.getNamedItem("required").getNodeValue().equalsIgnoreCase("true")) { - paramRequired = false; - } - } - return new WebserviceEndpointParameter(paramName, paramType, null, paramRequired == null ? null : !paramRequired, null); - } - - /** - * Removes namespace part of XML element node name. E.g. turns "tns:address" into "address". - * - * @param value XML element node name. - * @return XML element node name without namespace. - */ - private String stripOfNamespace(String value) { - return value.substring(value.indexOf(':') + 1); - } - - /** - * Recursively removes the namespace of a node. - * @param node the starting node. - */ - private void stripOfNamespaceRecursive(Node node) { - Document document = node.getOwnerDocument(); - if (node.getNodeType() == Node.ELEMENT_NODE) { - document.renameNode(node, null, stripOfNamespace(node.getNodeName())); - } - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); ++i) { - stripOfNamespaceRecursive(list.item(i)); - } - } - - @Override - public String generateIDL(Resource resource) { - throw new UnsupportedOperationException("Not supported yet."); - } -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; + +/** + *

This class can recognize and parse remote IDL documents representing WADL (Web Application Description Language) + * (see http://www.w3.org/Submission/wadl/#x3-70002.2). + * + *

Parsed WADL description object describing webservice is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a + * {@link cz.zcu.kiv.crce.metadata.Resource}. + * + *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly + * mentioned here is not being processed by this class. + * + *

IDL aspects parsed by this class: + *

    + *
  • webservice endpoints (WADL "method" elements):
  • + *
      + *
    • endpoint name
    • + *
    • endpoint type (GET, POST, DELETE, ...)
    • + *
    • path to the endpoint (absolute path constructed from relative paths of parent "resource" elements)
    • + *
    • parameters (for each parameter it's name, type and whether it's optional is being processed)
    • + *
    + *
+ * + *

Endpoint (WADL "method" element) responses and any "method", "representation" and "param" elements in root element ("application" element) are NOT + * PROCESSED by this class at the moment. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWadl extends WebserviceTypeBase implements WebserviceType { + + private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); + + private static final String WADL_WEBSERVICE_NAME = "REST webservice"; // WADL does not define any WS name, so we use a default generic one + private static final String WADL_MIME = "application/wadl+xml"; + + private static final String WADL_APPLICATION = "application"; + private static final String WADL_RESOURCES = "resources"; + private static final String WADL_RESOURCE = "resource"; + private static final String WADL_RESOURCE_PARAM = "param"; + private static final String WADL_RESOURCE_METHOD = "method"; + private static final String WADL_RESOURCE_METHOD_REQUEST = "request"; + @SuppressWarnings("unused") + private static final String WADL_RESOURCE_METHOD_RESPONSE = "response"; + + /** + * Constructor + * + * @param mf + * @param ms + */ + public WebserviceTypeWadl(MetadataFactory mf, MetadataService ms) { + super(mf, ms); + } + + @Override + public String getSpecificIdlCategory() { + return "wadl"; + } + + @Override + public String getSpecificWebserviceType() { + return "rest"; + } + + @Override + public boolean recognizeIDL(String idl) { + + // check whether IDL is a valid XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + Document document = null; + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(idl))); + } catch (ParserConfigurationException | SAXException | IOException ex) { + logger.debug("IDL is not a valid XML object", ex); + } + if (document == null) { + return false; + } + + // check whether IDL has a valid WSDL structure + Element root = document.getDocumentElement(); + stripOfNamespaceRecursive(root); + if (!root.getNodeName().equalsIgnoreCase(WADL_APPLICATION)) { + logger.debug("IDL is not a valid WADL. Does not have a root element \"{}\"", WADL_APPLICATION); + return false; + } + + // check whether WSDL has at least one resource set defined + if (root.getElementsByTagName(WADL_RESOURCES).getLength() < 1) { + logger.debug("WADL does not have any \"{}\" elements defined i.e. no webservice IDL endpoints to parse.", WADL_RESOURCES); + return false; + } + + return true; + } + + @Override + public int parseIDL(String idl, Resource resource) { + + //////////////////////////////////////////// + // process idl and get all necessary info // + //////////////////////////////////////////// + + // check whether IDL is a valid XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + Document document = null; + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(idl))); + } catch (ParserConfigurationException | SAXException | IOException ex) { + logger.debug("IDL is not a valid XML object", ex); + } + if (document == null) { + return -1; + } + + // check whether IDL has a valid WADL structure + Element root = document.getDocumentElement(); + stripOfNamespaceRecursive(root); + if (!root.getNodeName().equalsIgnoreCase(WADL_APPLICATION)) { + logger.debug("IDL is not a valid WADL. Does not have a root element \"{}\"", WADL_APPLICATION); + return -1; + } + + // TODO WADL can define multiple "method", "representation" and "param" elements in its root element and then point to these abstract elements from + // particular ones (see http://www.w3.org/Submission/wadl/#x3-70002.2). Process those elements and then use them while parsing concrete representations. + + // process all resource sets defined in this WADL + List processedEndpoints = new ArrayList<>(); + NodeList resourceSets = root.getElementsByTagName(WADL_RESOURCES); + for (int i = 0; i < resourceSets.getLength(); i++) { + Node resourceSet = resourceSets.item(i); + String resourceSetBaseUrl = resourceSet.getAttributes().getNamedItem("base").getNodeValue(); + NodeList resources = resourceSet.getChildNodes(); + processWadlResourcesRecursive(resources, resourceSetBaseUrl, processedEndpoints); + } + + //////////////////////////////////////////////////////////////////////////// + // create CRCE metadata structures and fill it by retrieved info from idl // + //////////////////////////////////////////////////////////////////////////// + + // create new variables for holding references to current capabilities + Capability capability, endpoint_capability; + + // Capability - CRCE Identity + capability = metadataService.getIdentity(resource); + metadataService.setPresentationName(resource, WADL_WEBSERVICE_NAME); + metadataService.setSize(resource, idl.length()); + capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__MIME, WADL_MIME); + capability.setAttribute(ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); + + // Capability - Webserviceschema Identity + capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); + resource.addCapability(capability); + resource.addRootCapability(capability); + + // Capability - Webserviceschema Webservice + capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, WADL_WEBSERVICE_NAME); + capability.setAttribute(ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, getSpecificWebserviceType()); + resource.addCapability(capability); + resource.addRootCapability(capability); + + // Capabilities - Webservice Endpoint + for (int i = 0; i < processedEndpoints.size(); i++) { + endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); + setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); + setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__URL, processedEndpoints.get(i).getUrl()); + + // Properties - Webservice Enpoint Parameter + List processedParams = processedEndpoints.get(i).getParameters(); + for (int j = 0; j < processedParams.size(); j++) { + Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); + if (processedParams.get(j).isOptional() != null) { + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__OPTIONAL, (long)(processedParams.get(j).isOptional() ? 1 : 0)); + } + endpoint_capability.addProperty(property); + } + + resource.addCapability(endpoint_capability); + capability.addChild(endpoint_capability); + } + + // return "1" as a number of parsed WSs, since WADL description document can describe exactly one webservice at once + return 1; + } + + /** + * Each WADL "resource" element can contain arbitrary number of "resource", "method" and "param" elements. This function process this structure recursively + * (by processing "resource" elements nested to each other) and creates {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint} from every + * "method" element along the way with parameters as all known "params" elements known at a current scope. + * + * @param resources Represent set of "resource", "method" and "param" elements on each level of recursion. + * @param baseUrl With each recursive call this parameter gets longer. It is a path used for all "method" elements and it's pieces are defined + * hierarchically in parent "resource" elements. + * @param processedEndpoints Passed {@link java.util.List} of {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint} discovered so far. + */ + private void processWadlResourcesRecursive(NodeList resources, String baseUrl, List processedEndpoints) { + + // process all parameters, methods and sub-resources defined in this resource + List processedResourceParameters = new ArrayList<>(); + for (int j = 0; j < resources.getLength(); j++) { + Node node = resources.item(j); + if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE)) { + + // process sub-resource + String resourcePath = node.getAttributes().getNamedItem("path").getNodeValue(); + NodeList subnodes = node.getChildNodes(); + processWadlResourcesRecursive(subnodes, baseUrl + resourcePath, processedEndpoints); + + } else if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE_PARAM)) { + + // process parameter + processedResourceParameters.add(processParameter(node.getAttributes())); + + } else if (node.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD)) { + + // process method + NamedNodeMap resourceAttributes = node.getAttributes(); + String methodId = null; + if (resourceAttributes.getNamedItem("id") != null) { + methodId = resourceAttributes.getNamedItem("id").getNodeValue(); + } + String methodName = null; + if (resourceAttributes.getNamedItem("name") != null) { + methodName = resourceAttributes.getNamedItem("name").getNodeValue(); + } + + // process all requests and response of this method + List processedMethodParameters = new ArrayList<>(); + NodeList subsubnodes = node.getChildNodes(); + for (int l = 0; l < subsubnodes.getLength(); l++) { + Node subsubnode = subsubnodes.item(l); + + if (subsubnode.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD_REQUEST)) { + + // proces request + NodeList params = subsubnode.getChildNodes(); + + // process all aditional params of this method request + for (int m = 0; m < params.getLength(); m++) { + Node param = params.item(m); + if (param.getNodeName().equalsIgnoreCase("param")) { + NamedNodeMap paramAttributes = param.getAttributes(); + + // process parameter + processedMethodParameters.add(processParameter(paramAttributes)); + } + } + + } /*else if (subsubnode.getNodeName().equalsIgnoreCase(WADL_RESOURCE_METHOD_REQUEST)) { + // process response + // TODO WADL method can define multiple responses, each with multiple representations, refactoring will be needed in order to represent them. + }*/ + } + + // create new endpoint + String endpointName; + methodName = "(" + methodName + ")"; + if (methodId == null) { + endpointName = methodName; + } else { + endpointName = methodId + " " + methodName; + } + String endpointUrl = baseUrl; + processedMethodParameters.addAll(processedResourceParameters); + processedEndpoints.add(new WebserviceEndpoint(endpointName, endpointUrl, processedMethodParameters, null)); + + } + } + + } + + /** + * Processes attributes of WADL "param" element into {@link cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter}. + * + * @param nodeAttributes Attributes of WADL "param" element. + * @return + */ + private WebserviceEndpointParameter processParameter(NamedNodeMap nodeAttributes) { + String paramName = null; + if (nodeAttributes.getNamedItem("name") != null) { + paramName = nodeAttributes.getNamedItem("name").getNodeValue(); + } + String paramType = null; + if (nodeAttributes.getNamedItem("type") != null) { + paramType = nodeAttributes.getNamedItem("type").getNodeValue(); + } + Boolean paramRequired = null; + if (nodeAttributes.getNamedItem("required") != null) { + if (nodeAttributes.getNamedItem("required").getNodeValue().equalsIgnoreCase("true")) { + paramRequired = true; + } else if (nodeAttributes.getNamedItem("required").getNodeValue().equalsIgnoreCase("true")) { + paramRequired = false; + } + } + return new WebserviceEndpointParameter(paramName, paramType, null, paramRequired == null ? null : !paramRequired, null); + } + + /** + * Removes namespace part of XML element node name. E.g. turns "tns:address" into "address". + * + * @param value XML element node name. + * @return XML element node name without namespace. + */ + private String stripOfNamespace(String value) { + return value.substring(value.indexOf(':') + 1); + } + + /** + * Recursively removes the namespace of a node. + * @param node the starting node. + */ + private void stripOfNamespaceRecursive(Node node) { + Document document = node.getOwnerDocument(); + if (node.getNodeType() == Node.ELEMENT_NODE) { + document.renameNode(node, null, stripOfNamespace(node.getNodeName())); + } + NodeList list = node.getChildNodes(); + for (int i = 0; i < list.getLength(); ++i) { + stripOfNamespaceRecursive(list.item(i)); + } + } + + @Override + public String generateIDL(Resource resource) { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWsdl.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWsdl.java index e4d1520b..027df872 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWsdl.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/internal/WebserviceTypeWsdl.java @@ -1,625 +1,625 @@ -package cz.zcu.kiv.crce.webservices.indexer.internal; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import cz.zcu.kiv.crce.metadata.Capability; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.Property; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.webservices.indexer.structures.Webservice; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; -import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointResponse; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlBindedOperation; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlBinding; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlInterface; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlMessage; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlOperation; -import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlPart; - -/** - *

This class can recognize and parse remote IDL documents representing WSDL (Web Services Description Language) - * (see http://www.w3.org/TR/wsdl20/). - * - *

Parsed WSDL description object describing webservices is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a - * {@link cz.zcu.kiv.crce.metadata.Resource} for each webservice description in the IDL. - * - *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly - * mentioned here is not being processed by this class. - * - *

IDL aspects parsed by this class: - *

    - *
  • WSDL version
  • - *
  • name of all webservices ("name" property of "service" element)
  • - *
  • webservice endpoints (each to it's corresponding webservice)
  • - *
      - *
    • endpoint name
    • - *
    • - *
    • parameters (for each parameter it's name, type and order is being processed)
    • - *
    • type of returned response (in document (i.e. messaging) communication style, output message can generally contain multiple parts, for now only - * first one is being grabbed)
    • - *
    - *
- * - *

Almost entire WSDL document is being processed (except "types" section, "fault" elements and several attributes of "input" and "output" elements), but - * due to the unified representation of webservice descriptions in CRCE repository only some of that information is being stored. For details see the code in - * this class. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdl extends WebserviceTypeBase implements WebserviceType { - - private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); - - private static final String WSDL_V_1_1 = "1.1"; - private static final String WSDL_V_2_0 = "2.0"; - - private static final String WSDL_MIME = "application/wsdl+xml"; - - private static final String WSDL_DESCRIPTION_V_1_1 = "definitions"; - private static final String WSDL_DESCRIPTION_V_2_0 = "description"; - private static final String WSDL_MESSAGE = "message"; - private static final String WSDL_SERVICE_INTERFACE_V_1_1 = "portType"; - private static final String WSDL_SERVICE_INTERFACE_V_2_0 = "interface"; - private static final String WSDL_BINDING = "binding"; - private static final String WSDL_SERVICE = "service"; - private static final String WSDL_SERVICE_ENDPOINT_V_1_1 = "port"; - private static final String WSDL_SERVICE_ENDPOINT_V_2_0 = "endpoint"; - - /** - * Constructor - * - * @param mf - * @param ms - */ - public WebserviceTypeWsdl(MetadataFactory mf, MetadataService ms) { - super(mf, ms); - } - - @Override - public String getSpecificIdlCategory() { - return "wsdl"; - } - - @Override - public String getSpecificWebserviceType() { - return "rpc/messaging"; - } - - @Override - public boolean recognizeIDL(String idl) { - - // check whether IDL is a valid XML - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - Document document = null; - try { - builder = factory.newDocumentBuilder(); - document = builder.parse(new InputSource(new StringReader(idl))); - } catch (ParserConfigurationException | SAXException | IOException ex) { - logger.debug("IDL is not a valid XML object", ex); - } - if (document == null) { - return false; - } - - // check whether IDL has a valid WSDL structure - Element root = document.getDocumentElement(); - stripOfNamespaceRecursive(root); - if (!root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_1_1) && !root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_2_0)) { - logger.debug("IDL is not a valid WSDL. Does not have a root element \"{}\" or \"{}\"", WSDL_DESCRIPTION_V_1_1, WSDL_DESCRIPTION_V_2_0); - return false; - } - -// // check whether WSDL has at least one service defined -// if (root.getElementsByTagName(WSDL_SERVICE).getLength() < 1) { -// logger.debug("WSDL does not have any \"{}\" elements defined i.e. no webservice IDLs to parse.", WSDL_SERVICE); -// return false; -// } - - return true; - } - - @Override - public int parseIDL(String idl, Resource resource) { - - //////////////////////////////////////////// - // process idl and get all necessary info // - //////////////////////////////////////////// - - // process IDL into XML DOM object - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - Document document = null; - try { - builder = factory.newDocumentBuilder(); - document = builder.parse(new InputSource(new StringReader(idl))); - } catch (ParserConfigurationException | SAXException | IOException ex) { - logger.debug("IDL is not a valid XML object", ex); - } - if (document == null) { - return -1; - } - - // get root WSDL element and thus detect WSDL version - Element root = document.getDocumentElement(); - String rootWsdlVersion; - stripOfNamespaceRecursive(root); - if (root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_1_1)) { - rootWsdlVersion = WSDL_V_1_1; - } else { - if (root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_2_0)) { - rootWsdlVersion = WSDL_V_2_0; - } else { - logger.debug("IDL is not a valid WSDL. Does not have a root element \"{}\" or \"{}\"", WSDL_DESCRIPTION_V_1_1, WSDL_DESCRIPTION_V_2_0); - return -1; - } - } - - // process all messages into list (WSDL 2.0 does not define any message elements) - NodeList messages = root.getElementsByTagName(WSDL_MESSAGE); - List processedMessges = new ArrayList<>(); - if (messages.getLength() > 0) { - processMessages(messages, processedMessges); - } - - // process all portTypes / interfaces into list - NodeList portTypes = root.getElementsByTagName(WSDL_SERVICE_INTERFACE_V_1_1); - NodeList interfaces = root.getElementsByTagName(WSDL_SERVICE_INTERFACE_V_2_0); - List processedInterfaces = new ArrayList<>(); - if (portTypes.getLength() > 0 && interfaces.getLength() == 0) { - //wsdlVersion = WSDL_V_1_1; - processInterfaces(portTypes, processedInterfaces); - } else if (portTypes.getLength() == 0 && interfaces.getLength() > 0) { - //wsdlVersion = WSDL_V_2_0; - processInterfaces(interfaces, processedInterfaces); - } else { - logger.warn("Processed WSDL seems to use both {} and {} specification. Parsing both \"{}\" and \"{}\" elements.", WSDL_V_1_1, WSDL_V_2_0, WSDL_SERVICE_INTERFACE_V_1_1, WSDL_SERVICE_INTERFACE_V_2_0); - processInterfaces(portTypes, processedInterfaces); - processInterfaces(interfaces, processedInterfaces); - } - - // process all bindings into list - NodeList bindings = root.getElementsByTagName(WSDL_BINDING); - List processedBindings = new ArrayList<>(); - processBindings(bindings, processedBindings); - - // process all services defined in this WSDL - List processedWebservices = new ArrayList<>(); - NodeList services = root.getElementsByTagName(WSDL_SERVICE); - for (int i = 0; i < services.getLength(); i++) { - Node service = services.item(i); - NamedNodeMap serviceAttributes = service.getAttributes(); - String serviceName = returnNodeValue(serviceAttributes, "name"); - String serviceIdlVersion = null; - - // get info about service endpoints - List processedEndpoints = new ArrayList<>(); - NodeList endpoints = service.getChildNodes(); - for(int j = 0; j < endpoints.getLength(); j++) { - Node endpoint = endpoints.item(j); - - if (endpoint.getNodeName().equalsIgnoreCase(WSDL_SERVICE_ENDPOINT_V_1_1)) { - // detected as WSDL 1.1 - serviceIdlVersion = WSDL_V_1_1; - } else if (endpoint.getNodeName().equalsIgnoreCase(WSDL_SERVICE_ENDPOINT_V_2_0)) { - // detected as WSDL 2.0 - serviceIdlVersion = WSDL_V_2_0; - } else { - logger.warn("Unrecognizable element \"{}\" in WSDL \"{}\" element", endpoint.getNodeName(), WSDL_SERVICE); - continue; - } - - NamedNodeMap endpointAttributes = endpoint.getAttributes(); - String endpointBinding = returnNodeValue(endpointAttributes, "binding"); - - // get all operations implemented by this endpoint via its's binding object and list of operations defined in corresponding interface - WebserviceTypeWsdlBinding binding = getBindingByName(processedBindings, endpointBinding); - List bindedOperations = binding.getBindedOperations(); - List interfaceOperations = getInterfaceByName(processedInterfaces, binding.getInterface_()).getOperations(); - - // process all operation defined in binding - for (WebserviceTypeWsdlBindedOperation bindedOperation : bindedOperations) { - // Note: This single binded operation represent endpoint in CRCE semantics. One WSDL port / endpoint can bind multiple particular operations - // each with their parameters, datatypes, return value etc. That is why CRCE Webservice Endpoint corresponds to WSDL Operation. - - WebserviceTypeWsdlOperation operation = getOperationByName(interfaceOperations, bindedOperation.getName()); - - // proces all input parts defined in this operation as endpoint parameters - List processedParameters = new ArrayList<>(); - if (operation.getInputMessage() != null) { - List parts = getMessageByName(processedMessges, operation.getInputMessage()).getParts(); - for (int k = 0; k < parts.size(); k++) { - WebserviceTypeWsdlPart part = parts.get(k); - String endpointParameterType = part.getType() != null ? part.getType() : part.getElement(); - processedParameters.add(new WebserviceEndpointParameter(part.getName(), endpointParameterType, (long)k + 1, null, null)); - } - } else if (operation.getInputElement() != null) { - processedParameters.add(new WebserviceEndpointParameter(operation.getName(), operation.getInputElement(), null, null, null)); - } else { - logger.warn("WSDL \"input\" element of operation \"{}\" does not have \"message\" or \"element\" attributes."); - } - - // proces all output parts defined in this operation as endpoint response - // TODO In document (i.e. messaging) communication style, output message can generally contain multiple parts - now we just grab a first one. - String endpointResponseType = null; - if (operation.getOutputMessage() != null) { - List parts = getMessageByName(processedMessges, operation.getOutputMessage()).getParts(); - if (parts.size() > 0) { - endpointResponseType = parts.get(0).getType() != null ? parts.get(0).getType() : parts.get(0).getElement(); - } - } else if (operation.getOutputElement() != null) { - endpointResponseType = operation.getOutputElement(); - } else { - logger.warn("WSDL \"output\" element of operation \"{}\" does not have \"message\" or \"element\" attributes."); - } - WebserviceEndpointResponse processedResponse = new WebserviceEndpointResponse(endpointResponseType, null); - - // add info about new endpoint - processedEndpoints.add(new WebserviceEndpoint(operation.getName(), bindedOperation.getSoapAction(), processedParameters, processedResponse)); - } - } - - processedWebservices.add(new Webservice(serviceName, null, serviceIdlVersion, getSpecificWebserviceType(), processedEndpoints)); - } - - //////////////////////////////////////////////////////////////////////////// - // create CRCE metadata structures and fill it by retrieved info from idl // - //////////////////////////////////////////////////////////////////////////// - - // create new variables for holding references to current capabilities - Capability capability, webservice_capability, endpoint_capability; - - // Capability - CRCE Identity - String main_name; - switch (processedWebservices.size()) { - case 0: - main_name = "No webservice descriptions"; - break; - case 1: - main_name = processedWebservices.get(0).getName(); - break; - default: - main_name = "Multiple webservice descriptions"; - break; - } - capability = metadataService.getIdentity(resource); - metadataService.setPresentationName(resource, main_name); - metadataService.setSize(resource, idl.length()); - setIfSet(capability, ATTRIBUTE__CRCE_IDENTITY__MIME, WSDL_MIME); - setIfSet(capability, ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); - - // Capability - Webserviceschema Identity - capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); - setIfSet(capability, ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION, rootWsdlVersion); - resource.addCapability(capability); - resource.addRootCapability(capability); - - // create one capability for each detected webservice representation - for (Webservice processedWebservice : processedWebservices) { - - // Capability - Webserviceschema Webservice - webservice_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); - setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, processedWebservice.getName()); - setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, processedWebservice.getType()); - setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI, processedWebservice.getUrl()); - - // Capabilities - Webservice Endpoint - List processedEndpoints = processedWebservice.getEndpoints(); - for (int i = 0; i < processedEndpoints.size(); i++) { - endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); - setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); - - // Properties - Webservice Enpoint Parameter - List processedParams = processedEndpoints.get(i).getParameters(); - for (int j = 0; j < processedParams.size(); j++) { - Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER, processedParams.get(j).getOrder()); - endpoint_capability.addProperty(property); - } - - // Property - Webservice Endpoint Response - Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE); - setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE, processedEndpoints.get(i).getResponse().getType()); - endpoint_capability.addProperty(property); - - resource.addCapability(endpoint_capability); - webservice_capability.addChild(endpoint_capability); - } - - resource.addCapability(webservice_capability); - capability.addChild(webservice_capability); - } - - return processedWebservices.size(); - } - - /** - * Processes all portTypes (WSDL 1.1) / interfaces (WSDL 2.0) defined in WSDL IDL document. - * - * @param interfaces Passed portTypes (WSDL 1.1) / interfaces (WSDL 2.0) defined in WSDL IDL document. - * @param processedInterfaces Resulting processed portTypes (WSDL 1.1) / interfaces (WSDL 2.0). - */ - private void processInterfaces(NodeList interfaces, List processedInterfaces) { - - // iterate through all passed "portType" / "interface" elements - for (int i = 0; i < interfaces.getLength(); i++) { - Node interface_ = interfaces.item(i); - NamedNodeMap interfaceAttributes = interface_.getAttributes(); - String interfaceName = returnNodeValue(interfaceAttributes, "name"); - - // iterate through all "operation" elements in "portType" / "interface" element - NodeList operations = interface_.getChildNodes(); - List processedOperations = new ArrayList<>(); - for (int j = 0; j < operations.getLength(); j++) { - Node operation = operations.item(j); - if (!operation.getNodeName().equalsIgnoreCase("operation")) { - continue; // WSDL 2.0 can define "fault" elements at this structure level - } - NamedNodeMap operationAttributes = operation.getAttributes(); - String operationName = returnNodeValue(operationAttributes, "name"); - String inputName = null; - String inputMessage = null; - String inputElement = null; - String outputName = null; - String outputMessage = null; - String outputElement = null; - - // iterate through all "input", "output" and "fault" elements in "operation" element - NodeList subNodes = operation.getChildNodes(); - for (int k = 0; k < subNodes.getLength(); k++) { - Node subnode = subNodes.item(k); - if (subnode.getNodeName().equalsIgnoreCase("input")) { - // found the "input" element => save all neccessary info about it - NamedNodeMap subNodeAttributes = subnode.getAttributes(); - inputName = returnNodeValue(subNodeAttributes, "name"); // WSDL 1.1 - if (inputName == null) { - inputName = returnNodeValue(subNodeAttributes, "messageLabel"); // WSDL 2.0 - } - inputMessage = returnNodeValue(subNodeAttributes, "message"); // WSDL 1.1 - inputElement = returnNodeValue(subNodeAttributes, "element"); // WSDL 2.0 - } else if (subnode.getNodeName().equalsIgnoreCase("output")) { - // found the "output" element => save all neccessary info about it - NamedNodeMap subNodeAttributes = subnode.getAttributes(); - outputName = returnNodeValue(subNodeAttributes, "name"); // WSDL 1.1 - if (outputName == null) { - outputName = returnNodeValue(subNodeAttributes, "messageLabel"); // WSDL 2.0 - } - outputMessage = returnNodeValue(subNodeAttributes, "message"); // WSDL 1.1 - outputElement = returnNodeValue(subNodeAttributes, "element"); // WSDL 2.0 - } - } - - // save info about processed operation - processedOperations.add(new WebserviceTypeWsdlOperation(operationName, inputName, inputMessage, inputElement, outputName, outputMessage, outputElement)); - } - - // save info about processed interface - processedInterfaces.add(new WebserviceTypeWsdlInterface(interfaceName, processedOperations)); - } - } - - /** - * Processes all messages (WSDL 1.1) defined in WSDL IDL document. - * - * @param messages Passed messages (WSDL 1.1) defined in WSDL IDL document. - * @param processedMessages Resulting processed messages (WSDL 1.1). - */ - private void processMessages(NodeList messages, List processedMessages) { - - // iterate through all passed "message" elements - for (int i = 0; i < messages.getLength(); i++) { - Node message = messages.item(i); - NamedNodeMap messageAttributes = message.getAttributes(); - String messageName = returnNodeValue(messageAttributes, "name"); - - // iterate through all "part" elements in "message" element - NodeList parts = message.getChildNodes(); - List processedParts = new ArrayList<>(); - for (int j = 0; j < parts.getLength(); j++) { - Node part = parts.item(j); - if (part.getNodeName().equalsIgnoreCase("part")) { - NamedNodeMap partAttributes = part.getAttributes(); - String partName = returnNodeValue(partAttributes, "name"); - String partType = returnNodeValue(partAttributes, "type"); - String partElement = returnNodeValue(partAttributes, "element"); - - // save info about processed parts - processedParts.add(new WebserviceTypeWsdlPart(partName, partType, partElement)); - } - } - - // save info about processed message - processedMessages.add(new WebserviceTypeWsdlMessage(messageName, processedParts)); - } - } - - /** - * Processes all bindings defined in WSDL IDL document. - * - * @param bindings Passed bindings defined in WSDL IDL document. - * @param processedBindings Resulting processed bindings. - */ - private void processBindings(NodeList bindings, List processedBindings) { - - // iterate through all passed "binding" elements - for (int i = 0; i < bindings.getLength(); i++) { - Node binding = bindings.item(i); - NamedNodeMap bindingAttributes = binding.getAttributes(); - String bindingName = returnNodeValue(bindingAttributes, "name"); - String bindingInterface = returnNodeValue(bindingAttributes, "type"); // WSDL 1.1 - if (bindingInterface == null) { - bindingInterface = returnNodeValue(bindingAttributes, "interface"); // WSDL 2.0 - } - if(bindingInterface == null) { - continue; - } - - // get SOAP-specific binding info - //Node bindingSoap = getNodeByNameAndNamespace(binding.getChildNodes(), "binding", "soap"); - //NamedNodeMap bindingSoapAttributes = bindingSoap.getAttributes(); - String bindingSoapStyle = returnNodeValue(bindingAttributes, "style"); - String bindingSoapTransport = returnNodeValue(bindingAttributes, "transport"); - - // iterate through all "operation" elements in "binding" element - NodeList operations = binding.getChildNodes(); - List processedBindedOperations = new ArrayList<>(); - for (int j = 0; j < operations.getLength(); j++) { - Node operation = operations.item(j); - if (operation.getNodeName().equalsIgnoreCase("operation")) { - String bindedOperationName = returnNodeValue(operation.getAttributes(), "name"); - - // get SOAP-specific operation info - //Node bindedOperationSoap = getNodeByNameAndNamespace(operation.getChildNodes(), "operation", "soap"); - //NamedNodeMap bindedOperationSoapAttributes = bindedOperationSoap.getAttributes(); - String bindedOperationSoapAction = returnNodeValue(operation.getAttributes(), "action"); - String bindedOperationSoapStyle = returnNodeValue(operation.getAttributes(), "style"); - - // save info about binded operation - processedBindedOperations.add(new WebserviceTypeWsdlBindedOperation(bindedOperationName, bindedOperationSoapAction, bindedOperationSoapStyle)); - } - } - - // save info about binding - processedBindings.add(new WebserviceTypeWsdlBinding(bindingName, bindingInterface, processedBindedOperations, bindingSoapStyle, bindingSoapTransport)); - } - } - - /** - * Returns binding from a list based on it's name. - * - * @param bindings List of bindings. - * @param name Name of desired binding. - * @return Returns binding from a list based on it's name. - */ - private WebserviceTypeWsdlBinding getBindingByName(List bindings, String name) { - if (bindings == null || name == null) { - return null; - } - for (WebserviceTypeWsdlBinding binding : bindings) { - if (binding.getName().equals(stripOfNamespace(name))) { - return binding; - } - } - return null; - } - - /** - * Returns interface from a list based on it's name. - * - * @param interfaces List of interfaces. - * @param name Name of desired interface. - * @return Returns interface from a list based on it's name. - */ - private WebserviceTypeWsdlInterface getInterfaceByName(List interfaces, String name) { - if (interfaces == null || name == null) { - return null; - } - for (WebserviceTypeWsdlInterface interface_ : interfaces) { - if (interface_.getName().equals(stripOfNamespace(name))) { - return interface_; - } - } - return null; - } - - /** - * Returns operation from a list based on it's name. - * - * @param operations List of operations. - * @param name Name of desired operation. - * @return Returns operation from a list based on it's name. - */ - private WebserviceTypeWsdlOperation getOperationByName(List operations, String name) { - if (operations == null || name == null) { - return null; - } - for (WebserviceTypeWsdlOperation operation : operations) { - if (operation.getName().equals(stripOfNamespace(name))) { - return operation; - } - } - return null; - } - - /** - * Returns message from a list based on it's name. - * - * @param messages List of messages. - * @param name Name of desired message. - * @return Returns message from a list based on it's name. - */ - private WebserviceTypeWsdlMessage getMessageByName(List messages, String name) { - if (messages == null || name == null) { - return null; - } - for (WebserviceTypeWsdlMessage message : messages) { - if (message.getName().equals(stripOfNamespace(name))) { - return message; - } - } - return null; - } - - /** - * Returns value of attribute only if it exists in passed attributes. - * - * @param namedNodeMap List of attributes. - * @param nodeName Name of attribute with desired value. - * @return Value of attribute only if it exists in passed attributes. null otherwise. - */ - private String returnNodeValue(NamedNodeMap namedNodeMap, String nodeName) { - Node node = namedNodeMap.getNamedItem(nodeName); - return node == null ? null : node.getNodeValue(); - } - - /** - * Removes namespace part of XML element node name. E.g. turns "tns:address" into "address". - * - * @param value XML element node name. - * @return XML element node name without namespace. - */ - private String stripOfNamespace(String value) { - return value.substring(value.indexOf(':') + 1); - } - - /** - * Recursively removes the namespace of a node. - * @param node the starting node. - */ - private void stripOfNamespaceRecursive(Node node) { - Document document = node.getOwnerDocument(); - if (node.getNodeType() == Node.ELEMENT_NODE) { - document.renameNode(node, null, stripOfNamespace(node.getNodeName())); - } - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); ++i) { - stripOfNamespaceRecursive(list.item(i)); - } - } - - @Override - public String generateIDL(Resource resource) { - throw new UnsupportedOperationException("Not supported yet."); - } -} +package cz.zcu.kiv.crce.webservices.indexer.internal; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import cz.zcu.kiv.crce.metadata.Capability; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.Property; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.webservices.indexer.structures.Webservice; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpoint; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointParameter; +import cz.zcu.kiv.crce.webservices.indexer.structures.WebserviceEndpointResponse; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlBindedOperation; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlBinding; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlInterface; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlMessage; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlOperation; +import cz.zcu.kiv.crce.webservices.indexer.structures.wsdl.WebserviceTypeWsdlPart; + +/** + *

This class can recognize and parse remote IDL documents representing WSDL (Web Services Description Language) + * (see http://www.w3.org/TR/wsdl20/). + * + *

Parsed WSDL description object describing webservices is then represented by {@link cz.zcu.kiv.crce.metadata.Capability} returned in a + * {@link cz.zcu.kiv.crce.metadata.Resource} for each webservice description in the IDL. + * + *

Following aspects of IDL are parsed by this class and stored in CRCE repository as meta-data to the IDL document. Everything that is not explicitly + * mentioned here is not being processed by this class. + * + *

IDL aspects parsed by this class: + *

    + *
  • WSDL version
  • + *
  • name of all webservices ("name" property of "service" element)
  • + *
  • webservice endpoints (each to it's corresponding webservice)
  • + *
      + *
    • endpoint name
    • + *
    • + *
    • parameters (for each parameter it's name, type and order is being processed)
    • + *
    • type of returned response (in document (i.e. messaging) communication style, output message can generally contain multiple parts, for now only + * first one is being grabbed)
    • + *
    + *
+ * + *

Almost entire WSDL document is being processed (except "types" section, "fault" elements and several attributes of "input" and "output" elements), but + * due to the unified representation of webservice descriptions in CRCE repository only some of that information is being stored. For details see the code in + * this class. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdl extends WebserviceTypeBase implements WebserviceType { + + private static final Logger logger = LoggerFactory.getLogger(WebserviceDescriptionResourceIndexer.class); + + private static final String WSDL_V_1_1 = "1.1"; + private static final String WSDL_V_2_0 = "2.0"; + + private static final String WSDL_MIME = "application/wsdl+xml"; + + private static final String WSDL_DESCRIPTION_V_1_1 = "definitions"; + private static final String WSDL_DESCRIPTION_V_2_0 = "description"; + private static final String WSDL_MESSAGE = "message"; + private static final String WSDL_SERVICE_INTERFACE_V_1_1 = "portType"; + private static final String WSDL_SERVICE_INTERFACE_V_2_0 = "interface"; + private static final String WSDL_BINDING = "binding"; + private static final String WSDL_SERVICE = "service"; + private static final String WSDL_SERVICE_ENDPOINT_V_1_1 = "port"; + private static final String WSDL_SERVICE_ENDPOINT_V_2_0 = "endpoint"; + + /** + * Constructor + * + * @param mf + * @param ms + */ + public WebserviceTypeWsdl(MetadataFactory mf, MetadataService ms) { + super(mf, ms); + } + + @Override + public String getSpecificIdlCategory() { + return "wsdl"; + } + + @Override + public String getSpecificWebserviceType() { + return "rpc/messaging"; + } + + @Override + public boolean recognizeIDL(String idl) { + + // check whether IDL is a valid XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + Document document = null; + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(idl))); + } catch (ParserConfigurationException | SAXException | IOException ex) { + logger.debug("IDL is not a valid XML object", ex); + } + if (document == null) { + return false; + } + + // check whether IDL has a valid WSDL structure + Element root = document.getDocumentElement(); + stripOfNamespaceRecursive(root); + if (!root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_1_1) && !root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_2_0)) { + logger.debug("IDL is not a valid WSDL. Does not have a root element \"{}\" or \"{}\"", WSDL_DESCRIPTION_V_1_1, WSDL_DESCRIPTION_V_2_0); + return false; + } + +// // check whether WSDL has at least one service defined +// if (root.getElementsByTagName(WSDL_SERVICE).getLength() < 1) { +// logger.debug("WSDL does not have any \"{}\" elements defined i.e. no webservice IDLs to parse.", WSDL_SERVICE); +// return false; +// } + + return true; + } + + @Override + public int parseIDL(String idl, Resource resource) { + + //////////////////////////////////////////// + // process idl and get all necessary info // + //////////////////////////////////////////// + + // process IDL into XML DOM object + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + Document document = null; + try { + builder = factory.newDocumentBuilder(); + document = builder.parse(new InputSource(new StringReader(idl))); + } catch (ParserConfigurationException | SAXException | IOException ex) { + logger.debug("IDL is not a valid XML object", ex); + } + if (document == null) { + return -1; + } + + // get root WSDL element and thus detect WSDL version + Element root = document.getDocumentElement(); + String rootWsdlVersion; + stripOfNamespaceRecursive(root); + if (root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_1_1)) { + rootWsdlVersion = WSDL_V_1_1; + } else { + if (root.getNodeName().equalsIgnoreCase(WSDL_DESCRIPTION_V_2_0)) { + rootWsdlVersion = WSDL_V_2_0; + } else { + logger.debug("IDL is not a valid WSDL. Does not have a root element \"{}\" or \"{}\"", WSDL_DESCRIPTION_V_1_1, WSDL_DESCRIPTION_V_2_0); + return -1; + } + } + + // process all messages into list (WSDL 2.0 does not define any message elements) + NodeList messages = root.getElementsByTagName(WSDL_MESSAGE); + List processedMessges = new ArrayList<>(); + if (messages.getLength() > 0) { + processMessages(messages, processedMessges); + } + + // process all portTypes / interfaces into list + NodeList portTypes = root.getElementsByTagName(WSDL_SERVICE_INTERFACE_V_1_1); + NodeList interfaces = root.getElementsByTagName(WSDL_SERVICE_INTERFACE_V_2_0); + List processedInterfaces = new ArrayList<>(); + if (portTypes.getLength() > 0 && interfaces.getLength() == 0) { + //wsdlVersion = WSDL_V_1_1; + processInterfaces(portTypes, processedInterfaces); + } else if (portTypes.getLength() == 0 && interfaces.getLength() > 0) { + //wsdlVersion = WSDL_V_2_0; + processInterfaces(interfaces, processedInterfaces); + } else { + logger.warn("Processed WSDL seems to use both {} and {} specification. Parsing both \"{}\" and \"{}\" elements.", WSDL_V_1_1, WSDL_V_2_0, WSDL_SERVICE_INTERFACE_V_1_1, WSDL_SERVICE_INTERFACE_V_2_0); + processInterfaces(portTypes, processedInterfaces); + processInterfaces(interfaces, processedInterfaces); + } + + // process all bindings into list + NodeList bindings = root.getElementsByTagName(WSDL_BINDING); + List processedBindings = new ArrayList<>(); + processBindings(bindings, processedBindings); + + // process all services defined in this WSDL + List processedWebservices = new ArrayList<>(); + NodeList services = root.getElementsByTagName(WSDL_SERVICE); + for (int i = 0; i < services.getLength(); i++) { + Node service = services.item(i); + NamedNodeMap serviceAttributes = service.getAttributes(); + String serviceName = returnNodeValue(serviceAttributes, "name"); + String serviceIdlVersion = null; + + // get info about service endpoints + List processedEndpoints = new ArrayList<>(); + NodeList endpoints = service.getChildNodes(); + for(int j = 0; j < endpoints.getLength(); j++) { + Node endpoint = endpoints.item(j); + + if (endpoint.getNodeName().equalsIgnoreCase(WSDL_SERVICE_ENDPOINT_V_1_1)) { + // detected as WSDL 1.1 + serviceIdlVersion = WSDL_V_1_1; + } else if (endpoint.getNodeName().equalsIgnoreCase(WSDL_SERVICE_ENDPOINT_V_2_0)) { + // detected as WSDL 2.0 + serviceIdlVersion = WSDL_V_2_0; + } else { + logger.warn("Unrecognizable element \"{}\" in WSDL \"{}\" element", endpoint.getNodeName(), WSDL_SERVICE); + continue; + } + + NamedNodeMap endpointAttributes = endpoint.getAttributes(); + String endpointBinding = returnNodeValue(endpointAttributes, "binding"); + + // get all operations implemented by this endpoint via its's binding object and list of operations defined in corresponding interface + WebserviceTypeWsdlBinding binding = getBindingByName(processedBindings, endpointBinding); + List bindedOperations = binding.getBindedOperations(); + List interfaceOperations = getInterfaceByName(processedInterfaces, binding.getInterface_()).getOperations(); + + // process all operation defined in binding + for (WebserviceTypeWsdlBindedOperation bindedOperation : bindedOperations) { + // Note: This single binded operation represent endpoint in CRCE semantics. One WSDL port / endpoint can bind multiple particular operations + // each with their parameters, datatypes, return value etc. That is why CRCE Webservice Endpoint corresponds to WSDL Operation. + + WebserviceTypeWsdlOperation operation = getOperationByName(interfaceOperations, bindedOperation.getName()); + + // proces all input parts defined in this operation as endpoint parameters + List processedParameters = new ArrayList<>(); + if (operation.getInputMessage() != null) { + List parts = getMessageByName(processedMessges, operation.getInputMessage()).getParts(); + for (int k = 0; k < parts.size(); k++) { + WebserviceTypeWsdlPart part = parts.get(k); + String endpointParameterType = part.getType() != null ? part.getType() : part.getElement(); + processedParameters.add(new WebserviceEndpointParameter(part.getName(), endpointParameterType, (long)k + 1, null, null)); + } + } else if (operation.getInputElement() != null) { + processedParameters.add(new WebserviceEndpointParameter(operation.getName(), operation.getInputElement(), null, null, null)); + } else { + logger.warn("WSDL \"input\" element of operation \"{}\" does not have \"message\" or \"element\" attributes."); + } + + // proces all output parts defined in this operation as endpoint response + // TODO In document (i.e. messaging) communication style, output message can generally contain multiple parts - now we just grab a first one. + String endpointResponseType = null; + if (operation.getOutputMessage() != null) { + List parts = getMessageByName(processedMessges, operation.getOutputMessage()).getParts(); + if (parts.size() > 0) { + endpointResponseType = parts.get(0).getType() != null ? parts.get(0).getType() : parts.get(0).getElement(); + } + } else if (operation.getOutputElement() != null) { + endpointResponseType = operation.getOutputElement(); + } else { + logger.warn("WSDL \"output\" element of operation \"{}\" does not have \"message\" or \"element\" attributes."); + } + WebserviceEndpointResponse processedResponse = new WebserviceEndpointResponse(endpointResponseType, null); + + // add info about new endpoint + processedEndpoints.add(new WebserviceEndpoint(operation.getName(), bindedOperation.getSoapAction(), processedParameters, processedResponse)); + } + } + + processedWebservices.add(new Webservice(serviceName, null, serviceIdlVersion, getSpecificWebserviceType(), processedEndpoints)); + } + + //////////////////////////////////////////////////////////////////////////// + // create CRCE metadata structures and fill it by retrieved info from idl // + //////////////////////////////////////////////////////////////////////////// + + // create new variables for holding references to current capabilities + Capability capability, webservice_capability, endpoint_capability; + + // Capability - CRCE Identity + String main_name; + switch (processedWebservices.size()) { + case 0: + main_name = "No webservice descriptions"; + break; + case 1: + main_name = processedWebservices.get(0).getName(); + break; + default: + main_name = "Multiple webservice descriptions"; + break; + } + capability = metadataService.getIdentity(resource); + metadataService.setPresentationName(resource, main_name); + metadataService.setSize(resource, idl.length()); + setIfSet(capability, ATTRIBUTE__CRCE_IDENTITY__MIME, WSDL_MIME); + setIfSet(capability, ATTRIBUTE__CRCE_IDENTITY__HASH, getIdlHash(idl)); + + // Capability - Webserviceschema Identity + capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_IDENTITY); + setIfSet(capability, ATTRIBUTE__WEBSERVICESCHEMA_IDENTITY__IDL_VERSION, rootWsdlVersion); + resource.addCapability(capability); + resource.addRootCapability(capability); + + // create one capability for each detected webservice representation + for (Webservice processedWebservice : processedWebservices) { + + // Capability - Webserviceschema Webservice + webservice_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICESCHEMA_WEBSERVICE); + setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__NAME, processedWebservice.getName()); + setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__TYPE, processedWebservice.getType()); + setIfSet(webservice_capability, ATTRIBUTE__WEBSERVICESCHEMA_WEBSERVICE__URI, processedWebservice.getUrl()); + + // Capabilities - Webservice Endpoint + List processedEndpoints = processedWebservice.getEndpoints(); + for (int i = 0; i < processedEndpoints.size(); i++) { + endpoint_capability = metadataFactory.createCapability(NAMESPACE__WEBSERVICE_ENDPOINT); + setIfSet(endpoint_capability, ATTRIBUTE__WEBSERVICE_ENDPOINT__NAME, processedEndpoints.get(i).getName()); + + // Properties - Webservice Enpoint Parameter + List processedParams = processedEndpoints.get(i).getParameters(); + for (int j = 0; j < processedParams.size(); j++) { + Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_PARAMETER); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__NAME, processedParams.get(j).getName()); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__TYPE, processedParams.get(j).getType()); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_PARAMETER__ORDER, processedParams.get(j).getOrder()); + endpoint_capability.addProperty(property); + } + + // Property - Webservice Endpoint Response + Property property = metadataFactory.createProperty(NAMESPACE__WEBSERVICE_ENDPOINT_RESPONSE); + setIfSet(property, ATTRIBUTE__WEBSERVICE_ENDPOINT_RESPONSE__TYPE, processedEndpoints.get(i).getResponse().getType()); + endpoint_capability.addProperty(property); + + resource.addCapability(endpoint_capability); + webservice_capability.addChild(endpoint_capability); + } + + resource.addCapability(webservice_capability); + capability.addChild(webservice_capability); + } + + return processedWebservices.size(); + } + + /** + * Processes all portTypes (WSDL 1.1) / interfaces (WSDL 2.0) defined in WSDL IDL document. + * + * @param interfaces Passed portTypes (WSDL 1.1) / interfaces (WSDL 2.0) defined in WSDL IDL document. + * @param processedInterfaces Resulting processed portTypes (WSDL 1.1) / interfaces (WSDL 2.0). + */ + private void processInterfaces(NodeList interfaces, List processedInterfaces) { + + // iterate through all passed "portType" / "interface" elements + for (int i = 0; i < interfaces.getLength(); i++) { + Node interface_ = interfaces.item(i); + NamedNodeMap interfaceAttributes = interface_.getAttributes(); + String interfaceName = returnNodeValue(interfaceAttributes, "name"); + + // iterate through all "operation" elements in "portType" / "interface" element + NodeList operations = interface_.getChildNodes(); + List processedOperations = new ArrayList<>(); + for (int j = 0; j < operations.getLength(); j++) { + Node operation = operations.item(j); + if (!operation.getNodeName().equalsIgnoreCase("operation")) { + continue; // WSDL 2.0 can define "fault" elements at this structure level + } + NamedNodeMap operationAttributes = operation.getAttributes(); + String operationName = returnNodeValue(operationAttributes, "name"); + String inputName = null; + String inputMessage = null; + String inputElement = null; + String outputName = null; + String outputMessage = null; + String outputElement = null; + + // iterate through all "input", "output" and "fault" elements in "operation" element + NodeList subNodes = operation.getChildNodes(); + for (int k = 0; k < subNodes.getLength(); k++) { + Node subnode = subNodes.item(k); + if (subnode.getNodeName().equalsIgnoreCase("input")) { + // found the "input" element => save all neccessary info about it + NamedNodeMap subNodeAttributes = subnode.getAttributes(); + inputName = returnNodeValue(subNodeAttributes, "name"); // WSDL 1.1 + if (inputName == null) { + inputName = returnNodeValue(subNodeAttributes, "messageLabel"); // WSDL 2.0 + } + inputMessage = returnNodeValue(subNodeAttributes, "message"); // WSDL 1.1 + inputElement = returnNodeValue(subNodeAttributes, "element"); // WSDL 2.0 + } else if (subnode.getNodeName().equalsIgnoreCase("output")) { + // found the "output" element => save all neccessary info about it + NamedNodeMap subNodeAttributes = subnode.getAttributes(); + outputName = returnNodeValue(subNodeAttributes, "name"); // WSDL 1.1 + if (outputName == null) { + outputName = returnNodeValue(subNodeAttributes, "messageLabel"); // WSDL 2.0 + } + outputMessage = returnNodeValue(subNodeAttributes, "message"); // WSDL 1.1 + outputElement = returnNodeValue(subNodeAttributes, "element"); // WSDL 2.0 + } + } + + // save info about processed operation + processedOperations.add(new WebserviceTypeWsdlOperation(operationName, inputName, inputMessage, inputElement, outputName, outputMessage, outputElement)); + } + + // save info about processed interface + processedInterfaces.add(new WebserviceTypeWsdlInterface(interfaceName, processedOperations)); + } + } + + /** + * Processes all messages (WSDL 1.1) defined in WSDL IDL document. + * + * @param messages Passed messages (WSDL 1.1) defined in WSDL IDL document. + * @param processedMessages Resulting processed messages (WSDL 1.1). + */ + private void processMessages(NodeList messages, List processedMessages) { + + // iterate through all passed "message" elements + for (int i = 0; i < messages.getLength(); i++) { + Node message = messages.item(i); + NamedNodeMap messageAttributes = message.getAttributes(); + String messageName = returnNodeValue(messageAttributes, "name"); + + // iterate through all "part" elements in "message" element + NodeList parts = message.getChildNodes(); + List processedParts = new ArrayList<>(); + for (int j = 0; j < parts.getLength(); j++) { + Node part = parts.item(j); + if (part.getNodeName().equalsIgnoreCase("part")) { + NamedNodeMap partAttributes = part.getAttributes(); + String partName = returnNodeValue(partAttributes, "name"); + String partType = returnNodeValue(partAttributes, "type"); + String partElement = returnNodeValue(partAttributes, "element"); + + // save info about processed parts + processedParts.add(new WebserviceTypeWsdlPart(partName, partType, partElement)); + } + } + + // save info about processed message + processedMessages.add(new WebserviceTypeWsdlMessage(messageName, processedParts)); + } + } + + /** + * Processes all bindings defined in WSDL IDL document. + * + * @param bindings Passed bindings defined in WSDL IDL document. + * @param processedBindings Resulting processed bindings. + */ + private void processBindings(NodeList bindings, List processedBindings) { + + // iterate through all passed "binding" elements + for (int i = 0; i < bindings.getLength(); i++) { + Node binding = bindings.item(i); + NamedNodeMap bindingAttributes = binding.getAttributes(); + String bindingName = returnNodeValue(bindingAttributes, "name"); + String bindingInterface = returnNodeValue(bindingAttributes, "type"); // WSDL 1.1 + if (bindingInterface == null) { + bindingInterface = returnNodeValue(bindingAttributes, "interface"); // WSDL 2.0 + } + if(bindingInterface == null) { + continue; + } + + // get SOAP-specific binding info + //Node bindingSoap = getNodeByNameAndNamespace(binding.getChildNodes(), "binding", "soap"); + //NamedNodeMap bindingSoapAttributes = bindingSoap.getAttributes(); + String bindingSoapStyle = returnNodeValue(bindingAttributes, "style"); + String bindingSoapTransport = returnNodeValue(bindingAttributes, "transport"); + + // iterate through all "operation" elements in "binding" element + NodeList operations = binding.getChildNodes(); + List processedBindedOperations = new ArrayList<>(); + for (int j = 0; j < operations.getLength(); j++) { + Node operation = operations.item(j); + if (operation.getNodeName().equalsIgnoreCase("operation")) { + String bindedOperationName = returnNodeValue(operation.getAttributes(), "name"); + + // get SOAP-specific operation info + //Node bindedOperationSoap = getNodeByNameAndNamespace(operation.getChildNodes(), "operation", "soap"); + //NamedNodeMap bindedOperationSoapAttributes = bindedOperationSoap.getAttributes(); + String bindedOperationSoapAction = returnNodeValue(operation.getAttributes(), "action"); + String bindedOperationSoapStyle = returnNodeValue(operation.getAttributes(), "style"); + + // save info about binded operation + processedBindedOperations.add(new WebserviceTypeWsdlBindedOperation(bindedOperationName, bindedOperationSoapAction, bindedOperationSoapStyle)); + } + } + + // save info about binding + processedBindings.add(new WebserviceTypeWsdlBinding(bindingName, bindingInterface, processedBindedOperations, bindingSoapStyle, bindingSoapTransport)); + } + } + + /** + * Returns binding from a list based on it's name. + * + * @param bindings List of bindings. + * @param name Name of desired binding. + * @return Returns binding from a list based on it's name. + */ + private WebserviceTypeWsdlBinding getBindingByName(List bindings, String name) { + if (bindings == null || name == null) { + return null; + } + for (WebserviceTypeWsdlBinding binding : bindings) { + if (binding.getName().equals(stripOfNamespace(name))) { + return binding; + } + } + return null; + } + + /** + * Returns interface from a list based on it's name. + * + * @param interfaces List of interfaces. + * @param name Name of desired interface. + * @return Returns interface from a list based on it's name. + */ + private WebserviceTypeWsdlInterface getInterfaceByName(List interfaces, String name) { + if (interfaces == null || name == null) { + return null; + } + for (WebserviceTypeWsdlInterface interface_ : interfaces) { + if (interface_.getName().equals(stripOfNamespace(name))) { + return interface_; + } + } + return null; + } + + /** + * Returns operation from a list based on it's name. + * + * @param operations List of operations. + * @param name Name of desired operation. + * @return Returns operation from a list based on it's name. + */ + private WebserviceTypeWsdlOperation getOperationByName(List operations, String name) { + if (operations == null || name == null) { + return null; + } + for (WebserviceTypeWsdlOperation operation : operations) { + if (operation.getName().equals(stripOfNamespace(name))) { + return operation; + } + } + return null; + } + + /** + * Returns message from a list based on it's name. + * + * @param messages List of messages. + * @param name Name of desired message. + * @return Returns message from a list based on it's name. + */ + private WebserviceTypeWsdlMessage getMessageByName(List messages, String name) { + if (messages == null || name == null) { + return null; + } + for (WebserviceTypeWsdlMessage message : messages) { + if (message.getName().equals(stripOfNamespace(name))) { + return message; + } + } + return null; + } + + /** + * Returns value of attribute only if it exists in passed attributes. + * + * @param namedNodeMap List of attributes. + * @param nodeName Name of attribute with desired value. + * @return Value of attribute only if it exists in passed attributes. null otherwise. + */ + private String returnNodeValue(NamedNodeMap namedNodeMap, String nodeName) { + Node node = namedNodeMap.getNamedItem(nodeName); + return node == null ? null : node.getNodeValue(); + } + + /** + * Removes namespace part of XML element node name. E.g. turns "tns:address" into "address". + * + * @param value XML element node name. + * @return XML element node name without namespace. + */ + private String stripOfNamespace(String value) { + return value.substring(value.indexOf(':') + 1); + } + + /** + * Recursively removes the namespace of a node. + * @param node the starting node. + */ + private void stripOfNamespaceRecursive(Node node) { + Document document = node.getOwnerDocument(); + if (node.getNodeType() == Node.ELEMENT_NODE) { + document.renameNode(node, null, stripOfNamespace(node.getNodeName())); + } + NodeList list = node.getChildNodes(); + for (int i = 0; i < list.getLength(); ++i) { + stripOfNamespaceRecursive(list.item(i)); + } + } + + @Override + public String generateIDL(Resource resource) { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/Webservice.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/Webservice.java index 6bc77c3f..259d1011 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/Webservice.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/Webservice.java @@ -1,105 +1,105 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures; - -import java.util.List; - -/** - * This is a data class for inner representation of webservice functionality. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class Webservice { - - private String name; - private String url; - private String idlVersion; - private String type; // rpc / messaging / rest - private List endpoints; - - /** - * Constructor. - * - * @param name Name of webservice. - * @param url URL from which webservice can be accessed. - * @param idlVersion Version of IDL which describes this webservice. - * @param type Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... - * @param endpoints List of endpoints available at this webservice. - */ - public Webservice(String name, String url, String idlVersion, String type, List endpoints) { - this.name = name; - this.url = url; - this.idlVersion = idlVersion; - this.type = type; - this.endpoints = endpoints; - } - - /** - * @return Name of webservice. - */ - public String getName() { - return name; - } - - /** - * @param name Name of webservice. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return URL from which webservice can be accessed. - */ - public String getUrl() { - return url; - } - - /** - * @param url URL from which webservice can be accessed. - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * @return Version of IDL which describes this webservice. - */ - public String getIdlVersion() { - return idlVersion; - } - - /** - * @param idlVersion Version of IDL which describes this webservice. - */ - public void setIdlVersion(String idlVersion) { - this.idlVersion = idlVersion; - } - - /** - * @return Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... - */ - public String getType() { - return type; - } - - /** - * @param type Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return List of endpoints available at this webservice. - */ - public List getEndpoints() { - return endpoints; - } - - /** - * @param endpoints List of endpoints available at this webservice. - */ - public void setEndpoints(List endpoints) { - this.endpoints = endpoints; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures; + +import java.util.List; + +/** + * This is a data class for inner representation of webservice functionality. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class Webservice { + + private String name; + private String url; + private String idlVersion; + private String type; // rpc / messaging / rest + private List endpoints; + + /** + * Constructor. + * + * @param name Name of webservice. + * @param url URL from which webservice can be accessed. + * @param idlVersion Version of IDL which describes this webservice. + * @param type Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... + * @param endpoints List of endpoints available at this webservice. + */ + public Webservice(String name, String url, String idlVersion, String type, List endpoints) { + this.name = name; + this.url = url; + this.idlVersion = idlVersion; + this.type = type; + this.endpoints = endpoints; + } + + /** + * @return Name of webservice. + */ + public String getName() { + return name; + } + + /** + * @param name Name of webservice. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return URL from which webservice can be accessed. + */ + public String getUrl() { + return url; + } + + /** + * @param url URL from which webservice can be accessed. + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * @return Version of IDL which describes this webservice. + */ + public String getIdlVersion() { + return idlVersion; + } + + /** + * @param idlVersion Version of IDL which describes this webservice. + */ + public void setIdlVersion(String idlVersion) { + this.idlVersion = idlVersion; + } + + /** + * @return Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... + */ + public String getType() { + return type; + } + + /** + * @param type Type of webservice communication pattern. E.g. "rpc", "messaging", "rest", etc... + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return List of endpoints available at this webservice. + */ + public List getEndpoints() { + return endpoints; + } + + /** + * @param endpoints List of endpoints available at this webservice. + */ + public void setEndpoints(List endpoints) { + this.endpoints = endpoints; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpoint.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpoint.java index 48a69cc5..664daf20 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpoint.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpoint.java @@ -1,88 +1,88 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures; - -import java.util.List; - -/** - * This is a data class for inner representation of webservice endpoint functionality. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceEndpoint { - - private String name; - private String url; - private List parameters; - private WebserviceEndpointResponse response; - - /** - * Constructor. - * - * @param name Name of webservice endpoint. - * @param url URL from which webservice endpoint can be accessed. - * @param parameters List of parameters passed to this webservice endpoint. - * @param response Response returned by this webservice endpoint. - */ - public WebserviceEndpoint(String name, String url, List parameters, WebserviceEndpointResponse response) { - this.name = name; - this.url = url; - this.parameters = parameters; - this.response = response; - } - - /** - * @return Name of webservice endpoint. - */ - public String getName() { - return name; - } - - /** - * @param name Name of webservice endpoint. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return List of parameters passed to this webservice endpoint. - */ - public List getParameters() { - return parameters; - } - - /** - * @param parameters List of parameters passed to this webservice endpoint. - */ - public void setParameters(List parameters) { - this.parameters = parameters; - } - - /** - * @return Response returned by this webservice endpoint. - */ - public WebserviceEndpointResponse getResponse() { - return response; - } - - /** - * @param response Response returned by this webservice endpoint. - */ - public void setResponse(WebserviceEndpointResponse response) { - this.response = response; - } - - /** - * @return URL from which webservice endpoint can be accessed. - */ - public String getUrl() { - return url; - } - - /** - * @param url URL from which webservice endpoint can be accessed. - */ - public void setUrl(String url) { - this.url = url; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures; + +import java.util.List; + +/** + * This is a data class for inner representation of webservice endpoint functionality. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceEndpoint { + + private String name; + private String url; + private List parameters; + private WebserviceEndpointResponse response; + + /** + * Constructor. + * + * @param name Name of webservice endpoint. + * @param url URL from which webservice endpoint can be accessed. + * @param parameters List of parameters passed to this webservice endpoint. + * @param response Response returned by this webservice endpoint. + */ + public WebserviceEndpoint(String name, String url, List parameters, WebserviceEndpointResponse response) { + this.name = name; + this.url = url; + this.parameters = parameters; + this.response = response; + } + + /** + * @return Name of webservice endpoint. + */ + public String getName() { + return name; + } + + /** + * @param name Name of webservice endpoint. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return List of parameters passed to this webservice endpoint. + */ + public List getParameters() { + return parameters; + } + + /** + * @param parameters List of parameters passed to this webservice endpoint. + */ + public void setParameters(List parameters) { + this.parameters = parameters; + } + + /** + * @return Response returned by this webservice endpoint. + */ + public WebserviceEndpointResponse getResponse() { + return response; + } + + /** + * @param response Response returned by this webservice endpoint. + */ + public void setResponse(WebserviceEndpointResponse response) { + this.response = response; + } + + /** + * @return URL from which webservice endpoint can be accessed. + */ + public String getUrl() { + return url; + } + + /** + * @param url URL from which webservice endpoint can be accessed. + */ + public void setUrl(String url) { + this.url = url; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointParameter.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointParameter.java index 3fa4c06b..9f518028 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointParameter.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointParameter.java @@ -1,103 +1,103 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures; - -/** - * This is a data class for inner representation of functionality of a parameter passed to the webservice endpoint. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceEndpointParameter { - - private String name; - private String type; - private Long order; - private Boolean optional; - private Boolean array; - - /** - * Constructor. - * - * @param name Name of parameter. - * @param type Datatype of parameter. - * @param order Position of parameter (i.e. at which place it is put when passed to the endpoint). - * @param optional Defines whether this parameter is optional. - * @param array Defines whether this parameter is represented as a single instance of type or a collection of it. - */ - public WebserviceEndpointParameter(String name, String type, Long order, Boolean optional, Boolean array) { - this.name = name; - this.type = type; - this.order = order; - this.optional = optional; - this.array = array; - } - - /** - * @return Name of parameter. - */ - public String getName() { - return name; - } - - /** - * @param name Name of parameter. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return Datatype of parameter. - */ - public String getType() { - return type; - } - - /** - * @param type Datatype of parameter. - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return Position of parameter (i.e. at which place it is put when passed to the endpoint). - */ - public Long getOrder() { - return order; - } - - /** - * @param order Position of parameter (i.e. at which place it is put when passed to the endpoint). - */ - public void setOrder(Long order) { - this.order = order; - } - - /** - * @return Defines whether this parameter is optional. - */ - public Boolean isOptional() { - return optional; - } - - /** - * @param optional Defines whether this parameter is optional. - */ - public void setOptional(Boolean optional) { - this.optional = optional; - } - - /** - * @return Defines whether this parameter is represented as a single instance of type or a collection of it. - */ - public Boolean isArray() { - return array; - } - - /** - * @param array Defines whether this parameter is represented as a single instance of type or a collection of it. - */ - public void setArray(Boolean array) { - this.array = array; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures; + +/** + * This is a data class for inner representation of functionality of a parameter passed to the webservice endpoint. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceEndpointParameter { + + private String name; + private String type; + private Long order; + private Boolean optional; + private Boolean array; + + /** + * Constructor. + * + * @param name Name of parameter. + * @param type Datatype of parameter. + * @param order Position of parameter (i.e. at which place it is put when passed to the endpoint). + * @param optional Defines whether this parameter is optional. + * @param array Defines whether this parameter is represented as a single instance of type or a collection of it. + */ + public WebserviceEndpointParameter(String name, String type, Long order, Boolean optional, Boolean array) { + this.name = name; + this.type = type; + this.order = order; + this.optional = optional; + this.array = array; + } + + /** + * @return Name of parameter. + */ + public String getName() { + return name; + } + + /** + * @param name Name of parameter. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return Datatype of parameter. + */ + public String getType() { + return type; + } + + /** + * @param type Datatype of parameter. + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return Position of parameter (i.e. at which place it is put when passed to the endpoint). + */ + public Long getOrder() { + return order; + } + + /** + * @param order Position of parameter (i.e. at which place it is put when passed to the endpoint). + */ + public void setOrder(Long order) { + this.order = order; + } + + /** + * @return Defines whether this parameter is optional. + */ + public Boolean isOptional() { + return optional; + } + + /** + * @param optional Defines whether this parameter is optional. + */ + public void setOptional(Boolean optional) { + this.optional = optional; + } + + /** + * @return Defines whether this parameter is represented as a single instance of type or a collection of it. + */ + public Boolean isArray() { + return array; + } + + /** + * @param array Defines whether this parameter is represented as a single instance of type or a collection of it. + */ + public void setArray(Boolean array) { + this.array = array; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointResponse.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointResponse.java index 48e8d39b..460bf1ef 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointResponse.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/WebserviceEndpointResponse.java @@ -1,52 +1,52 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures; - -/** - * This is a data class for inner representation of functionality of a response returned from the webservice endpoint. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceEndpointResponse { - - private String type; - private Boolean array; - - /** - * Constructor. - * - * @param type Datatype of response. - * @param array Defines whether this response is represented as a single instance of type or a collection of it. - */ - public WebserviceEndpointResponse(String type, Boolean array) { - this.type = type; - this.array = array; - } - - /** - * @return Datatype of response. - */ - public String getType() { - return type; - } - - /** - * @param type Datatype of response. - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return Defines whether this response is represented as a single instance of type or a collection of it. - */ - public Boolean isArray() { - return array; - } - - /** - * @param array Defines whether this response is represented as a single instance of type or a collection of it. - */ - public void setArray(Boolean array) { - this.array = array; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures; + +/** + * This is a data class for inner representation of functionality of a response returned from the webservice endpoint. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceEndpointResponse { + + private String type; + private Boolean array; + + /** + * Constructor. + * + * @param type Datatype of response. + * @param array Defines whether this response is represented as a single instance of type or a collection of it. + */ + public WebserviceEndpointResponse(String type, Boolean array) { + this.type = type; + this.array = array; + } + + /** + * @return Datatype of response. + */ + public String getType() { + return type; + } + + /** + * @param type Datatype of response. + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return Defines whether this response is represented as a single instance of type or a collection of it. + */ + public Boolean isArray() { + return array; + } + + /** + * @param array Defines whether this response is represented as a single instance of type or a collection of it. + */ + public void setArray(Boolean array) { + this.array = array; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBindedOperation.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBindedOperation.java index 085be91d..9c11554e 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBindedOperation.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBindedOperation.java @@ -1,75 +1,75 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -/** - * This is a data class for inner representation of WSDL binding element. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlBindedOperation { - - private String name; - - // attributes specific for SOAP XML namespace - private String soapAction; - private String soapStyle; - - /** - * Constructor. - * - * @param name Name of this binded operation. - * @param soapAction URL from which this functionality can be accessed at. - * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - */ - public WebserviceTypeWsdlBindedOperation(String name, String soapAction, String soapStyle) { - this.name = name; - this.soapAction = soapAction; - this.soapStyle = soapStyle; - } - - @Override - public String toString() { - return String.format("name: %s, soapAction: %s, soapStyle: %s", name, soapAction, soapStyle); - } - - /** - * @return Name of this binded operation. - */ - public String getName() { - return name; - } - - /** - * @param name Name of this binded operation. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return URL from which this functionality can be accessed at. - */ - public String getSoapAction() { - return soapAction; - } - - /** - * @param soapAction URL from which this functionality can be accessed at. - */ - public void setSoapAction(String soapAction) { - this.soapAction = soapAction; - } - - /** - * @return Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - */ - public String getSoapStyle() { - return soapStyle; - } - - /** - * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - */ - public void setSoapStyle(String soapStyle) { - this.soapStyle = soapStyle; - } -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +/** + * This is a data class for inner representation of WSDL binding element. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlBindedOperation { + + private String name; + + // attributes specific for SOAP XML namespace + private String soapAction; + private String soapStyle; + + /** + * Constructor. + * + * @param name Name of this binded operation. + * @param soapAction URL from which this functionality can be accessed at. + * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + */ + public WebserviceTypeWsdlBindedOperation(String name, String soapAction, String soapStyle) { + this.name = name; + this.soapAction = soapAction; + this.soapStyle = soapStyle; + } + + @Override + public String toString() { + return String.format("name: %s, soapAction: %s, soapStyle: %s", name, soapAction, soapStyle); + } + + /** + * @return Name of this binded operation. + */ + public String getName() { + return name; + } + + /** + * @param name Name of this binded operation. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return URL from which this functionality can be accessed at. + */ + public String getSoapAction() { + return soapAction; + } + + /** + * @param soapAction URL from which this functionality can be accessed at. + */ + public void setSoapAction(String soapAction) { + this.soapAction = soapAction; + } + + /** + * @return Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + */ + public String getSoapStyle() { + return soapStyle; + } + + /** + * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + */ + public void setSoapStyle(String soapStyle) { + this.soapStyle = soapStyle; + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBinding.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBinding.java index 3de9c8ea..bd4244b0 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBinding.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlBinding.java @@ -1,106 +1,106 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -import java.util.List; - -/** - * This is a data class for inner representation of WSDL binding element. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlBinding { - - private String name; - private String interface_; - private List bindedOperations; - - // attributes specific for SOAP XML namespace - private String soapStyle; // rpc / document (i.e. messaging) - private String soapTransport; - - /** - * - * @param name Name of this binding. - * @param interface_ Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. - * @param bindedOperations List of all operation defined in this binding (i.e. being implemented by a webservice). - * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - * @param soapTransport Definition of used transport protocol. - */ - public WebserviceTypeWsdlBinding(String name, String interface_, List bindedOperations, String soapStyle, String soapTransport) { - this.name = name; - this.interface_ = interface_; - this.bindedOperations = bindedOperations; - this.soapStyle = soapStyle; - this.soapTransport = soapTransport; - } - - /** - * @return Name of this binding. - */ - public String getName() { - return name; - } - - /** - * @param name Name of this binding. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. - */ - public String getInterface_() { - return interface_; - } - - /** - * @param interface_ Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. - */ - public void setInterface_(String interface_) { - this.interface_ = interface_; - } - - /** - * @return List of all operation defined in this binding (i.e. being implemented by a webservice). - */ - public List getBindedOperations() { - return bindedOperations; - } - - /** - * @param bindedOperations List of all operation defined in this binding (i.e. being implemented by a webservice). - */ - public void setBindedOperationNames(List bindedOperations) { - this.bindedOperations = bindedOperations; - } - - /** - * @return Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - */ - public String getSoapStyle() { - return soapStyle; - } - - /** - * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. - */ - public void setSoapStyle(String soapStyle) { - this.soapStyle = soapStyle; - } - - /** - * @return Definition of used transport protocol. - */ - public String getSoapTransport() { - return soapTransport; - } - - /** - * @param soapTransport Definition of used transport protocol. - */ - public void setSoapTransport(String soapTransport) { - this.soapTransport = soapTransport; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +import java.util.List; + +/** + * This is a data class for inner representation of WSDL binding element. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlBinding { + + private String name; + private String interface_; + private List bindedOperations; + + // attributes specific for SOAP XML namespace + private String soapStyle; // rpc / document (i.e. messaging) + private String soapTransport; + + /** + * + * @param name Name of this binding. + * @param interface_ Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. + * @param bindedOperations List of all operation defined in this binding (i.e. being implemented by a webservice). + * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + * @param soapTransport Definition of used transport protocol. + */ + public WebserviceTypeWsdlBinding(String name, String interface_, List bindedOperations, String soapStyle, String soapTransport) { + this.name = name; + this.interface_ = interface_; + this.bindedOperations = bindedOperations; + this.soapStyle = soapStyle; + this.soapTransport = soapTransport; + } + + /** + * @return Name of this binding. + */ + public String getName() { + return name; + } + + /** + * @param name Name of this binding. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. + */ + public String getInterface_() { + return interface_; + } + + /** + * @param interface_ Reference to a portType (WSDL 1.1) / interface (WSDL 2.0) definition. + */ + public void setInterface_(String interface_) { + this.interface_ = interface_; + } + + /** + * @return List of all operation defined in this binding (i.e. being implemented by a webservice). + */ + public List getBindedOperations() { + return bindedOperations; + } + + /** + * @param bindedOperations List of all operation defined in this binding (i.e. being implemented by a webservice). + */ + public void setBindedOperationNames(List bindedOperations) { + this.bindedOperations = bindedOperations; + } + + /** + * @return Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + */ + public String getSoapStyle() { + return soapStyle; + } + + /** + * @param soapStyle Either "rpc" for RPC communication pattern or "document" for messaging communication pattern. + */ + public void setSoapStyle(String soapStyle) { + this.soapStyle = soapStyle; + } + + /** + * @return Definition of used transport protocol. + */ + public String getSoapTransport() { + return soapTransport; + } + + /** + * @param soapTransport Definition of used transport protocol. + */ + public void setSoapTransport(String soapTransport) { + this.soapTransport = soapTransport; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlInterface.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlInterface.java index 3436e76c..c862ee1c 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlInterface.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlInterface.java @@ -1,55 +1,55 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -import java.util.ArrayList; -import java.util.List; - -/** - * This is a data class for inner representation of WSDL portType (WSDL 1.1) / interface (WSDL 2.0) element. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlInterface { - - private String name; - private List operations = new ArrayList<>(); - - /** - * Constructor. - * - * @param name Name of this portType (WSDL 1.1) / interface (WSDL 2.0). - * @param operations List of defined abstract operations. - */ - public WebserviceTypeWsdlInterface(String name, List operations) { - this.name = name; - this.operations = operations; - } - - /** - * @return Name of this portType (WSDL 1.1) / interface (WSDL 2.0). - */ - public String getName() { - return name; - } - - /** - * @param name Name of this portType (WSDL 1.1) / interface (WSDL 2.0). - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return List of defined abstract operations. - */ - public List getOperations() { - return operations; - } - - /** - * @param operations List of defined abstract operations. - */ - public void setOperations(List operations) { - this.operations = operations; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +import java.util.ArrayList; +import java.util.List; + +/** + * This is a data class for inner representation of WSDL portType (WSDL 1.1) / interface (WSDL 2.0) element. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlInterface { + + private String name; + private List operations = new ArrayList<>(); + + /** + * Constructor. + * + * @param name Name of this portType (WSDL 1.1) / interface (WSDL 2.0). + * @param operations List of defined abstract operations. + */ + public WebserviceTypeWsdlInterface(String name, List operations) { + this.name = name; + this.operations = operations; + } + + /** + * @return Name of this portType (WSDL 1.1) / interface (WSDL 2.0). + */ + public String getName() { + return name; + } + + /** + * @param name Name of this portType (WSDL 1.1) / interface (WSDL 2.0). + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return List of defined abstract operations. + */ + public List getOperations() { + return operations; + } + + /** + * @param operations List of defined abstract operations. + */ + public void setOperations(List operations) { + this.operations = operations; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlMessage.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlMessage.java index a772b0d4..00321052 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlMessage.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlMessage.java @@ -1,54 +1,54 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -import java.util.List; - -/** - * This is a data class for inner representation of WSDL message element (defined only in WSDL 1.1). - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlMessage { - - private String name; - private List parts; - - /** - * Constructor. - * - * @param name Name of this message. - * @param parts List of parts from which this message consists of. - */ - public WebserviceTypeWsdlMessage(String name, List parts) { - this.name = name; - this. parts = parts; - } - - /** - * @return Name of this message. - */ - public String getName() { - return name; - } - - /** - * @param name Name of this message. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return List of parts from which this message consists of. - */ - public List getParts() { - return parts; - } - - /** - * @param parts List of parts from which this message consists of. - */ - public void setParts(List parts) { - this.parts = parts; - } - -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +import java.util.List; + +/** + * This is a data class for inner representation of WSDL message element (defined only in WSDL 1.1). + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlMessage { + + private String name; + private List parts; + + /** + * Constructor. + * + * @param name Name of this message. + * @param parts List of parts from which this message consists of. + */ + public WebserviceTypeWsdlMessage(String name, List parts) { + this.name = name; + this. parts = parts; + } + + /** + * @return Name of this message. + */ + public String getName() { + return name; + } + + /** + * @param name Name of this message. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return List of parts from which this message consists of. + */ + public List getParts() { + return parts; + } + + /** + * @param parts List of parts from which this message consists of. + */ + public void setParts(List parts) { + this.parts = parts; + } + +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlOperation.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlOperation.java index 9553ca7c..d1fac7ee 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlOperation.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlOperation.java @@ -1,144 +1,144 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -/** - * This is a data class for inner representation of abstract WSDL operation element. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlOperation { - - private String name; - - private String inputName; - private String inputMessage; - private String inputElement; - - private String outputName; - private String outputMessage; - private String outputElement; - - /** - * Constructor. - * - * @param name Name of this operation. - * @param inputName Name of element representing the input structure of this operation. - * @param inputMessage Reference to a message (WSDL 1.1) representing the input structure of this operation. - * @param inputElement Reference to an element (WSDL 2.0) representing the input structure of this operation. - * @param outputName Name of element representing the output structure of this operation. - * @param outputMessage Reference to a message (WSDL 1.1) representing the output structure of this operation. - * @param outputElement Reference to an element (WSDL 2.0) representing the output structure of this operation. - */ - public WebserviceTypeWsdlOperation(String name, String inputName, String inputMessage, String inputElement, String outputName, String outputMessage, String outputElement) { - this.name = name; - this.inputName = inputName; - this.inputMessage = inputMessage; - this.inputElement = inputElement; - this.outputName = outputName; - this.outputMessage = outputMessage; - this.outputElement = outputElement; - } - - @Override - public String toString() { - return String.format("name: %s, inputName: %s, inputMessage: %s, inputElement: %s, outputName: %s, outputMessage: %s, outputElement: %s", - name, inputName, inputMessage, inputElement, outputName, outputMessage, outputElement); - } - - /** - * @return Name of this operation. - */ - public String getName() { - return name; - } - - /** - * @param name Name of this operation. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return Name of element representing the input structure of this operation. - */ - public String getInputName() { - return inputName; - } - - /** - * @param inputName Name of element representing the input structure of this operation. - */ - public void setInputName(String inputName) { - this.inputName = inputName; - } - - /** - * @return Reference to a message (WSDL 1.1) representing the input structure of this operation. - */ - public String getInputMessage() { - return inputMessage; - } - - /** - * @param inputMessage Reference to a message (WSDL 1.1) representing the input structure of this operation. - */ - public void setInputMessage(String inputMessage) { - this.inputMessage = inputMessage; - } - - /** - * @return Reference to an element (WSDL 2.0) representing the input structure of this operation. - */ - public String getInputElement() { - return inputElement; - } - - /** - * @param inputElement Reference to an element (WSDL 2.0) representing the input structure of this operation. - */ - public void setInputElement(String inputElement) { - this.inputElement = inputElement; - } - - /** - * @return Name of element representing the output structure of this operation. - */ - public String getOutputName() { - return outputName; - } - - /** - * @param outputName Name of element representing the output structure of this operation. - */ - public void setOutputName(String outputName) { - this.outputName = outputName; - } - - /** - * @return Reference to a message (WSDL 1.1) representing the output structure of this operation. - */ - public String getOutputMessage() { - return outputMessage; - } - - /** - * @param outputMessage Reference to a message (WSDL 1.1) representing the output structure of this operation. - */ - public void setOutputMessage(String outputMessage) { - this.outputMessage = outputMessage; - } - - /** - * @return Reference to an element (WSDL 2.0) representing the output structure of this operation. - */ - public String getOutputElement() { - return outputElement; - } - - /** - * @param outputElement Reference to an element (WSDL 2.0) representing the output structure of this operation. - */ - public void setOutputElement(String outputElement) { - this.outputElement = outputElement; - } -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +/** + * This is a data class for inner representation of abstract WSDL operation element. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlOperation { + + private String name; + + private String inputName; + private String inputMessage; + private String inputElement; + + private String outputName; + private String outputMessage; + private String outputElement; + + /** + * Constructor. + * + * @param name Name of this operation. + * @param inputName Name of element representing the input structure of this operation. + * @param inputMessage Reference to a message (WSDL 1.1) representing the input structure of this operation. + * @param inputElement Reference to an element (WSDL 2.0) representing the input structure of this operation. + * @param outputName Name of element representing the output structure of this operation. + * @param outputMessage Reference to a message (WSDL 1.1) representing the output structure of this operation. + * @param outputElement Reference to an element (WSDL 2.0) representing the output structure of this operation. + */ + public WebserviceTypeWsdlOperation(String name, String inputName, String inputMessage, String inputElement, String outputName, String outputMessage, String outputElement) { + this.name = name; + this.inputName = inputName; + this.inputMessage = inputMessage; + this.inputElement = inputElement; + this.outputName = outputName; + this.outputMessage = outputMessage; + this.outputElement = outputElement; + } + + @Override + public String toString() { + return String.format("name: %s, inputName: %s, inputMessage: %s, inputElement: %s, outputName: %s, outputMessage: %s, outputElement: %s", + name, inputName, inputMessage, inputElement, outputName, outputMessage, outputElement); + } + + /** + * @return Name of this operation. + */ + public String getName() { + return name; + } + + /** + * @param name Name of this operation. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return Name of element representing the input structure of this operation. + */ + public String getInputName() { + return inputName; + } + + /** + * @param inputName Name of element representing the input structure of this operation. + */ + public void setInputName(String inputName) { + this.inputName = inputName; + } + + /** + * @return Reference to a message (WSDL 1.1) representing the input structure of this operation. + */ + public String getInputMessage() { + return inputMessage; + } + + /** + * @param inputMessage Reference to a message (WSDL 1.1) representing the input structure of this operation. + */ + public void setInputMessage(String inputMessage) { + this.inputMessage = inputMessage; + } + + /** + * @return Reference to an element (WSDL 2.0) representing the input structure of this operation. + */ + public String getInputElement() { + return inputElement; + } + + /** + * @param inputElement Reference to an element (WSDL 2.0) representing the input structure of this operation. + */ + public void setInputElement(String inputElement) { + this.inputElement = inputElement; + } + + /** + * @return Name of element representing the output structure of this operation. + */ + public String getOutputName() { + return outputName; + } + + /** + * @param outputName Name of element representing the output structure of this operation. + */ + public void setOutputName(String outputName) { + this.outputName = outputName; + } + + /** + * @return Reference to a message (WSDL 1.1) representing the output structure of this operation. + */ + public String getOutputMessage() { + return outputMessage; + } + + /** + * @param outputMessage Reference to a message (WSDL 1.1) representing the output structure of this operation. + */ + public void setOutputMessage(String outputMessage) { + this.outputMessage = outputMessage; + } + + /** + * @return Reference to an element (WSDL 2.0) representing the output structure of this operation. + */ + public String getOutputElement() { + return outputElement; + } + + /** + * @param outputElement Reference to an element (WSDL 2.0) representing the output structure of this operation. + */ + public void setOutputElement(String outputElement) { + this.outputElement = outputElement; + } +} diff --git a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlPart.java b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlPart.java index 82672d3a..bd05a8b5 100644 --- a/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlPart.java +++ b/modules/crce-webservices-indexer/src/main/java/cz/zcu/kiv/crce/webservices/indexer/structures/wsdl/WebserviceTypeWsdlPart.java @@ -1,68 +1,68 @@ -package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; - -/** - * This is a data class for inner representation of WSDL part element. - * - * @author David Pejrimovsky (maxidejf@gmail.com) - */ -public class WebserviceTypeWsdlPart { - - private String name; - private String type; - private String element; - - /** - * Constructor. - * - * @param name Name of this part. - * @param type Datatype of a parameter (in case of RPC communication pattern). - * @param element Reference to a grammar definition (in case of messaging communication pattern). - */ - public WebserviceTypeWsdlPart(String name, String type, String element) { - this.name = name; - this.type = type; - this.element = element; - } - - /** - * @return Name of this part. - */ - public String getName() { - return name; - } - - /** - * @param name Name of this part. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return Datatype of a parameter (in case of RPC communication pattern). - */ - public String getType() { - return type; - } - - /** - * @param type Datatype of a parameter (in case of RPC communication pattern). - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return Reference to a grammar definition (in case of messaging communication pattern). - */ - public String getElement() { - return element; - } - - /** - * @param element Reference to a grammar definition (in case of messaging communication pattern). - */ - public void setElement(String element) { - this.element = element; - } -} +package cz.zcu.kiv.crce.webservices.indexer.structures.wsdl; + +/** + * This is a data class for inner representation of WSDL part element. + * + * @author David Pejrimovsky (maxidejf@gmail.com) + */ +public class WebserviceTypeWsdlPart { + + private String name; + private String type; + private String element; + + /** + * Constructor. + * + * @param name Name of this part. + * @param type Datatype of a parameter (in case of RPC communication pattern). + * @param element Reference to a grammar definition (in case of messaging communication pattern). + */ + public WebserviceTypeWsdlPart(String name, String type, String element) { + this.name = name; + this.type = type; + this.element = element; + } + + /** + * @return Name of this part. + */ + public String getName() { + return name; + } + + /** + * @param name Name of this part. + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return Datatype of a parameter (in case of RPC communication pattern). + */ + public String getType() { + return type; + } + + /** + * @param type Datatype of a parameter (in case of RPC communication pattern). + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return Reference to a grammar definition (in case of messaging communication pattern). + */ + public String getElement() { + return element; + } + + /** + * @param element Reference to a grammar definition (in case of messaging communication pattern). + */ + public void setElement(String element) { + this.element = element; + } +} diff --git a/modules/crce-webservices-indexer/src/test/java/cz/zcu/kiv/crce/AppTest.java b/modules/crce-webservices-indexer/src/test/java/cz/zcu/kiv/crce/AppTest.java index 65a93109..2fdd41c8 100644 --- a/modules/crce-webservices-indexer/src/test/java/cz/zcu/kiv/crce/AppTest.java +++ b/modules/crce-webservices-indexer/src/test/java/cz/zcu/kiv/crce/AppTest.java @@ -1,38 +1,38 @@ -package cz.zcu.kiv.crce; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} +package cz.zcu.kiv.crce; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/modules/crce-webui/osgi.bnd b/modules/crce-webui/osgi.bnd index 278c9bfc..acb42322 100644 --- a/modules/crce-webui/osgi.bnd +++ b/modules/crce-webui/osgi.bnd @@ -1,40 +1,40 @@ -#----------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the bundle -#----------------------------------------------------------------- - -Bundle-Version>: \ - ${pom.version} - -Bundle-SymbolicName: \ - ${bundle.symbolicName} - -Bundle-Name: CRCE - Web UI - -Bundle-Activator: ${bundle.namespace}.internal.Activator - -Export-Package: - -Import-Package: \ - javax.servlet, \ - javax.servlet.http, \ - javax.servlet.*, \ - javax.servlet.jsp.*, \ - javax.servlet.jsp.jstl.*, \ - javax.xml.parsers, \ - javax.xml.namespace, \ - javax.xml.xpath, \ - org.osgi.framework, \ - org.osgi.service.log, \ - org.osgi.service.useradmin, \ - org.xml.sax, \ - org.w3c.dom, \ - cz.zcu.kiv.crce.metadata, \ - * - -Dynamic-ImportPackage: * - -Bundle-ClassPath: .,WEB-INF/classes - -Web-ContextPath: crce - -Webapp-Context: crce +#----------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the bundle +#----------------------------------------------------------------- + +Bundle-Version>: \ + ${pom.version} + +Bundle-SymbolicName: \ + ${bundle.symbolicName} + +Bundle-Name: CRCE - Web UI + +Bundle-Activator: ${bundle.namespace}.internal.Activator + +Export-Package: + +Import-Package: \ + javax.servlet, \ + javax.servlet.http, \ + javax.servlet.*, \ + javax.servlet.jsp.*, \ + javax.servlet.jsp.jstl.*, \ + javax.xml.parsers, \ + javax.xml.namespace, \ + javax.xml.xpath, \ + org.osgi.framework, \ + org.osgi.service.log, \ + org.osgi.service.useradmin, \ + org.xml.sax, \ + org.w3c.dom, \ + cz.zcu.kiv.crce.metadata, \ + * + +Dynamic-ImportPackage: * + +Bundle-ClassPath: .,WEB-INF/classes + +Web-ContextPath: crce + +Webapp-Context: crce diff --git a/modules/crce-webui/pom.xml b/modules/crce-webui/pom.xml index 12df6c30..3a5fee27 100644 --- a/modules/crce-webui/pom.xml +++ b/modules/crce-webui/pom.xml @@ -1,182 +1,202 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-webui - war - - CRCE - Web UI - - - ${namespace}.webui - ${namespace}.webui - - - - - - - - com.lukegb.mojo - gitdescribe-maven-plugin - 3.0 - - - - gitdescribe - - git-describe - initialize - - - --tags - - - - - - - maven-war-plugin - - - %regex[WEB-INF/lib/(?!jstl-|standard-).*.jar] - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - ${project.parent.version} - ${describe} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - bundle-manifest - process-classes - - manifest - - - - - - - - - - jar - bundle - war - - - - - - - - - - - - - - - - - javax.servlet - servlet-api - - - javax.servlet - jsp-api - - - commons-fileupload - commons-fileupload - - - commons-io - commons-io - - - taglibs - c - 1.1.2 - tld - runtime - - - taglibs - standard - 1.1.2 - - - javax.servlet - jstl - 1.2 - - - - - - ${project.groupId} - crce-core - pom - - - - ${project.groupId} - crce-metadata-osgi-bundle - ${project.version} - - - ${project.groupId} - crce-compatibility-api - ${project.version} - - - - - - junit - junit - - - org.openengsb.wrapped - net.sourceforge.htmlunit-all - 2.8.w1 - bundle - test - - - - - javax.ws.rs - javax.ws.rs-api - - - org.glassfish.jersey.containers - jersey-container-servlet-core - - - org.glassfish.jersey.media - jersey-media-multipart - - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-webui + war + + CRCE - Web UI + + + ${namespace}.webui + ${namespace}.webui + + + + + + + + com.lukegb.mojo + gitdescribe-maven-plugin + 3.0 + + + + gitdescribe + + git-describe + initialize + + + --tags + + + + + + + maven-war-plugin + + + %regex[WEB-INF/lib/(?!jstl-|standard-).*.jar] + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + ${project.parent.version} + ${describe} + + + + + + org.apache.felix + maven-bundle-plugin + true + + + + bundle-manifest + process-classes + + manifest + + + + + + + + + + jar + bundle + war + + + + + + + + + + + + + + + + + javax.servlet + servlet-api + + + javax.servlet + jsp-api + + + commons-fileupload + commons-fileupload + + + commons-io + commons-io + + + taglibs + c + 1.1.2 + tld + runtime + + + taglibs + standard + 1.1.2 + + + javax.servlet + jstl + 1.2 + + + + + + ${project.groupId} + crce-core + pom + + + + ${project.groupId} + crce-metadata-osgi-bundle + ${project.version} + + + ${project.groupId} + crce-compatibility-api + ${project.version} + + + ${project.groupId} + crce-mvn-plugin + ${project.version} + + + + + + junit + junit + + + org.openengsb.wrapped + net.sourceforge.htmlunit-all + 2.8.w1 + bundle + test + + + + + javax.ws.rs + javax.ws.rs-api + + + org.glassfish.jersey.containers + jersey-container-servlet-core + + + org.glassfish.jersey.media + jersey-media-multipart + + + + + org.glassfish.jersey.media + jersey-media-moxy + + + org.glassfish.jersey.core + jersey-client + + + org.eclipse.persistence + org.eclipse.persistence.moxy + 2.6.4 + + + + + diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Activator.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Activator.java index e0835f03..10cb18f4 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Activator.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Activator.java @@ -1,177 +1,177 @@ -package cz.zcu.kiv.crce.webui.internal; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Nonnull; -import javax.servlet.http.HttpServletRequest; - -import org.apache.felix.dm.DependencyActivatorBase; -import org.apache.felix.dm.DependencyManager; -import org.osgi.framework.BundleContext; -import org.osgi.service.blueprint.container.ServiceUnavailableException; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; -import cz.zcu.kiv.crce.metadata.MetadataFactory; -import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; -import cz.zcu.kiv.crce.metadata.service.MetadataService; -import cz.zcu.kiv.crce.plugin.PluginManager; -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.SessionRegister; -import cz.zcu.kiv.crce.repository.Store; - -/** - * Activator of this bundle - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -@SuppressWarnings("FinalClass") -public final class Activator extends DependencyActivatorBase { - - private static final Logger logger = LoggerFactory.getLogger(Activator.class); - - private static volatile Activator instance; - - // injected by dependency manager: - private volatile BundleContext bundleContext; - private volatile MetadataFactory metadataFactory; - private volatile ResourceDAO resourceDAO; - private volatile PluginManager pluginManager; - private volatile SessionRegister sessionRegister; - private volatile MetadataService metadataService; - private volatile CompatibilitySearchService compatibilityService; - - public static Activator instance() { - if (instance == null) { - throw new IllegalStateException("Activator instance is null."); - } - return instance; - } - - public PluginManager getPluginManager() { - return pluginManager; - } - - public SessionRegister getSessionRegister() { - if (sessionRegister == null) { - throw new IllegalStateException("sessionRegister is null."); - } - return sessionRegister; - } - - public ResourceDAO getResourceDAO() { - return resourceDAO; - } - - public MetadataFactory getMetadataFactory() { - return metadataFactory; - } - - /** - * - * @return Map of repository ID to repository name. - */ - @Nonnull - public Map getRepositories() { - Map stores = new HashMap<>(); - - Collection> serviceReferences; - try { - serviceReferences = bundleContext.getServiceReferences(Store.class, null); - } catch (InvalidSyntaxException e) { - logger.error("Invalid filter.", e); // this should not happen - return stores; - } - - if (serviceReferences == null) { - logger.trace("No stores found."); - return stores; - } - - for (ServiceReference serviceReference : serviceReferences) { - String id = (String) serviceReference.getProperty("id"); - String name = (String) serviceReference.getProperty("name"); - if (id != null) { - stores.put(id, name != null ? name : id); - } - } - - return stores; - } - - public Store getStore(String repositoryId) { - String filter = "(id=" + repositoryId + ")"; - - Collection> serviceReferences; - try { - serviceReferences = bundleContext.getServiceReferences(Store.class, filter); - } catch (InvalidSyntaxException ex) { - logger.error("Invalid filter: " + filter); - return null; - } - - if (serviceReferences == null || serviceReferences.isEmpty()) { - logger.warn("Store not found for repository ID: {}", repositoryId); - return null; - } - - if (serviceReferences.size() > 1) { - logger.warn("More than one stores found for repository ID: {}, using the first one.", repositoryId); - } - - return bundleContext.getService(serviceReferences.iterator().next()); - } - - public CompatibilitySearchService getCompatibilityService() { - if(compatibilityService != null) { - return compatibilityService; - } else { - throw new ServiceUnavailableException("This installation does not support compatibility services!", ""); - } - } - - public boolean isCompatibilityServicePresent() { - return compatibilityService != null; - } - - public Buffer getBuffer(HttpServletRequest req) { - if (req == null) { - return null; - } - - String sid = req.getSession(true).getId(); - return sessionRegister.getSessionData(sid).getBuffer(); - } - - public MetadataService getMetadataService() { - return metadataService; - } - - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Workaround for providing DM components.") - @Override - public void init(BundleContext context, DependencyManager manager) throws Exception { - instance = this; - - manager.add(createComponent() - .setImplementation(this) - .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) - .add(createServiceDependency().setService(PluginManager.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) - .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) - .add(createServiceDependency().setService(CompatibilitySearchService.class).setRequired(false)) // FIXME 'not required' is only a temporary solution to make the component startable - ); - - - logger.debug("WebUI activator initialized."); - } - - @Override - public void destroy(BundleContext context, DependencyManager manager) throws Exception { - // nothing to do - } -} +package cz.zcu.kiv.crce.webui.internal; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nonnull; +import javax.servlet.http.HttpServletRequest; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; +import org.osgi.service.blueprint.container.ServiceUnavailableException; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.service.CompatibilitySearchService; +import cz.zcu.kiv.crce.metadata.MetadataFactory; +import cz.zcu.kiv.crce.metadata.dao.ResourceDAO; +import cz.zcu.kiv.crce.metadata.service.MetadataService; +import cz.zcu.kiv.crce.plugin.PluginManager; +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.SessionRegister; +import cz.zcu.kiv.crce.repository.Store; + +/** + * Activator of this bundle + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +@SuppressWarnings("FinalClass") +public final class Activator extends DependencyActivatorBase { + + private static final Logger logger = LoggerFactory.getLogger(Activator.class); + + private static volatile Activator instance; + + // injected by dependency manager: + private volatile BundleContext bundleContext; + private volatile MetadataFactory metadataFactory; + private volatile ResourceDAO resourceDAO; + private volatile PluginManager pluginManager; + private volatile SessionRegister sessionRegister; + private volatile MetadataService metadataService; + private volatile CompatibilitySearchService compatibilityService; + + public static Activator instance() { + if (instance == null) { + throw new IllegalStateException("Activator instance is null."); + } + return instance; + } + + public PluginManager getPluginManager() { + return pluginManager; + } + + public SessionRegister getSessionRegister() { + if (sessionRegister == null) { + throw new IllegalStateException("sessionRegister is null."); + } + return sessionRegister; + } + + public ResourceDAO getResourceDAO() { + return resourceDAO; + } + + public MetadataFactory getMetadataFactory() { + return metadataFactory; + } + + /** + * + * @return Map of repository ID to repository name. + */ + @Nonnull + public Map getRepositories() { + Map stores = new HashMap<>(); + + Collection> serviceReferences; + try { + serviceReferences = bundleContext.getServiceReferences(Store.class, null); + } catch (InvalidSyntaxException e) { + logger.error("Invalid filter.", e); // this should not happen + return stores; + } + + if (serviceReferences == null) { + logger.trace("No stores found."); + return stores; + } + + for (ServiceReference serviceReference : serviceReferences) { + String id = (String) serviceReference.getProperty("id"); + String name = (String) serviceReference.getProperty("name"); + if (id != null) { + stores.put(id, name != null ? name : id); + } + } + + return stores; + } + + public Store getStore(String repositoryId) { + String filter = "(id=" + repositoryId + ")"; + + Collection> serviceReferences; + try { + serviceReferences = bundleContext.getServiceReferences(Store.class, filter); + } catch (InvalidSyntaxException ex) { + logger.error("Invalid filter: " + filter); + return null; + } + + if (serviceReferences == null || serviceReferences.isEmpty()) { + logger.warn("Store not found for repository ID: {}", repositoryId); + return null; + } + + if (serviceReferences.size() > 1) { + logger.warn("More than one stores found for repository ID: {}, using the first one.", repositoryId); + } + + return bundleContext.getService(serviceReferences.iterator().next()); + } + + public CompatibilitySearchService getCompatibilityService() { + if(compatibilityService != null) { + return compatibilityService; + } else { + throw new ServiceUnavailableException("This installation does not support compatibility services!", ""); + } + } + + public boolean isCompatibilityServicePresent() { + return compatibilityService != null; + } + + public Buffer getBuffer(HttpServletRequest req) { + if (req == null) { + return null; + } + + String sid = req.getSession(true).getId(); + return sessionRegister.getSessionData(sid).getBuffer(); + } + + public MetadataService getMetadataService() { + return metadataService; + } + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Workaround for providing DM components.") + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + instance = this; + + manager.add(createComponent() + .setImplementation(this) + .add(createServiceDependency().setService(SessionRegister.class).setRequired(true)) + .add(createServiceDependency().setService(PluginManager.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataFactory.class).setRequired(true)) + .add(createServiceDependency().setService(MetadataService.class).setRequired(true)) + .add(createServiceDependency().setService(CompatibilitySearchService.class).setRequired(false)) // FIXME 'not required' is only a temporary solution to make the component startable + ); + + + logger.debug("WebUI activator initialized."); + } + + @Override + public void destroy(BundleContext context, DependencyManager manager) throws Exception { + // nothing to do + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Helper.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Helper.java index bc4ea5ed..805d0ef4 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Helper.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/Helper.java @@ -1,26 +1,26 @@ -package cz.zcu.kiv.crce.webui.internal; - -import java.io.IOException; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author kalwi - */ -public class Helper { - - private static final Logger logger = LoggerFactory.getLogger(Helper.class); - - public static void forwardTo(String url, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - logger.debug("Forwarding to: " + url); - - RequestDispatcher rd = req.getRequestDispatcher(url); - rd.forward(req, res); - } -} +package cz.zcu.kiv.crce.webui.internal; + +import java.io.IOException; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author kalwi + */ +public class Helper { + + private static final Logger logger = LoggerFactory.getLogger(Helper.class); + + public static void forwardTo(String url, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + logger.debug("Forwarding to: " + url); + + RequestDispatcher rd = req.getRequestDispatcher(url); + rd.forward(req, res); + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/MavenServlet.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/MavenServlet.java new file mode 100644 index 00000000..b9b4c93c --- /dev/null +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/MavenServlet.java @@ -0,0 +1,280 @@ +package cz.zcu.kiv.crce.webui.internal; + +import cz.zcu.kiv.crce.mvn.plugin.search.Configurable; +import cz.zcu.kiv.crce.mvn.plugin.search.FoundArtifact; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.MavenResolver; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.VersionFilter; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.central.rest.CentralMavenRestLocator; +import cz.zcu.kiv.crce.mvn.plugin.search.impl.resolver.MavenAetherResolver; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** + * A servlet for maven search page. + * + * Created by Zdenek Vales on 11.4.2017. + */ +public class MavenServlet extends HttpServlet { + + private static final long serialVersionUID = -7359560802939893940L; + + private static final Logger logger = LoggerFactory.getLogger(MavenServlet.class); + + public static final String COORDINATES_FEEDBACK = "coordFeedback"; + public static final String PACKAGE_NAME_FEEDBACK = "packageFeedback"; + public static final String MAIN_FEEDBACK = "mainFeedback"; + public static final String CONF_FEEDBACK = "confFeedback"; + + public static final String LOWEST_VERSION = "lv"; + public static final String HIGHEST_VERSION = "hv"; + public static final String NO_VERSION_FILTER = "no-v"; + + public static final String NO_GROUP_ID_FILTER = "no-gid"; + public static final String HIGHEST_GROUP_ID = "h-match"; + public static final String MANUAL_GROUP_ID = "manual-gid"; + public static final String MANUAL_GROUP_ID_VAL = "manual-gid-val"; + + // those correspond with name attribute of html input element + public static final String GROUP_ID_PARAM = "gid"; + public static final String ARTIFACT_ID_PARAM = "aid"; + public static final String VERSION_PARAM = "ver"; + public static final String PACKAGE_NAME_PARAM = "pname"; + public static final String PACKAGE_VERSION_FILTER = "package-ver-filter"; + public static final String COORD_VERSION_FILTER = "coord-ver-filter"; + public static final String GROUP_FILTER_PARAM_NAME = "gid-filter"; + public static final String RESOLVER_CONFIGRATION = "resolver-conf-file"; + + // 'search' button names + public static final String COORD_SEARCH = "coord-search"; + public static final String PACKAGE_SEARCH = "package-search"; + + private Map parameters; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + // do nothing and display the maven search page + req.getRequestDispatcher("resource?link=maven").forward(req, resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + MavenLocator locator = new CentralMavenRestLocator(); + MavenAetherResolver resolver = new MavenAetherResolver(); + + // first of all load configuration if needed + loadConfiguration(req, resp, resolver); + + // search by coordinates or package name? + if(parameters.containsKey(COORD_SEARCH)) { + searchByCoordinates(req, resp, locator, resolver); + } else if (parameters.containsKey(PACKAGE_SEARCH)) { + searchByPackageName(req, resp, locator, resolver); + } else { + String msg = "Unknown action."; + logger.debug(msg); + displayFeedback(req, resp, MAIN_FEEDBACK, msg); + return; + } + } + + /** + * Check if any configuration files were uploaded and reconfigure components. + * Uses apache commons library to get the uploadded file and must be called before any + * 'getParameter()' method is called on the request object. + * + * @param req Request. + * @param resp Response. + */ + private void loadConfiguration(HttpServletRequest req, HttpServletResponse resp, Configurable resolver) throws ServletException, IOException { + parameters = new HashMap<>(); + try { + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); + for(FileItem fi : items) { + if(!fi.isFormField()) { + String fieldName = fi.getFieldName(); + if(fieldName.equals(RESOLVER_CONFIGRATION)) { + // load configuration file for resolver + InputStream is = fi.getInputStream(); + resolver.reconfigure(is); + is.close(); + } + } else { + // normal parameter + String fieldName = fi.getFieldName(); + String fieldValue = fi.getString(); + parameters.put(fieldName, fieldValue); + } + } + } catch (FileUploadException | IOException e) { + logger.error("Exception while getting the uploaded file: "+e.getMessage()); + displayFeedback(req, resp, CONF_FEEDBACK, "Error while getting uploaded configuration file."); + return; + } + } + + /** + * Handles searching by maven coordinates. + */ + private void searchByCoordinates(HttpServletRequest req, HttpServletResponse resp, MavenLocator locator, MavenResolver resolver) throws ServletException, IOException { + String gid = parameters.get(GROUP_ID_PARAM); + String aid = parameters.get(ARTIFACT_ID_PARAM); + String ver = parameters.get(VERSION_PARAM); + String verFilter = parameters.get(COORD_VERSION_FILTER); + VersionFilter vf = VersionFilter.HIGHEST_ONLY; + logger.debug("Searching for maven artifacts by coordinates: gid={}; aid={}; version={}",gid, aid, ver); + + // check parameters + if( gid == null || gid.isEmpty() || + aid == null || aid.isEmpty() || + (ver == null || ver.isEmpty()) && verFilter.equals(NO_VERSION_FILTER) + ) { + logger.warn("Not all parameters were specified."); + displayFeedback(req, resp, COORDINATES_FEEDBACK, "Group Id, artifact Id or version is missing."); + return; + } + + // perform search + Collection foundArtifacts = new ArrayList<>(); + if(ver == null || ver.isEmpty() || !verFilter.equals(NO_VERSION_FILTER)) { + foundArtifacts = locator.locate(gid, aid); + if(verFilter.equals(LOWEST_VERSION)) { + vf = VersionFilter.LOWEST_ONLY; + } + foundArtifacts = locator.filter(foundArtifacts, vf); + } else { + foundArtifacts.add(locator.locate(gid, aid, ver)); + } + + if(foundArtifacts.isEmpty()) { + logger.warn("No artifact found..."); + displayFeedback(req, resp, MAIN_FEEDBACK, "0 artifacts found."); + return; + } + + Collection resolvedArtifacts = resolver.resolveArtifacts(foundArtifacts); + if(resolvedArtifacts == null) { + // this really shouldn't happen + displayFeedback(req, resp, MAIN_FEEDBACK, "Error while resolving artifact."); + return; + } + + // upload to buffer + addResolvedArtifactsToBuffer(req, resp, resolvedArtifacts); + } + + /** + * Handles searching by package name. + */ + private void searchByPackageName(HttpServletRequest req, HttpServletResponse resp, MavenLocator locator, MavenResolver resolver) throws ServletException, IOException { + logger.debug("Searching for maven artifacts by package name..."); + String packageName = parameters.get(PACKAGE_NAME_PARAM); + String versionFilter = parameters.get(PACKAGE_VERSION_FILTER); + String groupIdFilter = parameters.get(GROUP_FILTER_PARAM_NAME); + String manualG = ""; + + logger.debug("Package name: "+packageName+"; version filter: "+versionFilter+"; groupId filter: "+groupIdFilter); + + // check parameters + if( packageName == null || packageName.isEmpty() || + versionFilter == null || versionFilter.isEmpty() || + groupIdFilter == null || groupIdFilter.isEmpty()) { + // todo: display some error message? + logger.warn("Package name, version filter or group id filter not specified."); + displayFeedback(req, resp, PACKAGE_NAME_FEEDBACK, "Package name, version filter or group id filter is missing."); + return; + } + + if(groupIdFilter.equals(MANUAL_GROUP_ID)) { + manualG = parameters.get(MANUAL_GROUP_ID_VAL); + if(manualG == null || manualG.isEmpty()) { + logger.warn("Manual groupId filter si missing."); + displayFeedback(req, resp, PACKAGE_NAME_FEEDBACK, "Value for manual groupId filter is missing"); + return; + } else { + logger.debug("Value of manual groupId filter: "+manualG); + } + } + + // perform search + Collection foundArtifacts = new ArrayList<>(); + switch (groupIdFilter) { + case NO_GROUP_ID_FILTER: + foundArtifacts = locator.locate(packageName); + break; + + case HIGHEST_GROUP_ID: + foundArtifacts = locator.locate(packageName, true); + break; + + case MANUAL_GROUP_ID: + foundArtifacts = locator.locate(packageName, manualG, false); + break; + + default: + foundArtifacts = locator.locate(packageName, true); + } + + // version filtering + VersionFilter vf = VersionFilter.HIGHEST_ONLY; + if(versionFilter.equals(LOWEST_VERSION)) { + vf = VersionFilter.LOWEST_ONLY; + } + foundArtifacts = locator.filter(foundArtifacts, vf); + Collection resolvedArtifacts = resolver.resolveArtifacts(foundArtifacts); + if(resolvedArtifacts == null) { + // this really shouldn't happen + logger.warn("Artifact couldn't been resolved."); + displayFeedback(req, resp, PACKAGE_NAME_FEEDBACK, "Error while locating artifacts."); + return; + } + + // upload to buffer + addResolvedArtifactsToBuffer(req, resp, resolvedArtifacts); + } + + private void addResolvedArtifactsToBuffer(HttpServletRequest req, HttpServletResponse resp, Collection resolvedArtifacts) throws IOException, ServletException { + logger.debug(resolvedArtifacts.size()+" artifacts resolved."); + int bufferCounter = 0; + for(File resolvedArtifact : resolvedArtifacts) { + FileInputStream fi = new FileInputStream(resolvedArtifact); + try { + Activator.instance().getBuffer(req).put(resolvedArtifact.getName(), fi); + bufferCounter++; + } catch (RefusedArtifactException e) { + logger.warn("Artifact revoked: ", e.getMessage()); + displayFeedback(req, resp, PACKAGE_NAME_FEEDBACK, "Error while putting artifact to buffer."); + return; + } finally { + fi.close(); + } + } + + displayFeedback(req, resp, MAIN_FEEDBACK, bufferCounter+" artifact(s) resolved"); + } + + /** + * Sets the feedback attribute and redirects to maven search page immediately. + * @param feedbackName Name of the feedback. + * @param feedback Feedback to be displayed + */ + private void displayFeedback(HttpServletRequest req, HttpServletResponse resp, String feedbackName, String feedback) throws ServletException, IOException { + req.setAttribute(feedbackName, feedback); + req.getRequestDispatcher("resource?link=maven").forward(req, resp); + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/ResourceServlet.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/ResourceServlet.java index f39a759f..5f406939 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/ResourceServlet.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/ResourceServlet.java @@ -1,389 +1,394 @@ -package cz.zcu.kiv.crce.webui.internal; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.CheckForNull; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.compatibility.Compatibility; -import cz.zcu.kiv.crce.compatibility.CompatibilityVersionComparator; -import cz.zcu.kiv.crce.metadata.Requirement; -import cz.zcu.kiv.crce.metadata.Resource; -import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; -import cz.zcu.kiv.crce.metadata.type.Version; -import cz.zcu.kiv.crce.plugin.Plugin; -import cz.zcu.kiv.crce.webui.internal.bean.Category; -import cz.zcu.kiv.crce.webui.internal.custom.ResourceExt; - -public class ResourceServlet extends HttpServlet { - - private static final long serialVersionUID = -4218424299866417104L; - - private static final Logger logger = LoggerFactory.getLogger(ResourceServlet.class); - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - String source = (String) req.getSession().getAttribute("source"); - logger.debug("Resource servlet POST source: {}", source); - - //if form was submit, set session parameters{ - if ("yes".equalsIgnoreCase(req.getParameter("showStoreTag"))) { - req.getSession().setAttribute("showStoreTag", "yes"); - logger.debug("showStoreTag session attribute set to yes"); - } else { - req.getSession().setAttribute("showStoreTag", "no"); - logger.debug("showStoreTag session attribute set to no"); - } - - if ("yes".equalsIgnoreCase(req.getParameter("showBufferTag"))) { - req.getSession().setAttribute("showBufferTag", "yes"); - logger.debug("showBufferTag session attribute set to yes"); - } else { - req.getSession().setAttribute("showBufferTag", "no"); - logger.debug("showBufferTag session attribute set to no"); - } - - if ("upload".equals(source) || "commit".equals(source)) { - doGet(req, resp); - } else { - String filter = req.getParameter("filter"); - if (filter != null && !filter.isEmpty()) { - - logger.warn("LDAP filter is not supported yet with new Metadata API, returning all resources for filter: {}", filter); - - fillSession(source, req, null); // TODO there was filter instead of null in implementation with old metadata - req.getRequestDispatcher("jsp/" + source + ".jsp").forward(req, resp); - } else { - doGet(req, resp); - } - } - - - - - - -// else if (req.getParameter("repositorySelection") != null) { -// req.getSession().setAttribute("repositoryId", req.getParameter("repositorySelection")); -// } - - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) { - - String link = null; - - if (req.getParameter("link") != null) { - link = req.getParameter("link"); - } - - try { - if (fillSession(link, req, null)) { - //resp.sendRedirect("jsp/"+link+".jsp"); - req.getRequestDispatcher("jsp/" + link + ".jsp").forward(req, resp); - } else { - logger.debug("Default forward"); - req.getRequestDispatcher("resource?link=store").forward(req, resp); - } - - } catch (ServletException e) { - logger.warn("Can't forward: {}", e); - } catch (IOException e) { - logger.error("Can't forward", e); - } - } - - public static void cleanSession(HttpSession session) { - session.removeAttribute("resources"); - session.removeAttribute("plugins"); - session.removeAttribute("store"); - } - - public static void setError(HttpSession session, boolean success, String message) { - session.setAttribute("success", success); - session.setAttribute("message", message); - } - - private boolean fillSession(String link, HttpServletRequest req, Requirement filter) { - - String errorMessage = filter + " is not a valid filter"; - HttpSession session = req.getSession(); - cleanSession(session); - if (link == null) { - return false; - } - - Set> repositories = Activator.instance().getRepositories().entrySet(); - session.setAttribute("showRepositorySelection", repositories.size() > 1); // TODO this logic should be in header.jsp - session.setAttribute("repositories", repositories); - session.setAttribute("repositoryId", getRepositoryId(req)); - - switch (link) { - case "buffer": { - List resources; - if (filter == null) { - resources = Activator.instance().getBuffer(req).getResources(); - } else { - try { - resources = Activator.instance().getBuffer(req).getResources(filter); - } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? - setError(session, false, errorMessage); - resources = Activator.instance().getBuffer(req).getResources(); - } - } - List bufferResourcesExt = new ArrayList<>(resources.size()); - for (Resource resource : resources) { - bufferResourcesExt.add(new ResourceExt(resource, Activator.instance().getMetadataService())); - } - session.setAttribute("buffer", bufferResourcesExt); - return true; - } - - case "plugins": { - List plugins; - if (filter == null) { - plugins = Activator.instance().getPluginManager().getPlugins(); - } else { - plugins = Activator.instance().getPluginManager().getPlugins(); - logger.warn("Filtering plugins with new Metadata API is not supported yet, returning all plugins."); -// plugins = Activator.instance().getPluginManager().getPlugins(Plugin.class, filter); - } - List pluginWrappers = new ArrayList<>(plugins.size()); - for (Plugin plugin : plugins) { - pluginWrappers.add(new cz.zcu.kiv.crce.webui.internal.custom.Plugin(plugin)); - } - session.setAttribute("plugins", pluginWrappers); - return true; - } - - case "store": { - String id = getRepositoryId(req); - if (id == null) { - return true; - } - List resources; - if (filter == null) { - resources = Activator.instance().getStore(id).getResources(); - } else { - try { - resources = Activator.instance().getStore(id).getResources(filter); - } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? - setError(session, false, errorMessage); - resources = Activator.instance().getStore(id).getResources(); - } - } - List storeResourcesExt = new ArrayList<>(resources.size()); - for (Resource resource : resources) { - storeResourcesExt.add(new ResourceExt(resource, Activator.instance().getMetadataService())); - } - session.setAttribute("store", storeResourcesExt); - return true; - } - - case "tags": { - List resources = prepareResources(req, filter); - ArrayList categoryList = prepareCategoryList(resources); - ArrayList filteredResourceList; - - String selectedCategory; - if (req.getParameter("tag") != null) { - selectedCategory = req.getParameter("tag"); - - filteredResourceList = filterResources(selectedCategory, resources); - - } else { - filteredResourceList = null; - } - - session.setAttribute("resources", filteredResourceList); - session.setAttribute("categoryList", categoryList); - - return true; - } - - case "compatibility": { - String name = req.getParameter("name"); - String version = req.getParameter("version"); - String id = getRepositoryId(req); - - List lower = null; - List upper = null; - - if (name == null || name.isEmpty() || version == null || version.isEmpty() || id == null) { - session.setAttribute("nodata", true); - return true; - } - session.setAttribute("nodata", false); - - Requirement resFilter = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); - resFilter.addAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, name); - Version v = new Version(version); - resFilter.addAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, v); - - List res = Activator.instance().getStore(id).getResources(resFilter); - if (!res.isEmpty()) { - lower = Activator.instance().getCompatibilityService().listLowerCompatibilities(res.get(0)); - Collections.sort(lower, CompatibilityVersionComparator.getBaseComparator()); - - upper = Activator.instance().getCompatibilityService().listUpperCompatibilities(res.get(0)); - Collections.sort(upper, CompatibilityVersionComparator.getUpperComparator()); - - } - - session.setAttribute("pivotName", name); - session.setAttribute("pivotVersion", version); - session.setAttribute("lower", lower); - session.setAttribute("upper", upper); - - return true; - } - - default: - return false; - } - } - - /** - * Prepare resource array. Resource array is created from store and buffer. Store resources are added, if request parameter - * store is "yes". Buffer resources are added, if request parameter - * buffer is "yes". - * - * @param req request with parameters - * @param filter possible filter of resources - * @return array of resources - */ - private List prepareResources(HttpServletRequest req, Requirement filter) { - HttpSession session = req.getSession(); - - List storeResources = Collections.emptyList(); - List bufferResources = Collections.emptyList(); - - String id = getRepositoryId(req); - if (id != null && "yes".equalsIgnoreCase((String) session.getAttribute("showStoreTag"))) { - if (filter == null) { - storeResources = Activator.instance().getStore(id).getResources(); - } else { - try { - storeResources = Activator.instance().getStore(id).getResources(filter); - } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? - logger.warn("Invalid syntax", e); - setError(session, false, filter + " is not a valid filter"); - storeResources = Activator.instance().getStore(id).getResources(); - } - } - } - - if ("yes".equals((String) session.getAttribute("showBufferTag"))) { - if (filter == null) { - bufferResources = Activator.instance().getBuffer(req).getResources(); - } else { - try { - bufferResources = Activator.instance().getBuffer(req).getResources(filter); - } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? - logger.warn("Invalid syntax", e); - setError(session, false, filter + " is not a valid filter"); - bufferResources = Activator.instance().getBuffer(req).getResources(); - } - } - } - - //merge two resources arrays - List resources = new ArrayList<>(storeResources.size() + bufferResources.size()); - resources.addAll(storeResources); - resources.addAll(bufferResources); - - return resources; - } - - /** - * Prepare list of categories (tags) that are on all resources in the store. Category is represented by name and the number of - * occurrences. - * - * @param resources - all resources from the store - * @return array list of categories - */ - private ArrayList prepareCategoryList(List resources) { - - HashMap categoryMap = new HashMap<>(); - - for (Resource resource : resources) { - List categories = Activator.instance().getMetadataService().getCategories(resource); - for (String category : categories) { - if (categoryMap.containsKey(category)) { - //category is already contained, increase count - categoryMap.put(category, categoryMap.get(category) + 1); - } else { - //add new category - categoryMap.put(category, 1); - } - } - } - - ArrayList categoryList = new ArrayList<>(); - - //Get categories from map to list - for (Map.Entry entry : categoryMap.entrySet()) { - Category newCategory = new Category(entry.getKey()); - newCategory.setCount(entry.getValue()); - categoryList.add(newCategory); - } - - //sort category list - Collections.sort(categoryList); - - return categoryList; - - - } - - /** - * Filter resources according some category. Output list contains only resources that have required category. - * - * @param filterCategory required category - * @param resources resources - * @return filtered resources list - */ - private ArrayList filterResources(String filterCategory, List resources) { - ArrayList filteredResourceList = new ArrayList<>(); - for (Resource resource : resources) { - List categories = Activator.instance().getMetadataService().getCategories(resource); - for (String category : categories) { - if (category.equals(filterCategory)) { - filteredResourceList.add(new ResourceExt(resource, Activator.instance().getMetadataService())); - break; - } - } - } - - return filteredResourceList; - } - - @CheckForNull - private String getRepositoryId(HttpServletRequest req) { - String id = req.getParameter("repositoryId"); - if (id == null) { - Map stores = Activator.instance().getRepositories(); - if (stores.isEmpty()) { - return null; - } - id = stores.keySet().iterator().next(); - logger.trace("Store ID not specified, using the first store found: " + id); - } - return id; - } -} +package cz.zcu.kiv.crce.webui.internal; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.CheckForNull; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.compatibility.Compatibility; +import cz.zcu.kiv.crce.compatibility.CompatibilityVersionComparator; +import cz.zcu.kiv.crce.metadata.Requirement; +import cz.zcu.kiv.crce.metadata.Resource; +import cz.zcu.kiv.crce.metadata.osgi.namespace.NsOsgiIdentity; +import cz.zcu.kiv.crce.metadata.type.Version; +import cz.zcu.kiv.crce.plugin.Plugin; +import cz.zcu.kiv.crce.webui.internal.bean.Category; +import cz.zcu.kiv.crce.webui.internal.custom.ResourceExt; + +public class ResourceServlet extends HttpServlet { + + private static final long serialVersionUID = -4218424299866417104L; + + private static final Logger logger = LoggerFactory.getLogger(ResourceServlet.class); + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + String source = (String) req.getSession().getAttribute("source"); + logger.debug("Resource servlet POST source: {}", source); + + //if form was submit, set session parameters{ + if ("yes".equalsIgnoreCase(req.getParameter("showStoreTag"))) { + req.getSession().setAttribute("showStoreTag", "yes"); + logger.debug("showStoreTag session attribute set to yes"); + } else { + req.getSession().setAttribute("showStoreTag", "no"); + logger.debug("showStoreTag session attribute set to no"); + } + + if ("yes".equalsIgnoreCase(req.getParameter("showBufferTag"))) { + req.getSession().setAttribute("showBufferTag", "yes"); + logger.debug("showBufferTag session attribute set to yes"); + } else { + req.getSession().setAttribute("showBufferTag", "no"); + logger.debug("showBufferTag session attribute set to no"); + } + + if ("upload".equals(source) || "commit".equals(source)) { + doGet(req, resp); + } else { + String filter = req.getParameter("filter"); + if (filter != null && !filter.isEmpty()) { + + logger.warn("LDAP filter is not supported yet with new Metadata API, returning all resources for filter: {}", filter); + + fillSession(source, req, null); // TODO there was filter instead of null in implementation with old metadata + req.getRequestDispatcher("jsp/" + source + ".jsp").forward(req, resp); + } else { + doGet(req, resp); + } + } + + + + + + +// else if (req.getParameter("repositorySelection") != null) { +// req.getSession().setAttribute("repositoryId", req.getParameter("repositorySelection")); +// } + + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + + String link = null; + + if (req.getParameter("link") != null) { + link = req.getParameter("link"); + } + + try { + if (fillSession(link, req, null)) { + //resp.sendRedirect("jsp/"+link+".jsp"); + req.getRequestDispatcher("jsp/" + link + ".jsp").forward(req, resp); + } else { + logger.debug("Default forward"); + req.getRequestDispatcher("resource?link=store").forward(req, resp); + } + + } catch (ServletException e) { + logger.warn("Can't forward: {}", e); + } catch (IOException e) { + logger.error("Can't forward", e); + } + } + + public static void cleanSession(HttpSession session) { + session.removeAttribute("resources"); + session.removeAttribute("plugins"); + session.removeAttribute("store"); + } + + public static void setError(HttpSession session, boolean success, String message) { + session.setAttribute("success", success); + session.setAttribute("message", message); + } + + private boolean fillSession(String link, HttpServletRequest req, Requirement filter) { + + String errorMessage = filter + " is not a valid filter"; + HttpSession session = req.getSession(); + cleanSession(session); + if (link == null) { + return false; + } + + Set> repositories = Activator.instance().getRepositories().entrySet(); + session.setAttribute("showRepositorySelection", repositories.size() > 1); // TODO this logic should be in header.jsp + session.setAttribute("repositories", repositories); + session.setAttribute("repositoryId", getRepositoryId(req)); + + switch (link) { + case "buffer": { + List resources; + if (filter == null) { + resources = Activator.instance().getBuffer(req).getResources(); + } else { + try { + resources = Activator.instance().getBuffer(req).getResources(filter); + } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? + setError(session, false, errorMessage); + resources = Activator.instance().getBuffer(req).getResources(); + } + } + List bufferResourcesExt = new ArrayList<>(resources.size()); + for (Resource resource : resources) { + bufferResourcesExt.add(new ResourceExt(resource, Activator.instance().getMetadataService())); + } + session.setAttribute("buffer", bufferResourcesExt); + return true; + } + + case "plugins": { + List plugins; + if (filter == null) { + plugins = Activator.instance().getPluginManager().getPlugins(); + } else { + plugins = Activator.instance().getPluginManager().getPlugins(); + logger.warn("Filtering plugins with new Metadata API is not supported yet, returning all plugins."); +// plugins = Activator.instance().getPluginManager().getPlugins(Plugin.class, filter); + } + List pluginWrappers = new ArrayList<>(plugins.size()); + for (Plugin plugin : plugins) { + pluginWrappers.add(new cz.zcu.kiv.crce.webui.internal.custom.Plugin(plugin)); + } + session.setAttribute("plugins", pluginWrappers); + return true; + } + + case "store": { + String id = getRepositoryId(req); + if (id == null) { + return true; + } + List resources; + if (filter == null) { + resources = Activator.instance().getStore(id).getResources(); + } else { + try { + resources = Activator.instance().getStore(id).getResources(filter); + } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? + setError(session, false, errorMessage); + resources = Activator.instance().getStore(id).getResources(); + } + } + List storeResourcesExt = new ArrayList<>(resources.size()); + for (Resource resource : resources) { + storeResourcesExt.add(new ResourceExt(resource, Activator.instance().getMetadataService())); + } + session.setAttribute("store", storeResourcesExt); + return true; + } + + case "tags": { + List resources = prepareResources(req, filter); + ArrayList categoryList = prepareCategoryList(resources); + ArrayList filteredResourceList; + + String selectedCategory; + if (req.getParameter("tag") != null) { + selectedCategory = req.getParameter("tag"); + + filteredResourceList = filterResources(selectedCategory, resources); + + } else { + filteredResourceList = null; + } + + session.setAttribute("resources", filteredResourceList); + session.setAttribute("categoryList", categoryList); + + return true; + } + + case "compatibility": { + String name = req.getParameter("name"); + String version = req.getParameter("version"); + String id = getRepositoryId(req); + + List lower = null; + List upper = null; + + if (name == null || name.isEmpty() || version == null || version.isEmpty() || id == null) { + session.setAttribute("nodata", true); + return true; + } + session.setAttribute("nodata", false); + + Requirement resFilter = Activator.instance().getMetadataFactory().createRequirement(NsOsgiIdentity.NAMESPACE__OSGI_IDENTITY); + resFilter.addAttribute(NsOsgiIdentity.ATTRIBUTE__SYMBOLIC_NAME, name); + Version v = new Version(version); + resFilter.addAttribute(NsOsgiIdentity.ATTRIBUTE__VERSION, v); + + List res = Activator.instance().getStore(id).getResources(resFilter); + if (!res.isEmpty()) { + lower = Activator.instance().getCompatibilityService().listLowerCompatibilities(res.get(0)); + Collections.sort(lower, CompatibilityVersionComparator.getBaseComparator()); + + upper = Activator.instance().getCompatibilityService().listUpperCompatibilities(res.get(0)); + Collections.sort(upper, CompatibilityVersionComparator.getUpperComparator()); + + } + + session.setAttribute("pivotName", name); + session.setAttribute("pivotVersion", version); + session.setAttribute("lower", lower); + session.setAttribute("upper", upper); + + return true; + } + + case "maven": { + logger.debug("Maven search page."); + return true; + } + + default: + return false; + } + } + + /** + * Prepare resource array. Resource array is created from store and buffer. Store resources are added, if request parameter + * store is "yes". Buffer resources are added, if request parameter + * buffer is "yes". + * + * @param req request with parameters + * @param filter possible filter of resources + * @return array of resources + */ + private List prepareResources(HttpServletRequest req, Requirement filter) { + HttpSession session = req.getSession(); + + List storeResources = Collections.emptyList(); + List bufferResources = Collections.emptyList(); + + String id = getRepositoryId(req); + if (id != null && "yes".equalsIgnoreCase((String) session.getAttribute("showStoreTag"))) { + if (filter == null) { + storeResources = Activator.instance().getStore(id).getResources(); + } else { + try { + storeResources = Activator.instance().getStore(id).getResources(filter); + } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? + logger.warn("Invalid syntax", e); + setError(session, false, filter + " is not a valid filter"); + storeResources = Activator.instance().getStore(id).getResources(); + } + } + } + + if ("yes".equals((String) session.getAttribute("showBufferTag"))) { + if (filter == null) { + bufferResources = Activator.instance().getBuffer(req).getResources(); + } else { + try { + bufferResources = Activator.instance().getBuffer(req).getResources(filter); + } catch (Exception e) { // TODO there was catch of InvalidSyntaxException, why? + logger.warn("Invalid syntax", e); + setError(session, false, filter + " is not a valid filter"); + bufferResources = Activator.instance().getBuffer(req).getResources(); + } + } + } + + //merge two resources arrays + List resources = new ArrayList<>(storeResources.size() + bufferResources.size()); + resources.addAll(storeResources); + resources.addAll(bufferResources); + + return resources; + } + + /** + * Prepare list of categories (tags) that are on all resources in the store. Category is represented by name and the number of + * occurrences. + * + * @param resources - all resources from the store + * @return array list of categories + */ + private ArrayList prepareCategoryList(List resources) { + + HashMap categoryMap = new HashMap<>(); + + for (Resource resource : resources) { + List categories = Activator.instance().getMetadataService().getCategories(resource); + for (String category : categories) { + if (categoryMap.containsKey(category)) { + //category is already contained, increase count + categoryMap.put(category, categoryMap.get(category) + 1); + } else { + //add new category + categoryMap.put(category, 1); + } + } + } + + ArrayList categoryList = new ArrayList<>(); + + //Get categories from map to list + for (Map.Entry entry : categoryMap.entrySet()) { + Category newCategory = new Category(entry.getKey()); + newCategory.setCount(entry.getValue()); + categoryList.add(newCategory); + } + + //sort category list + Collections.sort(categoryList); + + return categoryList; + + + } + + /** + * Filter resources according some category. Output list contains only resources that have required category. + * + * @param filterCategory required category + * @param resources resources + * @return filtered resources list + */ + private ArrayList filterResources(String filterCategory, List resources) { + ArrayList filteredResourceList = new ArrayList<>(); + for (Resource resource : resources) { + List categories = Activator.instance().getMetadataService().getCategories(resource); + for (String category : categories) { + if (category.equals(filterCategory)) { + filteredResourceList.add(new ResourceExt(resource, Activator.instance().getMetadataService())); + break; + } + } + } + + return filteredResourceList; + } + + @CheckForNull + private String getRepositoryId(HttpServletRequest req) { + String id = req.getParameter("repositoryId"); + if (id == null) { + Map stores = Activator.instance().getRepositories(); + if (stores.isEmpty()) { + return null; + } + id = stores.keySet().iterator().next(); + logger.trace("Store ID not specified, using the first store found: " + id); + } + return id; + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/UploadServlet.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/UploadServlet.java index fa929a3b..0d742af6 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/UploadServlet.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/UploadServlet.java @@ -1,213 +1,213 @@ -package cz.zcu.kiv.crce.webui.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cz.zcu.kiv.crce.repository.Buffer; -import cz.zcu.kiv.crce.repository.RefusedArtifactException; -import java.net.MalformedURLException; -import java.net.URL; - -/** - * - * @author kalwi - */ -public class UploadServlet extends HttpServlet { - - private static final long serialVersionUID = -7359560802937893940L; - - private static final Logger logger = LoggerFactory.getLogger(UploadServlet.class); - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - boolean failed = false; - - if (req.getParameter("uri") != null) { - Buffer buffer = Activator.instance().getBuffer(req); -// List resources = buffer.getResources(); -// String uriParam = req.getParameter("uri"); - try { -// URI uri = new URI(uriParam); -// Resource found = EditServlet.findResource(uri, resources); - buffer.commit(true); //TODO! Bad API -> Resources should be committed one by one -// } catch (URISyntaxException e) { -// logger.error("Invalid URI syntax", e); -// failed = true; - } catch (IOException e) { - logger.error("Could not commit", e); - failed = true; - } - } else { - failed = true; - } - if (failed) { - logger.error("Commit failed"); - ResourceServlet.setError(req.getSession(), !failed, "Commit failed"); - } else { - req.getRequestDispatcher("resource?link=buffer"); - } - - /*PrintWriter out = resp.getWriter(); - out.println("

Resources to commit:

"); - for (Resource res : buffer.getRepository().getResources()) { - out.println(res.getId() + " " + res.getUri()); - } - - List commited = buffer.commit(true); - out.println("

Commited resources " + commited.size() + ":

"); - for (Resource res : commited) { - out.println(res.getId() + " " + res.getUri() + "
"); - }*/ - - // HttpSession session = req.getSession(true); - // - // PrintWriter out = resp.getWriter(); - // out.println("m_stack: " + (Activator.instance().getBuffer(req) != null ? "found" : "not found")); // XXX - // - // Enumeration en = session.getAttributeNames(); - // - // while (en.hasMoreElements()) { - // String name = (String) en.nextElement(); - // out.println(name + ": " + session.getAttribute(name)); - // } - // - // session.setAttribute("id" + new Random().nextInt(100), new Random().nextInt(10)); - // - // - // out.close(); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - boolean success = true; - String message; - String from = req.getParameter("from"); - - if (from != null && from.equalsIgnoreCase("local")) { - // local upload from hdd - logger.debug("Got \"from\" parameter with value \"{}\".", from); - if (ServletFileUpload.isMultipartContent(req)) { - ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); - List fileItemsList; - try { - fileItemsList = servletFileUpload.parseRequest(req); - } catch (FileUploadException e) { - logger.error("Exception handling request: " + req.getRequestURL(), e); - sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - - for (Object o : fileItemsList) { - FileItem fi = (FileItem) o; - - if (!fi.isFormField()) { - String fileName = fi.getName(); - try (InputStream is = fi.getInputStream()) { - try { - Activator.instance().getBuffer(req).put(fileName, is); - } catch (RefusedArtifactException ex) { - logger.warn("Artifact revoked: ", ex.getMessage()); - success = false; - } - } - } - } - } else { - success = false; - } - } else { - // remote upload from url - logger.debug("Got \"from\" parameter with value \"{}\".", from); - String url = req.getParameter("url"); - if (from != null && from.equalsIgnoreCase("remote") && url != null && url.length() > 0) { - logger.debug("Got \"url\" parameter with value \"{}\".", url); - InputStream is = createInputStreamFromIdlUri(url); - try { - Activator.instance().getBuffer(req).put(url, is); - } catch (RefusedArtifactException ex) { - logger.warn("Artifact revoked: ", ex.getMessage()); - success = false; - } - } else { - success = false; - } - } - - StringBuilder metadataIndexerResult = new StringBuilder(); - if (success) { - message = "Upload was succesful."; - -// MetadataIndexingResultService indexerResult = Activator.instance().getMetadataIndexerResult(); -// if (!indexerResult.isEmpty()) { -// String[] metadataIndexerMessages = indexerResult.getMessages(); -// for (String indexerMessage : metadataIndexerMessages) { -// metadataIndexerResult.append("
").append(indexerMessage); -// } -// indexerResult.removeAllMessages(); -// } - } else { - message = "Upload failed."; - } - - ResourceServlet.setError(req.getSession(), success, message + metadataIndexerResult); - req.getSession().setAttribute("source", "upload"); - req.getRequestDispatcher("resource?link=buffer").forward(req, resp); - } - - // send a response with the specified status code - private void sendResponse(HttpServletResponse response, int statusCode) { - sendResponse(response, statusCode, ""); - } - - // send a response with the specified status code and description - private void sendResponse(HttpServletResponse response, int statusCode, String description) { - try { - response.sendError(statusCode, description); - } catch (Exception e) { - logger.warn("Unable to send response with status code '{}'", statusCode, e); - } - } - - /** - * Opens remote URL of IDL document and returns {@link java.io.InputStream} of that location in order to read content from it. - * - * - * @param url Remote URL - * @return {@link java.io.InputStream} of passed url location. - */ - private InputStream createInputStreamFromIdlUri(String url) { - - // try to access IDL content at uri - logger.debug("Attempting to access IDL at \"{}\".", url); - URL urlObj = null; - try { - urlObj = new URL(url); - } catch (MalformedURLException ex) { - logger.error("MalformedURLException: {}", url, ex); - } - if (urlObj == null) { - return null; - } - - // try to return InputStream - try { - return urlObj.openStream(); - } catch (IOException ex) { - logger.error("IOException: {}", url, ex); - return null; - } - } -} +package cz.zcu.kiv.crce.webui.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import cz.zcu.kiv.crce.repository.Buffer; +import cz.zcu.kiv.crce.repository.RefusedArtifactException; +import java.net.MalformedURLException; +import java.net.URL; + +/** + * + * @author kalwi + */ +public class UploadServlet extends HttpServlet { + + private static final long serialVersionUID = -7359560802937893940L; + + private static final Logger logger = LoggerFactory.getLogger(UploadServlet.class); + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + boolean failed = false; + + if (req.getParameter("uri") != null) { + Buffer buffer = Activator.instance().getBuffer(req); +// List resources = buffer.getResources(); +// String uriParam = req.getParameter("uri"); + try { +// URI uri = new URI(uriParam); +// Resource found = EditServlet.findResource(uri, resources); + buffer.commit(true); //TODO! Bad API -> Resources should be committed one by one +// } catch (URISyntaxException e) { +// logger.error("Invalid URI syntax", e); +// failed = true; + } catch (IOException e) { + logger.error("Could not commit", e); + failed = true; + } + } else { + failed = true; + } + if (failed) { + logger.error("Commit failed"); + ResourceServlet.setError(req.getSession(), !failed, "Commit failed"); + } else { + req.getRequestDispatcher("resource?link=buffer"); + } + + /*PrintWriter out = resp.getWriter(); + out.println("

Resources to commit:

"); + for (Resource res : buffer.getRepository().getResources()) { + out.println(res.getId() + " " + res.getUri()); + } + + List commited = buffer.commit(true); + out.println("

Commited resources " + commited.size() + ":

"); + for (Resource res : commited) { + out.println(res.getId() + " " + res.getUri() + "
"); + }*/ + + // HttpSession session = req.getSession(true); + // + // PrintWriter out = resp.getWriter(); + // out.println("m_stack: " + (Activator.instance().getBuffer(req) != null ? "found" : "not found")); // XXX + // + // Enumeration en = session.getAttributeNames(); + // + // while (en.hasMoreElements()) { + // String name = (String) en.nextElement(); + // out.println(name + ": " + session.getAttribute(name)); + // } + // + // session.setAttribute("id" + new Random().nextInt(100), new Random().nextInt(10)); + // + // + // out.close(); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + boolean success = true; + String message; + String from = req.getParameter("from"); + + if (from != null && from.equalsIgnoreCase("local")) { + // local upload from hdd + logger.debug("Got \"from\" parameter with value \"{}\".", from); + if (ServletFileUpload.isMultipartContent(req)) { + ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); + List fileItemsList; + try { + fileItemsList = servletFileUpload.parseRequest(req); + } catch (FileUploadException e) { + logger.error("Exception handling request: " + req.getRequestURL(), e); + sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + + for (Object o : fileItemsList) { + FileItem fi = (FileItem) o; + + if (!fi.isFormField()) { + String fileName = fi.getName(); + try (InputStream is = fi.getInputStream()) { + try { + Activator.instance().getBuffer(req).put(fileName, is); + } catch (RefusedArtifactException ex) { + logger.warn("Artifact revoked: ", ex.getMessage()); + success = false; + } + } + } + } + } else { + success = false; + } + } else { + // remote upload from url + logger.debug("Got \"from\" parameter with value \"{}\".", from); + String url = req.getParameter("url"); + if (from != null && from.equalsIgnoreCase("remote") && url != null && url.length() > 0) { + logger.debug("Got \"url\" parameter with value \"{}\".", url); + InputStream is = createInputStreamFromIdlUri(url); + try { + Activator.instance().getBuffer(req).put(url, is); + } catch (RefusedArtifactException ex) { + logger.warn("Artifact revoked: ", ex.getMessage()); + success = false; + } + } else { + success = false; + } + } + + StringBuilder metadataIndexerResult = new StringBuilder(); + if (success) { + message = "Upload was succesful."; + +// MetadataIndexingResultService indexerResult = Activator.instance().getMetadataIndexerResult(); +// if (!indexerResult.isEmpty()) { +// String[] metadataIndexerMessages = indexerResult.getMessages(); +// for (String indexerMessage : metadataIndexerMessages) { +// metadataIndexerResult.append("
").append(indexerMessage); +// } +// indexerResult.removeAllMessages(); +// } + } else { + message = "Upload failed."; + } + + ResourceServlet.setError(req.getSession(), success, message + metadataIndexerResult); + req.getSession().setAttribute("source", "upload"); + req.getRequestDispatcher("resource?link=buffer").forward(req, resp); + } + + // send a response with the specified status code + private void sendResponse(HttpServletResponse response, int statusCode) { + sendResponse(response, statusCode, ""); + } + + // send a response with the specified status code and description + private void sendResponse(HttpServletResponse response, int statusCode, String description) { + try { + response.sendError(statusCode, description); + } catch (Exception e) { + logger.warn("Unable to send response with status code '{}'", statusCode, e); + } + } + + /** + * Opens remote URL of IDL document and returns {@link java.io.InputStream} of that location in order to read content from it. + * + * + * @param url Remote URL + * @return {@link java.io.InputStream} of passed url location. + */ + private InputStream createInputStreamFromIdlUri(String url) { + + // try to access IDL content at uri + logger.debug("Attempting to access IDL at \"{}\".", url); + URL urlObj = null; + try { + urlObj = new URL(url); + } catch (MalformedURLException ex) { + logger.error("MalformedURLException: {}", url, ex); + } + if (urlObj == null) { + return null; + } + + // try to return InputStream + try { + return urlObj.openStream(); + } catch (IOException ex) { + logger.error("IOException: {}", url, ex); + return null; + } + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/VersionInfo.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/VersionInfo.java index ac31f678..59fb1557 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/VersionInfo.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/VersionInfo.java @@ -1,67 +1,67 @@ -package cz.zcu.kiv.crce.webui.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides information about application version. - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class VersionInfo { - - private static final Logger logger = LoggerFactory.getLogger(VersionInfo.class); - - private static final String MANIFEST = "/META-INF/MANIFEST.MF"; - private static final String PRODUCT_VERSION = "Product-Version"; - private static final String IMPLEMENTATION_BUILD = "Implementation-Build"; - private static final String UNKNOWN = "unknown"; - - private static VersionInfo instance = null; - private String productVersion; - private String buildRevision; - - /** - * Returns singleton instance of this class. - * @param servletContext Servlet context for reading WAR Manifest entries. If null, then the current - * class classloader will be used to read Manifest entries which can lead to that wrong Manifest will be read. - * @return Instance of this class. - */ - public static synchronized VersionInfo getVersionInfo(ServletContext servletContext) { - if (instance == null) { - instance = new VersionInfo(); - /* - * Product version is currently stored in WebUI MANIFEST, which could cause - * information mismatch if WAR from another build will be deployed. - * But for now it's enough. - */ - try (InputStream is - = servletContext != null ? servletContext.getResourceAsStream(MANIFEST) : Class.class.getResourceAsStream(MANIFEST)) { - Properties properties = new Properties(); - properties.load(is); - instance.productVersion = properties.getProperty(PRODUCT_VERSION); - instance.buildRevision = properties.getProperty(IMPLEMENTATION_BUILD); - } catch (IOException e) { - logger.error("Could not read version info from Manifest.", e); - } - } - return instance; - } - - public String getProductVersion() { - return productVersion != null ? productVersion : UNKNOWN; - } - - public String getBuildRevision() { - return buildRevision != null ? buildRevision : UNKNOWN; - } - - private VersionInfo() { - // singleton - } -} +package cz.zcu.kiv.crce.webui.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.servlet.ServletContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provides information about application version. + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class VersionInfo { + + private static final Logger logger = LoggerFactory.getLogger(VersionInfo.class); + + private static final String MANIFEST = "/META-INF/MANIFEST.MF"; + private static final String PRODUCT_VERSION = "Product-Version"; + private static final String IMPLEMENTATION_BUILD = "Implementation-Build"; + private static final String UNKNOWN = "unknown"; + + private static VersionInfo instance = null; + private String productVersion; + private String buildRevision; + + /** + * Returns singleton instance of this class. + * @param servletContext Servlet context for reading WAR Manifest entries. If null, then the current + * class classloader will be used to read Manifest entries which can lead to that wrong Manifest will be read. + * @return Instance of this class. + */ + public static synchronized VersionInfo getVersionInfo(ServletContext servletContext) { + if (instance == null) { + instance = new VersionInfo(); + /* + * Product version is currently stored in WebUI MANIFEST, which could cause + * information mismatch if WAR from another build will be deployed. + * But for now it's enough. + */ + try (InputStream is + = servletContext != null ? servletContext.getResourceAsStream(MANIFEST) : Class.class.getResourceAsStream(MANIFEST)) { + Properties properties = new Properties(); + properties.load(is); + instance.productVersion = properties.getProperty(PRODUCT_VERSION); + instance.buildRevision = properties.getProperty(IMPLEMENTATION_BUILD); + } catch (IOException e) { + logger.error("Could not read version info from Manifest.", e); + } + } + return instance; + } + + public String getProductVersion() { + return productVersion != null ? productVersion : UNKNOWN; + } + + public String getBuildRevision() { + return buildRevision != null ? buildRevision : UNKNOWN; + } + + private VersionInfo() { + // singleton + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/bean/Category.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/bean/Category.java index e59c9f1e..b77c272e 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/bean/Category.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/bean/Category.java @@ -1,65 +1,65 @@ -package cz.zcu.kiv.crce.webui.internal.bean; - -import java.io.Serializable; - -/** - * Bean class for category (tag of resources). - * Category is represented by name and number of occurences in the store. - * @author Jan Reznicek - * @version 1.0 - */ -public class Category implements Serializable, Comparable{ - private static final long serialVersionUID = 1L; - /** - * Name of category (jar,zip..) - */ - private String name; - /** - * Number of occurences of category in the store. - */ - private int count; - - public Category(String name) { - this.name = name; - count = 1; - } - - public String getName() { - return name; - } - public int getCount() { - return count; - } - public void setName(String name) { - this.name = name; - } - public void setCount(int count) { - this.count = count; - } - - @Override - public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null || obj.getClass() != this.getClass()) { - return false; - } - Category otherCat = (Category)obj; - if (otherCat.getName().equals(this.getName())) { - return true; - } - else { - return false; - } - } - - @Override - public int hashCode() { - - return name.hashCode(); - } - - public int compareTo(Category cat) { - return this.getName().compareTo(cat.getName()); - } - -} +package cz.zcu.kiv.crce.webui.internal.bean; + +import java.io.Serializable; + +/** + * Bean class for category (tag of resources). + * Category is represented by name and number of occurences in the store. + * @author Jan Reznicek + * @version 1.0 + */ +public class Category implements Serializable, Comparable{ + private static final long serialVersionUID = 1L; + /** + * Name of category (jar,zip..) + */ + private String name; + /** + * Number of occurences of category in the store. + */ + private int count; + + public Category(String name) { + this.name = name; + count = 1; + } + + public String getName() { + return name; + } + public int getCount() { + return count; + } + public void setName(String name) { + this.name = name; + } + public void setCount(int count) { + this.count = count; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) return true; + if(obj == null || obj.getClass() != this.getClass()) { + return false; + } + Category otherCat = (Category)obj; + if (otherCat.getName().equals(this.getName())) { + return true; + } + else { + return false; + } + } + + @Override + public int hashCode() { + + return name.hashCode(); + } + + public int compareTo(Category cat) { + return this.getName().compareTo(cat.getName()); + } + +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/custom/Plugin.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/custom/Plugin.java index 99bcbbc9..6f3a6d20 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/custom/Plugin.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/custom/Plugin.java @@ -1,47 +1,47 @@ -package cz.zcu.kiv.crce.webui.internal.custom; - -import java.io.Serializable; -import java.util.List; - -/** - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public class Plugin implements Serializable { - - private static final long serialVersionUID = 7452244491708601610L; - - private final String pluginId; - private final String pluginDescription; - private final String pluginPriority; - private final String pluginVersion; - private final List pluginKeywords; - - public Plugin(cz.zcu.kiv.crce.plugin.Plugin plugin) { - pluginId = plugin.getPluginId(); - pluginDescription = plugin.getPluginDescription(); - pluginPriority = String.valueOf(plugin.getPluginPriority()); - pluginVersion = plugin.getPluginVersion().toString(); - pluginKeywords = plugin.getPluginKeywords(); - } - - public String getPluginId() { - return pluginId; - } - - public String getPluginDescription() { - return pluginDescription; - } - - public String getPluginPriority() { - return pluginPriority; - } - - public String getPluginVersion() { - return pluginVersion; - } - - public List getPluginKeywords() { - return pluginKeywords; - } -} +package cz.zcu.kiv.crce.webui.internal.custom; + +import java.io.Serializable; +import java.util.List; + +/** + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public class Plugin implements Serializable { + + private static final long serialVersionUID = 7452244491708601610L; + + private final String pluginId; + private final String pluginDescription; + private final String pluginPriority; + private final String pluginVersion; + private final List pluginKeywords; + + public Plugin(cz.zcu.kiv.crce.plugin.Plugin plugin) { + pluginId = plugin.getPluginId(); + pluginDescription = plugin.getPluginDescription(); + pluginPriority = String.valueOf(plugin.getPluginPriority()); + pluginVersion = plugin.getPluginVersion().toString(); + pluginKeywords = plugin.getPluginKeywords(); + } + + public String getPluginId() { + return pluginId; + } + + public String getPluginDescription() { + return pluginDescription; + } + + public String getPluginPriority() { + return pluginPriority; + } + + public String getPluginVersion() { + return pluginVersion; + } + + public List getPluginKeywords() { + return pluginKeywords; + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/filter/CompatibilityAvailabilityFilter.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/filter/CompatibilityAvailabilityFilter.java index c3ac82aa..75335c2c 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/filter/CompatibilityAvailabilityFilter.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/filter/CompatibilityAvailabilityFilter.java @@ -1,39 +1,39 @@ -package cz.zcu.kiv.crce.webui.internal.filter; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import cz.zcu.kiv.crce.webui.internal.Activator; - -/** - * This filter checks for CompatibilityService presence - * and sets hasCompatInfo attribute for the request accordingly. - * - * Date: 25.3.15 - * - * @author Jakub Danek - */ -public class CompatibilityAvailabilityFilter implements Filter { - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - request.setAttribute("hasCompatInfo", Activator.instance().isCompatibilityServicePresent()); - chain.doFilter(request, response); - } - - @Override - public void destroy() { - - } -} +package cz.zcu.kiv.crce.webui.internal.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import cz.zcu.kiv.crce.webui.internal.Activator; + +/** + * This filter checks for CompatibilityService presence + * and sets hasCompatInfo attribute for the request accordingly. + * + * Date: 25.3.15 + * + * @author Jakub Danek + */ +public class CompatibilityAvailabilityFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + request.setAttribute("hasCompatInfo", Activator.instance().isCompatibilityServicePresent()); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + + } +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Capability.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Capability.java index 67004a9f..cc9ded05 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Capability.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Capability.java @@ -1,13 +1,13 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -/** - * Represents an OBR Capability. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Capability extends PropertyProvider { - - String getName(); - - NewProperty[] getNewProperties(); -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +/** + * Represents an OBR Capability. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Capability extends PropertyProvider { + + String getName(); + + NewProperty[] getNewProperties(); +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Property.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Property.java index 44f96394..a8f457ba 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Property.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Property.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -/** - * A property that can be set to a Resource or a Capability. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Property { - - String getName(); - - Type getType(); - - String getValue(); - - Object getConvertedValue(); - - boolean isWritable(); - -// void setValue(String value, Type type); -// -// void setValue(String string); -// -// void setValue(Version version); -// -// void setValue(URL url); -// -// void setValue(URI uri); -// -// void setValue(long llong); -// -// void setValue(double ddouble); -// -// void setValue(Set values); - -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +/** + * A property that can be set to a Resource or a Capability. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Property { + + String getName(); + + Type getType(); + + String getValue(); + + Object getConvertedValue(); + + boolean isWritable(); + +// void setValue(String value, Type type); +// +// void setValue(String string); +// +// void setValue(Version version); +// +// void setValue(URL url); +// +// void setValue(URI uri); +// +// void setValue(long llong); +// +// void setValue(double ddouble); +// +// void setValue(Set values); + +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/PropertyProvider.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/PropertyProvider.java index 64df3c52..19ecc6de 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/PropertyProvider.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/PropertyProvider.java @@ -1,41 +1,41 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -import java.net.URI; -import java.net.URL; -import java.util.Set; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Common interface for subclasses that can provide Properties. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - * @param - */ -public interface PropertyProvider> { - - Property[] getProperties(); - - Property getProperty(String name); - - String getPropertyString(String name); - - T setProperty(Property property); - - T setProperty(String name, String value, Type type); - - T setProperty(String name, String string); - - T setProperty(String name, Version version); - - T setProperty(String name, URL url); - - T setProperty(String name, URI uri); - - T setProperty(String name, long llong); - - T setProperty(String name, double ddouble); - - T setProperty(String name, Set values); - - T unsetProperty(String name); -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +import java.net.URI; +import java.net.URL; +import java.util.Set; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Common interface for subclasses that can provide Properties. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + * @param + */ +public interface PropertyProvider> { + + Property[] getProperties(); + + Property getProperty(String name); + + String getPropertyString(String name); + + T setProperty(Property property); + + T setProperty(String name, String value, Type type); + + T setProperty(String name, String string); + + T setProperty(String name, Version version); + + T setProperty(String name, URL url); + + T setProperty(String name, URI uri); + + T setProperty(String name, long llong); + + T setProperty(String name, double ddouble); + + T setProperty(String name, Set values); + + T unsetProperty(String name); +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Requirement.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Requirement.java index 88ab5470..952af35a 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Requirement.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Requirement.java @@ -1,36 +1,36 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -/** - * Represents a requirement to a capability with the same name. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Requirement { - - String getName(); - - String getFilter(); - - boolean isMultiple(); - - boolean isOptional(); - - boolean isExtend(); - - String getComment(); - - boolean isWritable(); - - boolean isSatisfied(Capability capability); - - Requirement setFilter(String filter); - - Requirement setMultiple(boolean multiple); - - Requirement setOptional(boolean optional); - - Requirement setExtend(boolean extend); - - Requirement setComment(String comment); - -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +/** + * Represents a requirement to a capability with the same name. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Requirement { + + String getName(); + + String getFilter(); + + boolean isMultiple(); + + boolean isOptional(); + + boolean isExtend(); + + String getComment(); + + boolean isWritable(); + + boolean isSatisfied(Capability capability); + + Requirement setFilter(String filter); + + Requirement setMultiple(boolean multiple); + + Requirement setOptional(boolean optional); + + Requirement setExtend(boolean extend); + + Requirement setComment(String comment); + +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Resource.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Resource.java index 7217ea2d..6ec6821d 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Resource.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Resource.java @@ -1,122 +1,122 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -import java.net.URI; -import java.util.Map; -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * Resource represents an artifact and it's OBR metadata. - * - *

An unique identificator of a resource is it's symbolic name and version. - * - *

Resource have capabilities, requirements, properties and categories. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public interface Resource extends PropertyProvider { - - String getId(); - - String getSymbolicName(); - - Version getVersion(); - - String getPresentationName(); - - URI getUri(); - - URI getRelativeUri(); - -// Repository getRepository(); - - NewProperty[] getNewProperties(); - - /** - * Returns the resource size in bytes or -1 if size is unknown. - * @return the resource size. - */ - long getSize(); - - String[] getCategories(); - - Capability[] getCapabilities(); - - Capability[] getCapabilities(String name); - - Requirement[] getRequirements(); - - Requirement[] getRequirements(String name); - - Map getPropertiesMap(); - - boolean hasCategory(String category); - - boolean hasCapability(Capability capability); - - boolean hasRequirement(Requirement requirement); - - /* --- setters --- */ - - void setSymbolicName(String name); - - void setSymbolicName(String name, boolean isStatic); - - void setPresentationName(String name); - - void setVersion(Version version); - - void setVersion(Version version, boolean isStatic); - - void setVersion(String version); - - void setVersion(String version, boolean isStatic); - - void addCategory(String category); - - void addCapability(Capability capability); - - void addRequirement(Requirement requirement); - - Capability createCapability(String name); - - Requirement createRequirement(String name); - - void unsetCategory(String category); - - void unsetCapability(Capability capability); - - void unsetRequirement(Requirement requirement); - - - /** - * Sets resource size. - * @param size size in bytes to set. - */ - void setSize(long size); - - void setUri(URI uri); - -// void setRepository(WritableRepository repository); - - boolean isWritable(); - - void unsetWritable(); - - /** - * Tells whether or not the version of this resource is hard-coded in - * artifact's binary data (e.g. in bundle manifest). - * @return true if the version is hard-coded and can not be - * changed. - */ - boolean isVersionStatic(); - - /** - * Tells whether or not the symbolic name of this resource is hard-coded in - * artifact's binary data (e.g. in bundle manifest). - * @return true if the symbolic name is hard-coded and can not - * be changed. - */ - boolean isSymbolicNameStatic(); - - String asString(); -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +import java.net.URI; +import java.util.Map; +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * Resource represents an artifact and it's OBR metadata. + * + *

An unique identificator of a resource is it's symbolic name and version. + * + *

Resource have capabilities, requirements, properties and categories. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public interface Resource extends PropertyProvider { + + String getId(); + + String getSymbolicName(); + + Version getVersion(); + + String getPresentationName(); + + URI getUri(); + + URI getRelativeUri(); + +// Repository getRepository(); + + NewProperty[] getNewProperties(); + + /** + * Returns the resource size in bytes or -1 if size is unknown. + * @return the resource size. + */ + long getSize(); + + String[] getCategories(); + + Capability[] getCapabilities(); + + Capability[] getCapabilities(String name); + + Requirement[] getRequirements(); + + Requirement[] getRequirements(String name); + + Map getPropertiesMap(); + + boolean hasCategory(String category); + + boolean hasCapability(Capability capability); + + boolean hasRequirement(Requirement requirement); + + /* --- setters --- */ + + void setSymbolicName(String name); + + void setSymbolicName(String name, boolean isStatic); + + void setPresentationName(String name); + + void setVersion(Version version); + + void setVersion(Version version, boolean isStatic); + + void setVersion(String version); + + void setVersion(String version, boolean isStatic); + + void addCategory(String category); + + void addCapability(Capability capability); + + void addRequirement(Requirement requirement); + + Capability createCapability(String name); + + Requirement createRequirement(String name); + + void unsetCategory(String category); + + void unsetCapability(Capability capability); + + void unsetRequirement(Requirement requirement); + + + /** + * Sets resource size. + * @param size size in bytes to set. + */ + void setSize(long size); + + void setUri(URI uri); + +// void setRepository(WritableRepository repository); + + boolean isWritable(); + + void unsetWritable(); + + /** + * Tells whether or not the version of this resource is hard-coded in + * artifact's binary data (e.g. in bundle manifest). + * @return true if the version is hard-coded and can not be + * changed. + */ + boolean isVersionStatic(); + + /** + * Tells whether or not the symbolic name of this resource is hard-coded in + * artifact's binary data (e.g. in bundle manifest). + * @return true if the symbolic name is hard-coded and can not + * be changed. + */ + boolean isSymbolicNameStatic(); + + String asString(); +} diff --git a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Type.java b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Type.java index c728d2c9..cc9621f3 100644 --- a/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Type.java +++ b/modules/crce-webui/src/main/java/cz/zcu/kiv/crce/webui/internal/legacy/Type.java @@ -1,79 +1,79 @@ -package cz.zcu.kiv.crce.webui.internal.legacy; - -import java.util.Arrays; -import java.util.List; - -import cz.zcu.kiv.crce.metadata.type.Version; - -/** - * This enumeration indicates the type of Properties. - * - * @author Jiri Kucera (jiri.kucera@kalwi.eu) - */ -public enum Type { - - STRING("string", String.class), - VERSION("version", Version.class), - LONG("long", Long.class), - DOUBLE("double", Double.class), -// URL("url", String.class), - URI("uri", String.class), // TODO URI is not supported type yet (PENDING) -// SET("set", List.class); - LIST("list", List.class), - BOOLEAN("boolean", Boolean.class); - - private final String string; - private final Class clazz; - - Type(String string, Class clazz) { - this.string = string; - this.clazz = clazz; - } - - @Override - public String toString() { - return string; - } - - public Class getTypeClass() { - return clazz; - } - - /** - * Returns Type for given string value. - * @param value - * @return - */ - public static Type getValue(String value) { - if (value != null) { - return valueOf(value.toUpperCase()); - } - return STRING; - } - - public static Object propertyValueFromString(Type type, String value) { - if (value == null) { - return null; - } - - switch (type) { - case DOUBLE: - return Double.valueOf(value); - - case LIST: - return Arrays.asList(value.split(",")); - - case LONG: - return Long.valueOf(value); - - case STRING: - return String.valueOf(type); - - case VERSION: - return new Version(value); - - default: - return null; - } - } -} +package cz.zcu.kiv.crce.webui.internal.legacy; + +import java.util.Arrays; +import java.util.List; + +import cz.zcu.kiv.crce.metadata.type.Version; + +/** + * This enumeration indicates the type of Properties. + * + * @author Jiri Kucera (jiri.kucera@kalwi.eu) + */ +public enum Type { + + STRING("string", String.class), + VERSION("version", Version.class), + LONG("long", Long.class), + DOUBLE("double", Double.class), +// URL("url", String.class), + URI("uri", String.class), // TODO URI is not supported type yet (PENDING) +// SET("set", List.class); + LIST("list", List.class), + BOOLEAN("boolean", Boolean.class); + + private final String string; + private final Class clazz; + + Type(String string, Class clazz) { + this.string = string; + this.clazz = clazz; + } + + @Override + public String toString() { + return string; + } + + public Class getTypeClass() { + return clazz; + } + + /** + * Returns Type for given string value. + * @param value + * @return + */ + public static Type getValue(String value) { + if (value != null) { + return valueOf(value.toUpperCase()); + } + return STRING; + } + + public static Object propertyValueFromString(Type type, String value) { + if (value == null) { + return null; + } + + switch (type) { + case DOUBLE: + return Double.valueOf(value); + + case LIST: + return Arrays.asList(value.split(",")); + + case LONG: + return Long.valueOf(value); + + case STRING: + return String.valueOf(type); + + case VERSION: + return new Version(value); + + default: + return null; + } + } +} diff --git a/modules/crce-webui/src/main/webapp/WEB-INF/web.xml b/modules/crce-webui/src/main/webapp/WEB-INF/web.xml index cafe9f52..efe2a33b 100644 --- a/modules/crce-webui/src/main/webapp/WEB-INF/web.xml +++ b/modules/crce-webui/src/main/webapp/WEB-INF/web.xml @@ -1,89 +1,98 @@ - - - - - - - - index.jsp - - - - - cz.zcu.kiv.crce.webui.internal.SessionListener - - - - - CompatInfoCheckFilter - cz.zcu.kiv.crce.webui.internal.filter.CompatibilityAvailabilityFilter - - - - CompatInfoCheckFilter - /* - - - - - - download - cz.zcu.kiv.crce.webui.internal.DownloadServlet - - - download - /download - - - - check - cz.zcu.kiv.crce.webui.internal.CheckServlet - - - check - /check - - - - test - cz.zcu.kiv.crce.webui.internal.RuntimeServlet - - - test - /test - - - - resource - cz.zcu.kiv.crce.webui.internal.ResourceServlet - - - resource - /resource - - - - edit - cz.zcu.kiv.crce.webui.internal.EditServlet - - - edit - /edit - - - - UploadServlet - cz.zcu.kiv.crce.webui.internal.UploadServlet - - - UploadServlet - /upload - - - - org.apache.commons.fileupload.servlet.FileCleanerCleanup - - - + + + + + + + + index.jsp + + + + + cz.zcu.kiv.crce.webui.internal.SessionListener + + + + + CompatInfoCheckFilter + cz.zcu.kiv.crce.webui.internal.filter.CompatibilityAvailabilityFilter + + + + CompatInfoCheckFilter + /* + + + + + + download + cz.zcu.kiv.crce.webui.internal.DownloadServlet + + + download + /download + + + + check + cz.zcu.kiv.crce.webui.internal.CheckServlet + + + check + /check + + + + test + cz.zcu.kiv.crce.webui.internal.RuntimeServlet + + + test + /test + + + + resource + cz.zcu.kiv.crce.webui.internal.ResourceServlet + + + resource + /resource + + + + edit + cz.zcu.kiv.crce.webui.internal.EditServlet + + + edit + /edit + + + + UploadServlet + cz.zcu.kiv.crce.webui.internal.UploadServlet + + + UploadServlet + /upload + + + + MavenServlet + cz.zcu.kiv.crce.webui.internal.MavenServlet + + + MavenServlet + /maven-search + + + + org.apache.commons.fileupload.servlet.FileCleanerCleanup + + + diff --git a/modules/crce-webui/src/main/webapp/index.jsp b/modules/crce-webui/src/main/webapp/index.jsp index d2d4d35d..775514fa 100644 --- a/modules/crce-webui/src/main/webapp/index.jsp +++ b/modules/crce-webui/src/main/webapp/index.jsp @@ -1,145 +1,145 @@ -<%-- - Document : index - Created on : 9.12.2010, 15:39:19 - Author : kalwi ---%> - -<%@page import="cz.zcu.kiv.crce.metadata.Attribute"%> -<%@page import="java.util.List"%> -<% - response.sendRedirect("resource"); - %> - -<%@page import="cz.zcu.kiv.crce.plugin.Plugin"%> -<%@page import="cz.zcu.kiv.crce.metadata.Requirement"%> -<%@page import="cz.zcu.kiv.crce.metadata.Property"%> -<%@page import="cz.zcu.kiv.crce.metadata.Capability"%> -<%@page import="cz.zcu.kiv.crce.repository.Buffer"%> -<%@page import="cz.zcu.kiv.crce.webui.internal.Activator"%> -<%@page import="cz.zcu.kiv.crce.metadata.Resource"%> -<%@page contentType="text/html" pageEncoding="UTF-8"%> - - - - - KIV CRCE - - - -

- -
- -

Store bundle:

- -
-
- -
- <% - String success = request.getParameter("success"); - if ("true".equals(success)) { - out.println("

Upload successful

"); - } - if ("false".equals(success)) { - out.println("

Upload failed

"); - } - %> - -

Plugins in plugin manager:

- <% - List plugins = Activator.instance().getPluginManager().getPlugins(); - out.println(""); - out.println(""); - for (Plugin plugin : plugins) { - out.println(""); - out.println(""); - out.println(""); - } - out.println("
IDprioritydescription
" + plugin.getPluginId() + "" + plugin.getPluginPriority() + "" + plugin.getPluginDescription() + "
"); - %> - -

Resources in buffer

- - <% - - - Buffer buffer = Activator.instance().getBuffer(request); - for (Resource res : buffer.getResources()) { - out.println("

" + res.getId() + "

"); - - out.println(""); - out.println(""); - out.println(""); - out.println(""); - out.print(""); - out.println("
Presentation name:" + Activator.instance().getMetadataService().getPresentationName(res) + "
Size:" + Activator.instance().getMetadataService().getSize(res) + "
URI:" + Activator.instance().getMetadataService().getUri(res).normalize() + "
Categories:"); - boolean first = true; - for (String category : Activator.instance().getMetadataService().getCategories(res)) { - if (first) { - first = false; - } else { - out.print(", "); - } - out.print(category); - } - out.println("
"); - - /* - out.println("

Properties

"); - out.println("
"); - out.println(""); - out.println(""); - for (Property prop : res.getProperties()) { - out.println(""); - } - out.println("
typenamevalue
" + prop.getType() + "" + prop.getName() + "" + prop.getValue() + "
"); - out.println("
"); - */ - - out.println("

Capabilities

"); - - out.println(""); - - out.println(""); - - for (Capability cap : res.getCapabilities()) { - out.println(""); - out.println(""); - - out.println(""); - out.println(""); - } - - out.println("
NameProperties
" + cap.getNamespace()+ ""); - out.println(""); - out.println(""); - for (Attribute attr : cap.getAttributes()) { - out.println(""); - } - out.println("
typenamevalue
" + attr.getAttributeType().getType() - + "" + attr.getAttributeType().getName() + "" + attr.getValue() + "
"); - out.println("
"); - - - out.println("

Requirements

"); - out.println(""); - out.println(""); - for (Requirement req : res.getRequirements()) { - out.println("" - + "" - + "" - + "" - + ""); - } - out.println("
NameFilterOptionalMultipleExtended
" + req.getNamespace()+ "" + req.getDirective("filter") + "" + (Boolean.getBoolean(req.getDirective("optional")) ? "Y" : "N") + "" + (Boolean.getBoolean(req.getDirective("multiple")) ? "Y" : "N") + "" + (Boolean.getBoolean(req.getDirective("extend")) ? "Y" : "N") + "
"); - - out.println("
"); - } - - - %> - -
- - +<%-- + Document : index + Created on : 9.12.2010, 15:39:19 + Author : kalwi +--%> + +<%@page import="cz.zcu.kiv.crce.metadata.Attribute"%> +<%@page import="java.util.List"%> +<% + response.sendRedirect("resource"); + %> + +<%@page import="cz.zcu.kiv.crce.plugin.Plugin"%> +<%@page import="cz.zcu.kiv.crce.metadata.Requirement"%> +<%@page import="cz.zcu.kiv.crce.metadata.Property"%> +<%@page import="cz.zcu.kiv.crce.metadata.Capability"%> +<%@page import="cz.zcu.kiv.crce.repository.Buffer"%> +<%@page import="cz.zcu.kiv.crce.webui.internal.Activator"%> +<%@page import="cz.zcu.kiv.crce.metadata.Resource"%> +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + KIV CRCE + + + + + +
+ +

Store bundle:

+ +
+
+ +
+ <% + String success = request.getParameter("success"); + if ("true".equals(success)) { + out.println("

Upload successful

"); + } + if ("false".equals(success)) { + out.println("

Upload failed

"); + } + %> + +

Plugins in plugin manager:

+ <% + List plugins = Activator.instance().getPluginManager().getPlugins(); + out.println(""); + out.println(""); + for (Plugin plugin : plugins) { + out.println(""); + out.println(""); + out.println(""); + } + out.println("
IDprioritydescription
" + plugin.getPluginId() + "" + plugin.getPluginPriority() + "" + plugin.getPluginDescription() + "
"); + %> + +

Resources in buffer

+ + <% + + + Buffer buffer = Activator.instance().getBuffer(request); + for (Resource res : buffer.getResources()) { + out.println("

" + res.getId() + "

"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.print(""); + out.println("
Presentation name:" + Activator.instance().getMetadataService().getPresentationName(res) + "
Size:" + Activator.instance().getMetadataService().getSize(res) + "
URI:" + Activator.instance().getMetadataService().getUri(res).normalize() + "
Categories:"); + boolean first = true; + for (String category : Activator.instance().getMetadataService().getCategories(res)) { + if (first) { + first = false; + } else { + out.print(", "); + } + out.print(category); + } + out.println("
"); + + /* + out.println("

Properties

"); + out.println("
"); + out.println(""); + out.println(""); + for (Property prop : res.getProperties()) { + out.println(""); + } + out.println("
typenamevalue
" + prop.getType() + "" + prop.getName() + "" + prop.getValue() + "
"); + out.println("
"); + */ + + out.println("

Capabilities

"); + + out.println(""); + + out.println(""); + + for (Capability cap : res.getCapabilities()) { + out.println(""); + out.println(""); + + out.println(""); + out.println(""); + } + + out.println("
NameProperties
" + cap.getNamespace()+ ""); + out.println(""); + out.println(""); + for (Attribute attr : cap.getAttributes()) { + out.println(""); + } + out.println("
typenamevalue
" + attr.getAttributeType().getType() + + "" + attr.getAttributeType().getName() + "" + attr.getValue() + "
"); + out.println("
"); + + + out.println("

Requirements

"); + out.println(""); + out.println(""); + for (Requirement req : res.getRequirements()) { + out.println("" + + "" + + "" + + "" + + ""); + } + out.println("
NameFilterOptionalMultipleExtended
" + req.getNamespace()+ "" + req.getDirective("filter") + "" + (Boolean.getBoolean(req.getDirective("optional")) ? "Y" : "N") + "" + (Boolean.getBoolean(req.getDirective("multiple")) ? "Y" : "N") + "" + (Boolean.getBoolean(req.getDirective("extend")) ? "Y" : "N") + "
"); + + out.println("
"); + } + + + %> + +
+ + diff --git a/modules/crce-webui/src/main/webapp/js/jquery-1.5.1.js b/modules/crce-webui/src/main/webapp/js/jquery-1.5.1.js index 78fcfa46..a869553a 100644 --- a/modules/crce-webui/src/main/webapp/js/jquery-1.5.1.js +++ b/modules/crce-webui/src/main/webapp/js/jquery-1.5.1.js @@ -1,8316 +1,8316 @@ -/*! - * jQuery JavaScript Library v1.5.1 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Wed Feb 23 13:55:29 2011 -0500 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // (both of which we optimize for) - quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Check for digits - rdigit = /\d/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // Has the ready events already been bound? - readyBound = false, - - // The deferred used on DOM ready - readyList, - - // Promise methods - promiseMethods = "then done fail isResolved isRejected promise".split( " " ), - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = "body"; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - match = quickExpr.exec( selector ); - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return (context || rootjQuery).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.5.1", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.done( fn ); - - return this; - }, - - eq: function( i ) { - return i === -1 ? - this.slice( i ) : - this.slice( i, +i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - window.$ = _$; - - if ( deep ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - // A third-party is pushing the ready event forwards - if ( wait === true ) { - jQuery.readyWait--; - } - - // Make sure that the DOM is not already loaded - if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).unbind( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyBound ) { - return; - } - - readyBound = true; - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent("onreadystatechange", DOMContentLoaded); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNaN: function( obj ) { - return obj == null || !rdigit.test( obj ) || isNaN( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw msg; - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test(data.replace(rvalidescape, "@") - .replace(rvalidtokens, "]") - .replace(rvalidbraces, "")) ) { - - // Try to use the native JSON parser first - return window.JSON && window.JSON.parse ? - window.JSON.parse( data ) : - (new Function("return " + data))(); - - } else { - jQuery.error( "Invalid JSON: " + data ); - } - }, - - // Cross-browser xml parsing - // (xml & tmp used internally) - parseXML: function( data , xml , tmp ) { - - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - - tmp = xml.documentElement; - - if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { - jQuery.error( "Invalid XML: " + data ); - } - - return xml; - }, - - noop: function() {}, - - // Evalulates a script in a global context - globalEval: function( data ) { - if ( data && rnotwhite.test(data) ) { - // Inspired by code by Andrea Giammarchi - // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html - var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement, - script = document.createElement( "script" ); - - if ( jQuery.support.scriptEval() ) { - script.appendChild( document.createTextNode( data ) ); - } else { - script.text = data; - } - - // Use insertBefore instead of appendChild to circumvent an IE6 bug. - // This arises when a base node is used (#2709). - head.insertBefore( script, head.firstChild ); - head.removeChild( script ); - } - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction(object); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( var value = object[0]; - i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // The extra typeof function check is to prevent crashes - // in Safari 2 (See: #3039) - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type(array); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array ) { - if ( array.indexOf ) { - return array.indexOf( elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var ret = [], value; - - // Go through the array, translating each of the items to their - // new value (or values). - for ( var i = 0, length = elems.length; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - proxy: function( fn, proxy, thisObject ) { - if ( arguments.length === 2 ) { - if ( typeof proxy === "string" ) { - thisObject = fn; - fn = thisObject[ proxy ]; - proxy = undefined; - - } else if ( proxy && !jQuery.isFunction( proxy ) ) { - thisObject = proxy; - proxy = undefined; - } - } - - if ( !proxy && fn ) { - proxy = function() { - return fn.apply( thisObject || this, arguments ); - }; - } - - // Set the guid of unique handler to the same of original handler, so it can be removed - if ( fn ) { - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - } - - // So proxy can be declared as an argument - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can be optionally by executed if its a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return (new Date()).getTime(); - }, - - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - firing, - // flag to know if the deferred has been cancelled - cancelled, - // the deferred itself - deferred = { - - // done( f1, f2, ...) - done: function() { - if ( !cancelled ) { - var args = arguments, - i, - length, - elem, - type, - _fired; - if ( fired ) { - _fired = fired; - fired = 0; - } - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - deferred.done.apply( deferred, elem ); - } else if ( type === "function" ) { - callbacks.push( elem ); - } - } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } - } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - // We have to add a catch block for - // IE prior to 8 or else the finally - // block will never get executed - catch (e) { - throw e; - } - finally { - fired = [ context, args ]; - firing = 0; - } - } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; - } - }; - - return deferred; - }, - - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ); - return this; - }, - fail: failDeferred.done, - rejectWith: failDeferred.resolveWith, - reject: failDeferred.resolve, - isRejected: failDeferred.isResolved, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - } ); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - return deferred; - }, - - // Deferred helper - when: function( object ) { - var lastIndex = arguments.length, - deferred = lastIndex <= 1 && object && jQuery.isFunction( object.promise ) ? - object : - jQuery.Deferred(), - promise = deferred.promise(); - - if ( lastIndex > 1 ) { - var array = slice.call( arguments, 0 ), - count = lastIndex, - iCallback = function( index ) { - return function( value ) { - array[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( promise, array ); - } - }; - }; - while( ( lastIndex-- ) ) { - object = array[ lastIndex ]; - if ( object && jQuery.isFunction( object.promise ) ) { - object.promise().then( iCallback(lastIndex), deferred.reject ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( promise, array ); - } - } else if ( deferred !== object ) { - deferred.resolve( object ); - } - return promise; - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySubclass( selector, context ) { - return new jQuerySubclass.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySubclass, this ); - jQuerySubclass.superclass = this; - jQuerySubclass.fn = jQuerySubclass.prototype = this(); - jQuerySubclass.fn.constructor = jQuerySubclass; - jQuerySubclass.subclass = this.subclass; - jQuerySubclass.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) { - context = jQuerySubclass(context); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass ); - }; - jQuerySubclass.fn.init.prototype = jQuerySubclass.fn; - var rootjQuerySubclass = jQuerySubclass(document); - return jQuerySubclass; - }, - - browser: {} -}); - -// Create readyList deferred -readyList = jQuery._Deferred(); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -if ( indexOf ) { - jQuery.inArray = function( elem, array ) { - return indexOf.call( array, elem ); - }; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -// Expose jQuery to the global object -return jQuery; - -})(); - - -(function() { - - jQuery.support = {}; - - var div = document.createElement("div"); - - div.style.display = "none"; - div.innerHTML = "
a"; - - var all = div.getElementsByTagName("*"), - a = div.getElementsByTagName("a")[0], - select = document.createElement("select"), - opt = select.appendChild( document.createElement("option") ), - input = div.getElementsByTagName("input")[0]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return; - } - - jQuery.support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: div.firstChild.nodeType === 3, - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText insted) - style: /red/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: a.getAttribute("href") === "/a", - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55$/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: input.value === "on", - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Will be defined later - deleteExpando: true, - optDisabled: false, - checkClone: false, - noCloneEvent: true, - noCloneChecked: true, - boxModel: null, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableHiddenOffsets: true - }; - - input.checked = true; - jQuery.support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as diabled) - select.disabled = true; - jQuery.support.optDisabled = !opt.disabled; - - var _scriptEval = null; - jQuery.support.scriptEval = function() { - if ( _scriptEval === null ) { - var root = document.documentElement, - script = document.createElement("script"), - id = "script" + jQuery.now(); - - try { - script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); - } catch(e) {} - - root.insertBefore( script, root.firstChild ); - - // Make sure that the execution of code works by injecting a script - // tag with appendChild/createTextNode - // (IE doesn't support this, fails, and uses .text instead) - if ( window[ id ] ) { - _scriptEval = true; - delete window[ id ]; - } else { - _scriptEval = false; - } - - root.removeChild( script ); - // release memory in IE - root = script = id = null; - } - - return _scriptEval; - }; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - - } catch(e) { - jQuery.support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent("onclick", function click() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - jQuery.support.noCloneEvent = false; - div.detachEvent("onclick", click); - }); - div.cloneNode(true).fireEvent("onclick"); - } - - div = document.createElement("div"); - div.innerHTML = ""; - - var fragment = document.createDocumentFragment(); - fragment.appendChild( div.firstChild ); - - // WebKit doesn't clone checked state correctly in fragments - jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; - - // Figure out if the W3C box model works as expected - // document.body must exist before we can do this - jQuery(function() { - var div = document.createElement("div"), - body = document.getElementsByTagName("body")[0]; - - // Frameset documents with no body should not run this code - if ( !body ) { - return; - } - - div.style.width = div.style.paddingLeft = "1px"; - body.appendChild( div ); - jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; - - if ( "zoom" in div.style ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
"; - jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; - } - - div.innerHTML = "
t
"; - var tds = div.getElementsByTagName("td"); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; - - tds[0].style.display = ""; - tds[1].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE < 8 fail this test) - jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; - div.innerHTML = ""; - - body.removeChild( div ).style.display = "none"; - div = tds = null; - }); - - // Technique from Juriy Zaytsev - // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ - var eventSupported = function( eventName ) { - var el = document.createElement("div"); - eventName = "on" + eventName; - - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( !el.attachEvent ) { - return true; - } - - var isSupported = (eventName in el); - if ( !isSupported ) { - el.setAttribute(eventName, "return;"); - isSupported = typeof el[eventName] === "function"; - } - el = null; - - return isSupported; - }; - - jQuery.support.submitBubbles = eventSupported("submit"); - jQuery.support.changeBubbles = eventSupported("change"); - - // release memory in IE - div = all = a = null; -})(); - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ jQuery.expando ] = id = ++jQuery.uuid; - } else { - id = jQuery.expando; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); - } else { - cache[ id ] = jQuery.extend(cache[ id ], name); - } - } - - thisCache = cache[ id ]; - - // Internal jQuery data is stored in a separate object inside the object's data - // cache in order to avoid key collisions between internal data and user-defined - // data - if ( pvt ) { - if ( !thisCache[ internalKey ] ) { - thisCache[ internalKey ] = {}; - } - - thisCache = thisCache[ internalKey ]; - } - - if ( data !== undefined ) { - thisCache[ name ] = data; - } - - // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should - // not attempt to inspect the internal events object using jQuery.data, as this - // internal data object is undocumented and subject to change. - if ( name === "events" && !thisCache[name] ) { - return thisCache[ internalKey ] && thisCache[ internalKey ].events; - } - - return getByName ? thisCache[ name ] : thisCache; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var internalKey = jQuery.expando, isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; - - if ( thisCache ) { - delete thisCache[ name ]; - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !isEmptyDataObject(thisCache) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( pvt ) { - delete cache[ id ][ internalKey ]; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - var internalCache = cache[ id ][ internalKey ]; - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - if ( jQuery.support.deleteExpando || cache != window ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the entire user cache at once because it's faster than - // iterating through each key, but we need to continue to persist internal - // data if it existed - if ( internalCache ) { - cache[ id ] = {}; - // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery - // metadata on plain JS objects when the object is serialized using - // JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - - cache[ id ][ internalKey ] = internalCache; - - // Otherwise, we need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - } else if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ jQuery.expando ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( jQuery.expando ); - } else { - elem[ jQuery.expando ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 ) { - var attr = this[0].attributes, name; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = name.substr( 5 ); - dataAttr( this[0], name, data[ name ] ); - } - } - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - var parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var $this = jQuery( this ), - args = [ parts[0], value ]; - - $this.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - $this.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - data = elem.getAttribute( "data-" + key ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - !jQuery.isNaN( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON -// property to be considered empty objects; this property always exists in -// order to make sure JSON.stringify does not expose internal metadata -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -jQuery.extend({ - queue: function( elem, type, data ) { - if ( !elem ) { - return; - } - - type = (type || "fx") + "queue"; - var q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( !data ) { - return q || []; - } - - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - - } else { - q.push( data ); - } - - return q; - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(); - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift("inprogress"); - } - - fn.call(elem, function() { - jQuery.dequeue(elem, type); - }); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue", true ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function( i ) { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue( type, function() { - var elem = this; - setTimeout(function() { - jQuery.dequeue( elem, type ); - }, time ); - }); - }, - - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspaces = /\s+/, - rreturn = /\r/g, - rspecialurl = /^(?:href|src|style)$/, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rradiocheck = /^(?:radio|checkbox)$/i; - -jQuery.props = { - "for": "htmlFor", - "class": "className", - readonly: "readOnly", - maxlength: "maxLength", - cellspacing: "cellSpacing", - rowspan: "rowSpan", - colspan: "colSpan", - tabindex: "tabIndex", - usemap: "useMap", - frameborder: "frameBorder" -}; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name, fn ) { - return this.each(function(){ - jQuery.attr( this, name, "" ); - if ( this.nodeType === 1 ) { - this.removeAttribute( name ); - } - }); - }, - - addClass: function( value ) { - if ( jQuery.isFunction(value) ) { - return this.each(function(i) { - var self = jQuery(this); - self.addClass( value.call(this, i, self.attr("class")) ); - }); - } - - if ( value && typeof value === "string" ) { - var classNames = (value || "").split( rspaces ); - - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className ) { - elem.className = value; - - } else { - var className = " " + elem.className + " ", - setClass = elem.className; - - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { - setClass += " " + classNames[c]; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - if ( jQuery.isFunction(value) ) { - return this.each(function(i) { - var self = jQuery(this); - self.removeClass( value.call(this, i, self.attr("class")) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - var classNames = (value || "").split( rspaces ); - - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - var className = (" " + elem.className + " ").replace(rclass, " "); - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[c] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function(i) { - var self = jQuery(this); - self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspaces ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " "; - for ( var i = 0, l = this.length; i < l; i++ ) { - if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - if ( !arguments.length ) { - var elem = this[0]; - - if ( elem ) { - if ( jQuery.nodeName( elem, "option" ) ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - - // We need to handle select boxes special - if ( jQuery.nodeName( elem, "select" ) ) { - var index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { - var option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery(option).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - } - - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { - return elem.getAttribute("value") === null ? "on" : elem.value; - } - - // Everything else, we just grab the value - return (elem.value || "").replace(rreturn, ""); - - } - - return undefined; - } - - var isFunction = jQuery.isFunction(value); - - return this.each(function(i) { - var self = jQuery(this), val = value; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call(this, i, self.val()); - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray(val) ) { - val = jQuery.map(val, function (value) { - return value == null ? "" : value + ""; - }); - } - - if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { - this.checked = jQuery.inArray( self.val(), val ) >= 0; - - } else if ( jQuery.nodeName( this, "select" ) ) { - var values = jQuery.makeArray(val); - - jQuery( "option", this ).each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - this.selectedIndex = -1; - } - - } else { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) { - return undefined; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery(elem)[name](value); - } - - var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), - // Whether we are setting (or getting) - set = value !== undefined; - - // Try to normalize/fix the name - name = notxml && jQuery.props[ name ] || name; - - // Only do all the following if this is a node (faster for style) - if ( elem.nodeType === 1 ) { - // These attributes require special treatment - var special = rspecialurl.test( name ); - - // Safari mis-reports the default selected property of an option - // Accessing the parent's selectedIndex property fixes it - if ( name === "selected" && !jQuery.support.optSelected ) { - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - - // If applicable, access the attribute via the DOM 0 way - // 'in' checks fail in Blackberry 4.7 #6931 - if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { - if ( set ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } - - if ( value === null ) { - if ( elem.nodeType === 1 ) { - elem.removeAttribute( name ); - } - - } else { - elem[ name ] = value; - } - } - - // browsers index elements by id/name on forms, give priority to attributes. - if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { - return elem.getAttributeNode( name ).nodeValue; - } - - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - if ( name === "tabIndex" ) { - var attributeNode = elem.getAttributeNode( "tabIndex" ); - - return attributeNode && attributeNode.specified ? - attributeNode.value : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - - return elem[ name ]; - } - - if ( !jQuery.support.style && notxml && name === "style" ) { - if ( set ) { - elem.style.cssText = "" + value; - } - - return elem.style.cssText; - } - - if ( set ) { - // convert the value to a string (all browsers do this but IE) see #1070 - elem.setAttribute( name, "" + value ); - } - - // Ensure that missing attributes return undefined - // Blackberry 4.7 returns "" from getAttribute #6938 - if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { - return undefined; - } - - var attr = !jQuery.support.hrefNormalized && notxml && special ? - // Some attributes require a special call on IE - elem.getAttribute( name, 2 ) : - elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return attr === null ? undefined : attr; - } - // Handle everything which isn't a DOM element node - if ( set ) { - elem[ name ] = value; - } - return elem[ name ]; - } -}); - - - - -var rnamespaces = /\.(.*)$/, - rformElems = /^(?:textarea|input|select)$/i, - rperiod = /\./g, - rspace = / /g, - rescape = /[^\w\s.|`]/g, - fcleanup = function( nm ) { - return nm.replace(rescape, "\\$&"); - }; - -/* - * A number of helper functions used for managing events. - * Many of the ideas behind this code originated from - * Dean Edwards' addEvent library. - */ -jQuery.event = { - - // Bind an event to an element - // Original by Dean Edwards - add: function( elem, types, handler, data ) { - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // TODO :: Use a try/catch until it's safe to pull this out (likely 1.6) - // Minor release fix for bug #8018 - try { - // For whatever reason, IE has trouble passing the window object - // around, causing it to be cloned in the process - if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { - elem = window; - } - } - catch ( e ) {} - - if ( handler === false ) { - handler = returnFalse; - } else if ( !handler ) { - // Fixes bug #7229. Fix recommended by jdalton - return; - } - - var handleObjIn, handleObj; - - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the function being executed has a unique ID - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure - var elemData = jQuery._data( elem ); - - // If no elemData is found then we must be trying to bind to one of the - // banned noData elements - if ( !elemData ) { - return; - } - - var events = elemData.events, - eventHandle = elemData.handle; - - if ( !events ) { - elemData.events = events = {}; - } - - if ( !eventHandle ) { - elemData.handle = eventHandle = function() { - // Handle the second event of a trigger and when - // an event is called after a page has unloaded - return typeof jQuery !== "undefined" && !jQuery.event.triggered ? - jQuery.event.handle.apply( eventHandle.elem, arguments ) : - undefined; - }; - } - - // Add elem as a property of the handle function - // This is to prevent a memory leak with non-native events in IE. - eventHandle.elem = elem; - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = types.split(" "); - - var type, i = 0, namespaces; - - while ( (type = types[ i++ ]) ) { - handleObj = handleObjIn ? - jQuery.extend({}, handleObjIn) : - { handler: handler, data: data }; - - // Namespaced event handlers - if ( type.indexOf(".") > -1 ) { - namespaces = type.split("."); - type = namespaces.shift(); - handleObj.namespace = namespaces.slice(0).sort().join("."); - - } else { - namespaces = []; - handleObj.namespace = ""; - } - - handleObj.type = type; - if ( !handleObj.guid ) { - handleObj.guid = handler.guid; - } - - // Get the current list of functions bound to this event - var handlers = events[ type ], - special = jQuery.event.special[ type ] || {}; - - // Init the event handler queue - if ( !handlers ) { - handlers = events[ type ] = []; - - // Check for a special event handler - // Only use addEventListener/attachEvent if the special - // events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add the function to the element's handler list - handlers.push( handleObj ); - - // Keep track of which events have been used, for global triggering - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, pos ) { - // don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - if ( handler === false ) { - handler = returnFalse; - } - - var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - events = elemData && elemData.events; - - if ( !elemData || !events ) { - return; - } - - // types is actually an event object here - if ( types && types.type ) { - handler = types.handler; - types = types.type; - } - - // Unbind all events for the element - if ( !types || typeof types === "string" && types.charAt(0) === "." ) { - types = types || ""; - - for ( type in events ) { - jQuery.event.remove( elem, type + types ); - } - - return; - } - - // Handle multiple events separated by a space - // jQuery(...).unbind("mouseover mouseout", fn); - types = types.split(" "); - - while ( (type = types[ i++ ]) ) { - origType = type; - handleObj = null; - all = type.indexOf(".") < 0; - namespaces = []; - - if ( !all ) { - // Namespaced event handlers - namespaces = type.split("."); - type = namespaces.shift(); - - namespace = new RegExp("(^|\\.)" + - jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - eventType = events[ type ]; - - if ( !eventType ) { - continue; - } - - if ( !handler ) { - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( all || namespace.test( handleObj.namespace ) ) { - jQuery.event.remove( elem, origType, handleObj.handler, j ); - eventType.splice( j--, 1 ); - } - } - - continue; - } - - special = jQuery.event.special[ type ] || {}; - - for ( j = pos || 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( handler.guid === handleObj.guid ) { - // remove the given handler for the given type - if ( all || namespace.test( handleObj.namespace ) ) { - if ( pos == null ) { - eventType.splice( j--, 1 ); - } - - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - - if ( pos != null ) { - break; - } - } - } - - // remove generic event handler if no more handlers exist - if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - ret = null; - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - var handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - delete elemData.events; - delete elemData.handle; - - if ( jQuery.isEmptyObject( elemData ) ) { - jQuery.removeData( elem, undefined, true ); - } - } - }, - - // bubbling is internal - trigger: function( event, data, elem /*, bubbling */ ) { - // Event object or event type - var type = event.type || event, - bubbling = arguments[3]; - - if ( !bubbling ) { - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - jQuery.extend( jQuery.Event(type), event ) : - // Just the event type (string) - jQuery.Event(type); - - if ( type.indexOf("!") >= 0 ) { - event.type = type = type.slice(0, -1); - event.exclusive = true; - } - - // Handle a global trigger - if ( !elem ) { - // Don't bubble custom events when global (to avoid too much overhead) - event.stopPropagation(); - - // Only trigger if we've ever bound an event for it - if ( jQuery.event.global[ type ] ) { - // XXX This code smells terrible. event.js should not be directly - // inspecting the data cache - jQuery.each( jQuery.cache, function() { - // internalKey variable is just used to make it easier to find - // and potentially change this stuff later; currently it just - // points to jQuery.expando - var internalKey = jQuery.expando, - internalCache = this[ internalKey ]; - if ( internalCache && internalCache.events && internalCache.events[ type ] ) { - jQuery.event.trigger( event, data, internalCache.handle.elem ); - } - }); - } - } - - // Handle triggering a single element - - // don't do events on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { - return undefined; - } - - // Clean up in case it is reused - event.result = undefined; - event.target = elem; - - // Clone the incoming data, if any - data = jQuery.makeArray( data ); - data.unshift( event ); - } - - event.currentTarget = elem; - - // Trigger the event, it is assumed that "handle" is a function - var handle = jQuery._data( elem, "handle" ); - - if ( handle ) { - handle.apply( elem, data ); - } - - var parent = elem.parentNode || elem.ownerDocument; - - // Trigger an inline bound script - try { - if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { - if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { - event.result = false; - event.preventDefault(); - } - } - - // prevent IE from throwing an error for some elements with some event types, see #3533 - } catch (inlineError) {} - - if ( !event.isPropagationStopped() && parent ) { - jQuery.event.trigger( event, data, parent, true ); - - } else if ( !event.isDefaultPrevented() ) { - var old, - target = event.target, - targetType = type.replace( rnamespaces, "" ), - isClick = jQuery.nodeName( target, "a" ) && targetType === "click", - special = jQuery.event.special[ targetType ] || {}; - - if ( (!special._default || special._default.call( elem, event ) === false) && - !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { - - try { - if ( target[ targetType ] ) { - // Make sure that we don't accidentally re-trigger the onFOO events - old = target[ "on" + targetType ]; - - if ( old ) { - target[ "on" + targetType ] = null; - } - - jQuery.event.triggered = true; - target[ targetType ](); - } - - // prevent IE from throwing an error for some elements with some event types, see #3533 - } catch (triggerError) {} - - if ( old ) { - target[ "on" + targetType ] = old; - } - - jQuery.event.triggered = false; - } - } - }, - - handle: function( event ) { - var all, handlers, namespaces, namespace_re, events, - namespace_sort = [], - args = jQuery.makeArray( arguments ); - - event = args[0] = jQuery.event.fix( event || window.event ); - event.currentTarget = this; - - // Namespaced event handlers - all = event.type.indexOf(".") < 0 && !event.exclusive; - - if ( !all ) { - namespaces = event.type.split("."); - event.type = namespaces.shift(); - namespace_sort = namespaces.slice(0).sort(); - namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - event.namespace = event.namespace || namespace_sort.join("."); - - events = jQuery._data(this, "events"); - - handlers = (events || {})[ event.type ]; - - if ( events && handlers ) { - // Clone the handlers to prevent manipulation - handlers = handlers.slice(0); - - for ( var j = 0, l = handlers.length; j < l; j++ ) { - var handleObj = handlers[ j ]; - - // Filter the functions by class - if ( all || namespace_re.test( handleObj.namespace ) ) { - // Pass in a reference to the handler function itself - // So that we can later remove it - event.handler = handleObj.handler; - event.data = handleObj.data; - event.handleObj = handleObj; - - var ret = handleObj.handler.apply( this, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - } - - return event.result; - }, - - props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // store a copy of the original event object - // and "clone" to set read-only properties - var originalEvent = event; - event = jQuery.Event( originalEvent ); - - for ( var i = this.props.length, prop; i; ) { - prop = this.props[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary - if ( !event.target ) { - // Fixes #1925 where srcElement might not be defined either - event.target = event.srcElement || document; - } - - // check if target is a textnode (safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && event.fromElement ) { - event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; - } - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && event.clientX != null ) { - var doc = document.documentElement, - body = document.body; - - event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add which for key events - if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { - event.which = event.charCode != null ? event.charCode : event.keyCode; - } - - // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) - if ( !event.metaKey && event.ctrlKey ) { - event.metaKey = event.ctrlKey; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && event.button !== undefined ) { - event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); - } - - return event; - }, - - // Deprecated, use jQuery.guid instead - guid: 1E8, - - // Deprecated, use jQuery.proxy instead - proxy: jQuery.proxy, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady, - teardown: jQuery.noop - }, - - live: { - add: function( handleObj ) { - jQuery.event.add( this, - liveConvert( handleObj.origType, handleObj.selector ), - jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); - }, - - remove: function( handleObj ) { - jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); - } - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - } -}; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src ) { - // Allow instantiation without the 'new' keyword - if ( !this.preventDefault ) { - return new jQuery.Event( src ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // timeStamp is buggy for some events on Firefox(#3843) - // So we won't rely on the native value - this.timeStamp = jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Checks if an event happened on an element within another element -// Used in jQuery.event.special.mouseenter and mouseleave handlers -var withinElement = function( event ) { - // Check if mouse(over|out) are still within the same parent element - var parent = event.relatedTarget; - - // Firefox sometimes assigns relatedTarget a XUL element - // which we cannot access the parentNode property of - try { - - // Chrome does something similar, the parentNode property - // can be accessed but is null. - if ( parent !== document && !parent.parentNode ) { - return; - } - // Traverse up the tree - while ( parent && parent !== this ) { - parent = parent.parentNode; - } - - if ( parent !== this ) { - // set the correct event type - event.type = event.data; - - // handle event if we actually just moused on to a non sub-element - jQuery.event.handle.apply( this, arguments ); - } - - // assuming we've left the element since we most likely mousedover a xul element - } catch(e) { } -}, - -// In case of event delegation, we only need to rename the event.type, -// liveHandler will take care of the rest. -delegate = function( event ) { - event.type = event.data; - jQuery.event.handle.apply( this, arguments ); -}; - -// Create mouseenter and mouseleave events -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - setup: function( data ) { - jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); - }, - teardown: function( data ) { - jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); - } - }; -}); - -// submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function( data, namespaces ) { - if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) { - jQuery.event.add(this, "click.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { - trigger( "submit", this, arguments ); - } - }); - - jQuery.event.add(this, "keypress.specialSubmit", function( e ) { - var elem = e.target, - type = elem.type; - - if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { - trigger( "submit", this, arguments ); - } - }); - - } else { - return false; - } - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialSubmit" ); - } - }; - -} - -// change delegation, happens here so we have bind. -if ( !jQuery.support.changeBubbles ) { - - var changeFilters, - - getVal = function( elem ) { - var type = elem.type, val = elem.value; - - if ( type === "radio" || type === "checkbox" ) { - val = elem.checked; - - } else if ( type === "select-multiple" ) { - val = elem.selectedIndex > -1 ? - jQuery.map( elem.options, function( elem ) { - return elem.selected; - }).join("-") : - ""; - - } else if ( elem.nodeName.toLowerCase() === "select" ) { - val = elem.selectedIndex; - } - - return val; - }, - - testChange = function testChange( e ) { - var elem = e.target, data, val; - - if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { - return; - } - - data = jQuery._data( elem, "_change_data" ); - val = getVal(elem); - - // the current data will be also retrieved by beforeactivate - if ( e.type !== "focusout" || elem.type !== "radio" ) { - jQuery._data( elem, "_change_data", val ); - } - - if ( data === undefined || val === data ) { - return; - } - - if ( data != null || val ) { - e.type = "change"; - e.liveFired = undefined; - jQuery.event.trigger( e, arguments[1], elem ); - } - }; - - jQuery.event.special.change = { - filters: { - focusout: testChange, - - beforedeactivate: testChange, - - click: function( e ) { - var elem = e.target, type = elem.type; - - if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { - testChange.call( this, e ); - } - }, - - // Change has to be called before submit - // Keydown will be called before keypress, which is used in submit-event delegation - keydown: function( e ) { - var elem = e.target, type = elem.type; - - if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || - (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || - type === "select-multiple" ) { - testChange.call( this, e ); - } - }, - - // Beforeactivate happens also before the previous element is blurred - // with this event you can't trigger a change event, but you can store - // information - beforeactivate: function( e ) { - var elem = e.target; - jQuery._data( elem, "_change_data", getVal(elem) ); - } - }, - - setup: function( data, namespaces ) { - if ( this.type === "file" ) { - return false; - } - - for ( var type in changeFilters ) { - jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); - } - - return rformElems.test( this.nodeName ); - }, - - teardown: function( namespaces ) { - jQuery.event.remove( this, ".specialChange" ); - - return rformElems.test( this.nodeName ); - } - }; - - changeFilters = jQuery.event.special.change.filters; - - // Handle when the input is .focus()'d - changeFilters.focus = changeFilters.beforeactivate; -} - -function trigger( type, elem, args ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - // Don't pass args or remember liveFired; they apply to the donor event. - var event = jQuery.extend( {}, args[ 0 ] ); - event.type = type; - event.originalEvent = {}; - event.liveFired = undefined; - jQuery.event.handle.call( elem, event ); - if ( event.isDefaultPrevented() ) { - args[ 0 ].preventDefault(); - } -} - -// Create "bubbling" focus and blur events -if ( document.addEventListener ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - jQuery.event.special[ fix ] = { - setup: function() { - this.addEventListener( orig, handler, true ); - }, - teardown: function() { - this.removeEventListener( orig, handler, true ); - } - }; - - function handler( e ) { - e = jQuery.event.fix( e ); - e.type = fix; - return jQuery.event.handle.call( this, e ); - } - }); -} - -jQuery.each(["bind", "one"], function( i, name ) { - jQuery.fn[ name ] = function( type, data, fn ) { - // Handle object literals - if ( typeof type === "object" ) { - for ( var key in type ) { - this[ name ](key, data, type[key], fn); - } - return this; - } - - if ( jQuery.isFunction( data ) || data === false ) { - fn = data; - data = undefined; - } - - var handler = name === "one" ? jQuery.proxy( fn, function( event ) { - jQuery( this ).unbind( event, handler ); - return fn.apply( this, arguments ); - }) : fn; - - if ( type === "unload" && name !== "one" ) { - this.one( type, data, fn ); - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.add( this[i], type, handler, data ); - } - } - - return this; - }; -}); - -jQuery.fn.extend({ - unbind: function( type, fn ) { - // Handle object literals - if ( typeof type === "object" && !type.preventDefault ) { - for ( var key in type ) { - this.unbind(key, type[key]); - } - - } else { - for ( var i = 0, l = this.length; i < l; i++ ) { - jQuery.event.remove( this[i], type, fn ); - } - } - - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.live( types, data, fn, selector ); - }, - - undelegate: function( selector, types, fn ) { - if ( arguments.length === 0 ) { - return this.unbind( "live" ); - - } else { - return this.die( types, null, fn, selector ); - } - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - - triggerHandler: function( type, data ) { - if ( this[0] ) { - var event = jQuery.Event( type ); - event.preventDefault(); - event.stopPropagation(); - jQuery.event.trigger( event, data, this[0] ); - return event.result; - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - i = 1; - - // link all the functions, so any of them can unbind this click handler - while ( i < args.length ) { - jQuery.proxy( fn, args[ i++ ] ); - } - - return this.click( jQuery.proxy( fn, function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - })); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -var liveMap = { - focus: "focusin", - blur: "focusout", - mouseenter: "mouseover", - mouseleave: "mouseout" -}; - -jQuery.each(["live", "die"], function( i, name ) { - jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { - var type, i = 0, match, namespaces, preType, - selector = origSelector || this.selector, - context = origSelector ? this : jQuery( this.context ); - - if ( typeof types === "object" && !types.preventDefault ) { - for ( var key in types ) { - context[ name ]( key, data, types[key], selector ); - } - - return this; - } - - if ( jQuery.isFunction( data ) ) { - fn = data; - data = undefined; - } - - types = (types || "").split(" "); - - while ( (type = types[ i++ ]) != null ) { - match = rnamespaces.exec( type ); - namespaces = ""; - - if ( match ) { - namespaces = match[0]; - type = type.replace( rnamespaces, "" ); - } - - if ( type === "hover" ) { - types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); - continue; - } - - preType = type; - - if ( type === "focus" || type === "blur" ) { - types.push( liveMap[ type ] + namespaces ); - type = type + namespaces; - - } else { - type = (liveMap[ type ] || type) + namespaces; - } - - if ( name === "live" ) { - // bind live handler - for ( var j = 0, l = context.length; j < l; j++ ) { - jQuery.event.add( context[j], "live." + liveConvert( type, selector ), - { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); - } - - } else { - // unbind live handler - context.unbind( "live." + liveConvert( type, selector ), fn ); - } - } - - return this; - }; -}); - -function liveHandler( event ) { - var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, - elems = [], - selectors = [], - events = jQuery._data( this, "events" ); - - // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) - if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { - return; - } - - if ( event.namespace ) { - namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); - } - - event.liveFired = this; - - var live = events.live.slice(0); - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { - selectors.push( handleObj.selector ); - - } else { - live.splice( j--, 1 ); - } - } - - match = jQuery( event.target ).closest( selectors, event.currentTarget ); - - for ( i = 0, l = match.length; i < l; i++ ) { - close = match[i]; - - for ( j = 0; j < live.length; j++ ) { - handleObj = live[j]; - - if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { - elem = close.elem; - related = null; - - // Those two events require additional checking - if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { - event.type = handleObj.preType; - related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; - } - - if ( !related || related !== elem ) { - elems.push({ elem: elem, handleObj: handleObj, level: close.level }); - } - } - } - } - - for ( i = 0, l = elems.length; i < l; i++ ) { - match = elems[i]; - - if ( maxLevel && match.level > maxLevel ) { - break; - } - - event.currentTarget = match.elem; - event.data = match.handleObj.data; - event.handleObj = match.handleObj; - - ret = match.handleObj.origHandler.apply( match.elem, arguments ); - - if ( ret === false || event.isPropagationStopped() ) { - maxLevel = match.level; - - if ( ret === false ) { - stop = false; - } - if ( event.isImmediatePropagationStopped() ) { - break; - } - } - } - - return stop; -} - -function liveConvert( type, selector ) { - return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); -} - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.bind( name, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } -}); - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set; - - if ( !expr ) { - return []; - } - - for ( var i = 0, l = Expr.order.length; i < l; i++ ) { - var match, - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - var left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( var type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - var found, item, - filter = Expr.filter[ type ], - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( var i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - var pass = not ^ !!found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw "Syntax error, unrecognized expression: " + msg; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return "text" === elem.getAttribute( 'type' ); - }, - radio: function( elem ) { - return "radio" === elem.type; - }, - - checkbox: function( elem ) { - return "checkbox" === elem.type; - }, - - file: function( elem ) { - return "file" === elem.type; - }, - password: function( elem ) { - return "password" === elem.type; - }, - - submit: function( elem ) { - return "submit" === elem.type; - }, - - image: function( elem ) { - return "image" === elem.type; - }, - - reset: function( elem ) { - return "reset" === elem.type; - }, - - button: function( elem ) { - return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - var first = match[2], - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - var doneName = match[0], - parent = elem.parentNode; - - if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { - var count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent.sizcache = doneName; - } - - var diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // If the nodes are siblings (or identical) we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Utility function for retreiving the text value of an array of DOM nodes -Sizzle.getText = function( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += Sizzle.getText( elem.childNodes ); - } - } - - return ret; -}; - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector, - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - if ( matches ) { - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - return matches.call( node, expr ); - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem.sizcache === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem.sizcache = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var ret = this.pushStack( "", "find", selector ), - length = 0; - - for ( var i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( var n = length; n < ret.length; n++ ) { - for ( var r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && jQuery.filter( selector, this ).length > 0; - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - if ( jQuery.isArray( selectors ) ) { - var match, selector, - matches = {}, - level = 1; - - if ( cur && selectors.length ) { - for ( i = 0, l = selectors.length; i < l; i++ ) { - selector = selectors[i]; - - if ( !matches[selector] ) { - matches[selector] = jQuery.expr.match.POS.test( selector ) ? - jQuery( selector, context || this.context ) : - selector; - } - } - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( selector in matches ) { - match = matches[selector]; - - if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { - ret.push({ selector: selector, elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - } - - return ret; - } - - var pos = POS.test( selectors ) ? - jQuery( selectors, context || this.context ) : null; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique(ret) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - if ( !elem || typeof elem === "string" ) { - return jQuery.inArray( this[0], - // If it receives a string, the selector is used - // If it receives nothing, the siblings are used - elem ? jQuery( elem ) : this.parent().children() ); - } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ), - // The variable 'args' was introduced in - // https://github.com/jquery/jquery/commit/52a0238 - // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. - // http://code.google.com/p/v8/issues/detail?id=1050 - args = slice.call(arguments); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, args.join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return (elem === qualifier) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return (jQuery.inArray( elem, qualifier ) >= 0) === keep; - }); -} - - - - -var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
", "
" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - col: [ 2, "", "
" ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and - - - - - - CRCE - ${param.title} - - - - -
- - - - - - - - - - - - - - - - - - - - -
- - - -
- -
-
- - - - -
${message}
-
- -
${message}
-
-
- - -
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> + + + + + + + + + + + + + + + + CRCE - ${param.title} + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + + +
+ +
+
+ + + + +
${message}
+
+ +
${message}
+
+
+ + +
diff --git a/modules/crce-webui/src/main/webapp/jsp/maven.jsp b/modules/crce-webui/src/main/webapp/jsp/maven.jsp new file mode 100644 index 00000000..0c3494f6 --- /dev/null +++ b/modules/crce-webui/src/main/webapp/jsp/maven.jsp @@ -0,0 +1,153 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + +<% + // TODO: just one form + +%> + + + + + + +
+

Maven artifacts search

+ +
+ + + + + + + + + + + +
+

Search by maven coordinates

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
Version filter:
+
+
+
+ +

Search by fully qualified name

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version filter
+
+
GroupId filter
+
+
+
+ +
+
+ + \ No newline at end of file diff --git a/modules/crce-webui/src/main/webapp/jsp/plugins.jsp b/modules/crce-webui/src/main/webapp/jsp/plugins.jsp index ff12f87d..9abe8387 100644 --- a/modules/crce-webui/src/main/webapp/jsp/plugins.jsp +++ b/modules/crce-webui/src/main/webapp/jsp/plugins.jsp @@ -1,49 +1,49 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - -
- - -
-
- -
- edit -
-
-
-
-
Description: ${plugin.pluginDescription}
-
Priority: ${plugin.pluginPriority} [edit]
-
Version: ${plugin.pluginVersion} [edit]
-
Keywords: -
    - -
  • ${keyword}
  • -
    -
-
-
-
-
- - -
-
No plugins.
-
-
- - - - -
- +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + + + +
+ + +
+
+ +
+ edit +
+
+
+
+
Description: ${plugin.pluginDescription}
+
Priority: ${plugin.pluginPriority} [edit]
+
Version: ${plugin.pluginVersion} [edit]
+
Keywords: +
    + +
  • ${keyword}
  • +
    +
+
+
+
+
+ + +
+
No plugins.
+
+
+ + + + +
+ \ No newline at end of file diff --git a/modules/crce-webui/src/main/webapp/jsp/store.jsp b/modules/crce-webui/src/main/webapp/jsp/store.jsp index e122822d..f72fc2db 100644 --- a/modules/crce-webui/src/main/webapp/jsp/store.jsp +++ b/modules/crce-webui/src/main/webapp/jsp/store.jsp @@ -1,178 +1,178 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - -
- -
- - -
${resource.satisfied} - - - - uspech1 - - - neuspech1 - - - - "> - -
-
Properties: [edit] -
    -
  • Id: ${resource.id}
  • -
  • Symbolic name: ${resource.symbolicName}
  • -
  • Size: ${resource.size}
  • -
  • Export Meta-Data: LINK
  • -
-
    - -
  • - ${newProperty.name} - - - - -
    ${property.name}${property.type}${property.value}
    -
  • -
    -
-
-
Categories: [edit] -
    - -
  • ${category}
  • -
    -
-
-
-
Capabilities: [add new] -
    - -
  • - ${capability.name} [edit] - - - - -
    ${property.name}${property.type}${property.value}
    - -
      - -
    • - ${newProperty.name} - - - - -
      ${property.name}${property.type}${property.value}
      -
    • -
      -
    - -
  • -
    -
-
-
Requirements: [edit] - - - - - ${requirement.satisfied} - - - - - - - - - - - ${requirement.satisfied} - - - - class="uspech" - - - class="neuspech" - - - - > - - - - - - - - - - - -
NameFilterMultipleOptionalExtend
Comment
Unsatisfied requirements:
${requirement.name}${requirement.filter}${requirement.multiple}${requirement.optional}${requirement.extend}
${requirement.comment}
-
-
-
-
- - -
-
No resources in store.
-
-
- - - - - - -
- -
-
-
- -
-
- -
-
-
-
-
- +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + + + +
+ +
+ + +
${resource.satisfied} + + + + uspech1 + + + neuspech1 + + + + "> + +
+
Properties: [edit] +
    +
  • Id: ${resource.id}
  • +
  • Symbolic name: ${resource.symbolicName}
  • +
  • Size: ${resource.size}
  • +
  • Export Meta-Data: LINK
  • +
+
    + +
  • + ${newProperty.name} + + + + +
    ${property.name}${property.type}${property.value}
    +
  • +
    +
+
+
Categories: [edit] +
    + +
  • ${category}
  • +
    +
+
+
+
Capabilities: [add new] +
    + +
  • + ${capability.name} [edit] + + + + +
    ${property.name}${property.type}${property.value}
    + +
      + +
    • + ${newProperty.name} + + + + +
      ${property.name}${property.type}${property.value}
      +
    • +
      +
    + +
  • +
    +
+
+
Requirements: [edit] + + + + + ${requirement.satisfied} + + + + + + + + + + + ${requirement.satisfied} + + + + class="uspech" + + + class="neuspech" + + + + > + + + + + + + + + + + +
NameFilterMultipleOptionalExtend
Comment
Unsatisfied requirements:
${requirement.name}${requirement.filter}${requirement.multiple}${requirement.optional}${requirement.extend}
${requirement.comment}
+
+
+
+
+ + +
+
No resources in store.
+
+
+ + + + + + +
+ +
+
+
+ +
+
+ +
+
+
+
+
+ \ No newline at end of file diff --git a/modules/crce-webui/src/main/webapp/jsp/tags.jsp b/modules/crce-webui/src/main/webapp/jsp/tags.jsp index 5069d6c2..3704aba4 100644 --- a/modules/crce-webui/src/main/webapp/jsp/tags.jsp +++ b/modules/crce-webui/src/main/webapp/jsp/tags.jsp @@ -1,146 +1,146 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - -
- -
- - - Store: - - - Store: - - - - - - Buffer: - - - Buffer: - - - - -
- - - - -
- -
${resource.satisfied} - - - - uspech1 - - - neuspech1 - - - - "> - -
-
Properties: -
    -
  • Id: ${resource.id}
  • -
  • Symbolic name: ${resource.symbolicName}
  • -
  • Size: ${resource.size}
  • -
-
-
Categories: -
    - -
  • ${category}
  • -
    -
-
-
Capabilities: -
    - -
  • - ${capability.name} - - - - - - - - -
    ${property.name}${property.type}${property.value}
    -
  • -
    -
-
-
Requirements: - - - - - ${requirement.satisfied} - - - - class="uspech" - - - class="neuspech" - - - - > - - - - - - - - - - -
NameFilterMultipleOptionalExtend
Comment
${requirement.name}${requirement.filter}${requirement.multiple}${requirement.optional}${requirement.extend}
${requirement.comment}
-
-
-
-
-
- - -
- +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + + + +
+ +
+ + + Store: + + + Store: + + + + + + Buffer: + + + Buffer: + + + + +
+ + + + +
+ +
${resource.satisfied} + + + + uspech1 + + + neuspech1 + + + + "> + +
+
Properties: +
    +
  • Id: ${resource.id}
  • +
  • Symbolic name: ${resource.symbolicName}
  • +
  • Size: ${resource.size}
  • +
+
+
Categories: +
    + +
  • ${category}
  • +
    +
+
+
Capabilities: +
    + +
  • + ${capability.name} + + + + + + + + +
    ${property.name}${property.type}${property.value}
    +
  • +
    +
+
+
Requirements: + + + + + ${requirement.satisfied} + + + + class="uspech" + + + class="neuspech" + + + + > + + + + + + + + + + +
NameFilterMultipleOptionalExtend
Comment
${requirement.name}${requirement.filter}${requirement.multiple}${requirement.optional}${requirement.extend}
${requirement.comment}
+
+
+
+
+
+ + +
+ \ No newline at end of file diff --git a/modules/crce-webui/src/main/webapp/test.jsp b/modules/crce-webui/src/main/webapp/test.jsp index d6d47d25..5a9ce94a 100644 --- a/modules/crce-webui/src/main/webapp/test.jsp +++ b/modules/crce-webui/src/main/webapp/test.jsp @@ -1,142 +1,142 @@ -<%@page import="cz.zcu.kiv.crce.plugin.Plugin"%> -<%@page import="cz.zcu.kiv.crce.metadata.Requirement"%> -<%@page import="cz.zcu.kiv.crce.metadata.Property"%> -<%@page import="cz.zcu.kiv.crce.metadata.Capability"%> -<%@page import="cz.zcu.kiv.crce.repository.Buffer"%> -<%@page import="cz.zcu.kiv.crce.webui.internal.Activator"%> -<%@page import="cz.zcu.kiv.crce.metadata.Resource"%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> - - <% - //String hello = (String) session.getAttribute("hello"); - Resource[] resources = (Resource[]) session.getAttribute("resources"); - Plugin[] plugins = (Plugin[]) session.getAttribute("plugins"); - Resource[] store = (Resource[]) session.getAttribute("store"); - if(/*hello!=null &&*/ resources!=null && plugins!=null && store!=null) - { - //out.print(hello); - out.print("Resources size : "+resources.length+" Plugin size: "+plugins.length+" Store length: "+store.length); - } - else out.print("DIED"); - %> - - - - - - - - - - - - - - - Software components storage - - - - -
- -
-
logo
-
Software components storage
- -
-
- - -
-
-
-
- - - -
- - -
- -
-
Id: ${resource.id}
-
Symbolic name: ${resource.symbolicName}
-
URI: ${resource.uri}
-
Relative URI: ${resource.relativeUri}
-
Size: ${resource.size}
-
Categories: -
    - -
  • ${category}
  • -
    -
-
-
Capabilities: -
    - -
  • ${capability.name}
  • -
    -
-
-
Requirements: -
    - -
  • ${requirement.name} - ${requirement.filter}
  • -
    -
-
-
-
-
- - -
- -
© ASWI project 2011
- -
- - - - - +<%@page import="cz.zcu.kiv.crce.plugin.Plugin"%> +<%@page import="cz.zcu.kiv.crce.metadata.Requirement"%> +<%@page import="cz.zcu.kiv.crce.metadata.Property"%> +<%@page import="cz.zcu.kiv.crce.metadata.Capability"%> +<%@page import="cz.zcu.kiv.crce.repository.Buffer"%> +<%@page import="cz.zcu.kiv.crce.webui.internal.Activator"%> +<%@page import="cz.zcu.kiv.crce.metadata.Resource"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> + + <% + //String hello = (String) session.getAttribute("hello"); + Resource[] resources = (Resource[]) session.getAttribute("resources"); + Plugin[] plugins = (Plugin[]) session.getAttribute("plugins"); + Resource[] store = (Resource[]) session.getAttribute("store"); + if(/*hello!=null &&*/ resources!=null && plugins!=null && store!=null) + { + //out.print(hello); + out.print("Resources size : "+resources.length+" Plugin size: "+plugins.length+" Store length: "+store.length); + } + else out.print("DIED"); + %> + + + + + + + + + + + + + + + Software components storage + + + + +
+ +
+
logo
+
Software components storage
+ +
+
+ + +
+
+
+
+ + + +
+ + +
+ +
+
Id: ${resource.id}
+
Symbolic name: ${resource.symbolicName}
+
URI: ${resource.uri}
+
Relative URI: ${resource.relativeUri}
+
Size: ${resource.size}
+
Categories: +
    + +
  • ${category}
  • +
    +
+
+
Capabilities: +
    + +
  • ${capability.name}
  • +
    +
+
+
Requirements: +
    + +
  • ${requirement.name} - ${requirement.filter}
  • +
    +
+
+
+
+
+ + +
+ +
© ASWI project 2011
+ +
+ + + + + diff --git a/modules/crce-webui/src/test/java/cz/zcu/kiv/crce/webui/internal/ResourceServletTest.java b/modules/crce-webui/src/test/java/cz/zcu/kiv/crce/webui/internal/ResourceServletTest.java index f3d39f55..628850fd 100644 --- a/modules/crce-webui/src/test/java/cz/zcu/kiv/crce/webui/internal/ResourceServletTest.java +++ b/modules/crce-webui/src/test/java/cz/zcu/kiv/crce/webui/internal/ResourceServletTest.java @@ -1,40 +1,40 @@ -package cz.zcu.kiv.crce.webui.internal; - -import static org.junit.Assert.*; - - -import java.io.IOException; -import java.net.MalformedURLException; - -import org.junit.Ignore; -import org.junit.Test; - -import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - - -@Ignore -public class ResourceServletTest { - - - @Test - public void testDoGetHttpServletRequestHttpServletResponse() { - WebClient webClient = new WebClient(); - HtmlPage currentPage; - try { - currentPage =(HtmlPage) webClient.getPage("http://localhost:8090/crce/resource"); - - String pageAsText = currentPage.asText(); - assertTrue("Page does not contains uri: cz.zcu.kiv.crce.repository.api", pageAsText.contains("cz.zcu.kiv.crce.repository.api")); - } catch (FailingHttpStatusCodeException e) { - fail("FHSCE: " + e.toString()); - } catch (MalformedURLException e) { - fail("MUE: " + e.toString()); - } catch (IOException e) { - fail("IOE: " + e.toString()); - } - } - - -} +package cz.zcu.kiv.crce.webui.internal; + +import static org.junit.Assert.*; + + +import java.io.IOException; +import java.net.MalformedURLException; + +import org.junit.Ignore; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + + +@Ignore +public class ResourceServletTest { + + + @Test + public void testDoGetHttpServletRequestHttpServletResponse() { + WebClient webClient = new WebClient(); + HtmlPage currentPage; + try { + currentPage =(HtmlPage) webClient.getPage("http://localhost:8090/crce/resource"); + + String pageAsText = currentPage.asText(); + assertTrue("Page does not contains uri: cz.zcu.kiv.crce.repository.api", pageAsText.contains("cz.zcu.kiv.crce.repository.api")); + } catch (FailingHttpStatusCodeException e) { + fail("FHSCE: " + e.toString()); + } catch (MalformedURLException e) { + fail("MUE: " + e.toString()); + } catch (IOException e) { + fail("IOE: " + e.toString()); + } + } + + +} diff --git a/modules/pom.xml b/modules/pom.xml index 60173cc6..9bbbd998 100644 --- a/modules/pom.xml +++ b/modules/pom.xml @@ -1,171 +1,174 @@ - - - - 4.0.0 - - - pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - crce-modules-reactor - pom - - CRCE - Modules - Reactor - - Component Repository supporting Compatibility Evaluation - - - 3.0.4 - - - - https://github.com/ReliSA/crce/tree/master/modules - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - 8080 - 8443 - false - UTF-8 - false - 2000 - ../conf - .*\\.cfg - ../conf/logback.xml - - javax.inject,javax.jmdns,javax.jms,javax.mail,javax.mail.internet,javax.microedition.io - - - sun.*,com.sun.* - - - - 1.7.7 - 1.1.2 - - - - pom - provision - - - crce-metadata-osgi-bundle - - - - - - - - crce-handler-metrics - crce-webui - - - crce-rest-v2 - - crce-compatibility-api - crce-compatibility-dao-api - crce-compatibility-dao-mongodb - crce-concurrency - crce-vo - - - - crce-webservices-indexer - - - - - target - - crce-target - - - - run-it - - crce-integration-tests - - - - - - - - - org.ops4j - maven-pax-plugin - - - --vmOptions=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=65505 - - --platform=felix - - --repositories=http://uk.maven.org/maven2,http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public,http://repository.ops4j.org/maven2 - - - mvn:org.slf4j/slf4j-api/${version.org.slf4j}@1 - mvn:org.slf4j/osgi-over-slf4j/${version.org.slf4j}@1 - mvn:org.slf4j/log4j-over-slf4j/${version.org.slf4j}@1 - mvn:org.slf4j/jcl-over-slf4j/${version.org.slf4j}@1 - mvn:org.slf4j/jul-to-slf4j/${version.org.slf4j}@1 - mvn:ch.qos.logback/logback-core/${version.logback}@1 - mvn:ch.qos.logback/logback-classic/${version.logback}@1 - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.6 - - ${project.build.sourceEncoding} - - - - copy-resources - validate - - copy-resources - - - conf - - - conf.default - - - false - - - - - - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + + pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + crce-modules-reactor + pom + + CRCE - Modules - Reactor + + Component Repository supporting Compatibility Evaluation + + + 3.0.4 + + + + https://github.com/ReliSA/crce/tree/master/modules + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + 8080 + 8443 + false + UTF-8 + false + 2000 + ../conf + .*\\.cfg + ../conf/logback.xml + + javax.inject,javax.jmdns,javax.jms,javax.mail,javax.mail.internet,javax.microedition.io + + + sun.*,com.sun.* + + + + 1.7.7 + 1.1.2 + + + + pom + provision + + + crce-metadata-osgi-bundle + + + + + + + + crce-handler-metrics + crce-webui + + + crce-rest-v2 + + crce-compatibility-api + crce-compatibility-dao-api + crce-compatibility-dao-mongodb + crce-concurrency + crce-vo + + + + + + crce-webservices-indexer + crce-mvn-plugin + + + + + target + + crce-target + + + + run-it + + crce-integration-tests + + + + + + + + + org.ops4j + maven-pax-plugin + + + --vmOptions=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=65505 + + --platform=felix + + --repositories=http://uk.maven.org/maven2,http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public,http://repository.ops4j.org/maven2 + + + mvn:org.slf4j/slf4j-api/${version.org.slf4j}@1 + mvn:org.slf4j/osgi-over-slf4j/${version.org.slf4j}@1 + mvn:org.slf4j/log4j-over-slf4j/${version.org.slf4j}@1 + mvn:org.slf4j/jcl-over-slf4j/${version.org.slf4j}@1 + mvn:org.slf4j/jul-to-slf4j/${version.org.slf4j}@1 + mvn:ch.qos.logback/logback-core/${version.logback}@1 + mvn:ch.qos.logback/logback-classic/${version.logback}@1 + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${project.build.sourceEncoding} + + + + copy-resources + validate + + copy-resources + + + conf + + + conf.default + + + false + + + + + + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/modules/pom/pom.xml b/modules/pom/pom.xml index 85743560..f7ae505e 100644 --- a/modules/pom/pom.xml +++ b/modules/pom/pom.xml @@ -1,93 +1,107 @@ - - - - 4.0.0 - - - cz.zcu.kiv.crce - compiled-bundle-settings - 2.1.1 - - - - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - pom - - CRCE - Modules Parent - - Component Repository supporting Compatibility Evaluation - - - - - - - - - - - ${project.groupId} - crce-core - 3.0.0-SNAPSHOT - pom - - - - - - javax.ws.rs - javax.ws.rs-api - 2.0 - - - org.glassfish.jersey.containers - jersey-container-servlet-core - 2.9.1 - - - org.glassfish.jersey.media - jersey-media-multipart - 2.9.1 - - - org.glassfish.jersey.media - jersey-media-json-jackson - 2.9.1 - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${version.com.fasterxml.jackson} - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - ${version.com.fasterxml.jackson} - - - - - - - - - - - central - http://uk.maven.org/maven2/ - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public/ - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - + + + + 4.0.0 + + + cz.zcu.kiv.crce + compiled-bundle-settings + 2.1.1 + + + + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + pom + + CRCE - Modules Parent + + Component Repository supporting Compatibility Evaluation + + + 2.9.1 + + + + + + + + + ${project.groupId} + crce-core + 3.0.0-SNAPSHOT + pom + + + + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${version.com.fasterxml.jackson} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${version.com.fasterxml.jackson} + + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + + + + + org.glassfish.jersey.media + jersey-media-moxy + ${jersey.version} + + + + + + + + + + + central + http://uk.maven.org/maven2/ + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public/ + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + diff --git a/modules/provision/pom.xml b/modules/provision/pom.xml index 1e5a075c..564e04e2 100644 --- a/modules/provision/pom.xml +++ b/modules/provision/pom.xml @@ -1,171 +1,171 @@ - - - - 4.0.0 - - - ../pom - cz.zcu.kiv.crce - crce-modules-parent - 2.1.1-SNAPSHOT - - - provision - - CRCE - Provision - - pom - - - - - - - - org.osgi - org.osgi.core - - - org.osgi - org.osgi.compendium - - - - - - org.ops4j.pax.web - pax-web-extender-war - - - org.ops4j.pax.web - pax-web-jetty-bundle - - - org.ops4j.pax.web - pax-web-jsp - - - org.ops4j.pax.web - pax-web-spi - - - - - - org.apache.felix - org.apache.felix.configadmin - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.apache.felix - org.apache.felix.gogo.runtime - - - - - org.apache.felix - org.apache.felix.dependencymanager.runtime - - - org.apache.felix - org.apache.felix.eventadmin - - - org.apache.felix - org.apache.felix.scr - - - org.apache.felix - org.apache.felix.webconsole - - - org.apache.felix - org.apache.felix.shell - - - org.apache.felix - org.apache.felix.bundlerepository - - - org.apache.felix - org.apache.felix.fileinstall - - - org.apache.felix - org.osgi.service.obr - - - - - - asm - asm-all - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.commons-vfs - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.bcel - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.jaxp-ri - - - com.google.code.gson - gson - - - org.codehaus.groovy - groovy-all - - - commons-fileupload - commons-fileupload - - - commons-io - commons-io - - - de.twentyeleven.skysail - org.json-osgi - - - org.apache.xbean - xbean-finder - - - - org.mybatis - mybatis - - - - com.h2database - h2 - - - - - - cz.zcu.kiv.crce - crce-core - pom - - - - + + + + 4.0.0 + + + ../pom + cz.zcu.kiv.crce + crce-modules-parent + 2.1.1-SNAPSHOT + + + provision + + CRCE - Provision + + pom + + + + + + + + org.osgi + org.osgi.core + + + org.osgi + org.osgi.compendium + + + + + + org.ops4j.pax.web + pax-web-extender-war + + + org.ops4j.pax.web + pax-web-jetty-bundle + + + org.ops4j.pax.web + pax-web-jsp + + + org.ops4j.pax.web + pax-web-spi + + + + + + org.apache.felix + org.apache.felix.configadmin + + + org.apache.felix + org.apache.felix.dependencymanager + + + org.apache.felix + org.apache.felix.dependencymanager.shell + + + org.apache.felix + org.apache.felix.gogo.runtime + + + + + org.apache.felix + org.apache.felix.dependencymanager.runtime + + + org.apache.felix + org.apache.felix.eventadmin + + + org.apache.felix + org.apache.felix.scr + + + org.apache.felix + org.apache.felix.webconsole + + + org.apache.felix + org.apache.felix.shell + + + org.apache.felix + org.apache.felix.bundlerepository + + + org.apache.felix + org.apache.felix.fileinstall + + + org.apache.felix + org.osgi.service.obr + + + + + + asm + asm-all + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-vfs + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.bcel + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.jaxp-ri + + + com.google.code.gson + gson + + + org.codehaus.groovy + groovy-all + + + commons-fileupload + commons-fileupload + + + commons-io + commons-io + + + de.twentyeleven.skysail + org.json-osgi + + + org.apache.xbean + xbean-finder + + + + org.mybatis + mybatis + + + + com.h2database + h2 + + + + + + cz.zcu.kiv.crce + crce-core + pom + + + + diff --git a/pom.xml b/pom.xml index cee06dbe..0729e35a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,35 +1,35 @@ - - - - 4.0.0 - - cz.zcu.kiv.crce - crce-reactor - 2.1.0-SNAPSHOT - pom - - CRCE - Reactor - - - pom - build - core - modules - - - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + cz.zcu.kiv.crce + crce-reactor + 2.1.0-SNAPSHOT + pom + + CRCE - Reactor + + + pom + build + core + modules + + + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/pom/pom.xml b/pom/pom.xml index 38a92be9..c468d3b3 100644 --- a/pom/pom.xml +++ b/pom/pom.xml @@ -1,103 +1,103 @@ - - - - 4.0.0 - - cz.zcu.kiv.crce - crce-parent - 2.1.1-SNAPSHOT - pom - - CRCE - Parent - - Component Repository supporting Compatibility Evaluation - - https://www.assembla.com/spaces/crce - - - ZČU KIV - http://www.kiv.zcu.cz - - - - - kalwi - Jiří Kučera - - - - - - 3.0.4 - - - - UTF-8 - - - - https://github.com/ReliSA/crce/tree/master/pom - https://github.com/ReliSA/crce.git - scm:git:git@github.com:ReliSA/crce.git - HEAD - - - - - - - org.apache.maven.wagon - wagon-webdav - 1.0-beta-2 - - - - - - maven-release-plugin - 2.5.1 - - - - - - - relisa-release - ReliSA Internal Releases - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/repositories/releases - - - relisa-snapshots - ReliSA Internal Snapshots - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/repositories/snapshots - - - - - - - central - http://uk.maven.org/maven2 - - - - relisa-global - ReliSA Global Proxy repository - http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public - - - - - maven.kalwi.eu.snapshots - kalwi.eu snapshots repository - http://maven.kalwi.eu/repo/snapshots - - - - maven.kalwi.eu.releases - kalwi.eu releases repository - http://maven.kalwi.eu/repo/releases - - - - + + + + 4.0.0 + + cz.zcu.kiv.crce + crce-parent + 2.1.1-SNAPSHOT + pom + + CRCE - Parent + + Component Repository supporting Compatibility Evaluation + + https://www.assembla.com/spaces/crce + + + ZČU KIV + http://www.kiv.zcu.cz + + + + + kalwi + Jiří Kučera + + + + + + 3.0.4 + + + + UTF-8 + + + + https://github.com/ReliSA/crce/tree/master/pom + https://github.com/ReliSA/crce.git + scm:git:git@github.com:ReliSA/crce.git + HEAD + + + + + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-2 + + + + + + maven-release-plugin + 2.5.1 + + + + + + + relisa-release + ReliSA Internal Releases + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/repositories/releases + + + relisa-snapshots + ReliSA Internal Snapshots + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/repositories/snapshots + + + + + + + central + http://uk.maven.org/maven2 + + + + relisa-global + ReliSA Global Proxy repository + http://relisa-dev.kiv.zcu.cz:8081/nexus/content/groups/public + + + + + maven.kalwi.eu.snapshots + kalwi.eu snapshots repository + http://maven.kalwi.eu/repo/snapshots + + + + maven.kalwi.eu.releases + kalwi.eu releases repository + http://maven.kalwi.eu/repo/releases + + + + diff --git a/third-party/httpclient/osgi.bnd b/third-party/httpclient/osgi.bnd index 4c08335c..0d4db057 100644 --- a/third-party/httpclient/osgi.bnd +++ b/third-party/httpclient/osgi.bnd @@ -1,9 +1,9 @@ -#-------------------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the wrapped library -#-------------------------------------------------------------------------- - -# -# this unpacks the contents of the wrapped jar artifact inside the bundle -# to also inline dependencies of this artifact add Embed-Transitive: true -# -Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true +#-------------------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the wrapped library +#-------------------------------------------------------------------------- + +# +# this unpacks the contents of the wrapped jar artifact inside the bundle +# to also inline dependencies of this artifact add Embed-Transitive: true +# +Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true diff --git a/third-party/httpcore/osgi.bnd b/third-party/httpcore/osgi.bnd index 4c08335c..0d4db057 100644 --- a/third-party/httpcore/osgi.bnd +++ b/third-party/httpcore/osgi.bnd @@ -1,9 +1,9 @@ -#-------------------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the wrapped library -#-------------------------------------------------------------------------- - -# -# this unpacks the contents of the wrapped jar artifact inside the bundle -# to also inline dependencies of this artifact add Embed-Transitive: true -# -Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true +#-------------------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the wrapped library +#-------------------------------------------------------------------------- + +# +# this unpacks the contents of the wrapped jar artifact inside the bundle +# to also inline dependencies of this artifact add Embed-Transitive: true +# +Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true diff --git a/third-party/plexus-component-annotations/osgi.bnd b/third-party/plexus-component-annotations/osgi.bnd index 4c08335c..0d4db057 100644 --- a/third-party/plexus-component-annotations/osgi.bnd +++ b/third-party/plexus-component-annotations/osgi.bnd @@ -1,9 +1,9 @@ -#-------------------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the wrapped library -#-------------------------------------------------------------------------- - -# -# this unpacks the contents of the wrapped jar artifact inside the bundle -# to also inline dependencies of this artifact add Embed-Transitive: true -# -Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true +#-------------------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the wrapped library +#-------------------------------------------------------------------------- + +# +# this unpacks the contents of the wrapped jar artifact inside the bundle +# to also inline dependencies of this artifact add Embed-Transitive: true +# +Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true diff --git a/third-party/plexus-interpolation/osgi.bnd b/third-party/plexus-interpolation/osgi.bnd index 4c08335c..0d4db057 100644 --- a/third-party/plexus-interpolation/osgi.bnd +++ b/third-party/plexus-interpolation/osgi.bnd @@ -1,9 +1,9 @@ -#-------------------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the wrapped library -#-------------------------------------------------------------------------- - -# -# this unpacks the contents of the wrapped jar artifact inside the bundle -# to also inline dependencies of this artifact add Embed-Transitive: true -# -Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true +#-------------------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the wrapped library +#-------------------------------------------------------------------------- + +# +# this unpacks the contents of the wrapped jar artifact inside the bundle +# to also inline dependencies of this artifact add Embed-Transitive: true +# +Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true diff --git a/third-party/plexus-utils/osgi.bnd b/third-party/plexus-utils/osgi.bnd index 4c08335c..0d4db057 100644 --- a/third-party/plexus-utils/osgi.bnd +++ b/third-party/plexus-utils/osgi.bnd @@ -1,9 +1,9 @@ -#-------------------------------------------------------------------------- -# Use this file to add customized Bnd instructions for the wrapped library -#-------------------------------------------------------------------------- - -# -# this unpacks the contents of the wrapped jar artifact inside the bundle -# to also inline dependencies of this artifact add Embed-Transitive: true -# -Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true +#-------------------------------------------------------------------------- +# Use this file to add customized Bnd instructions for the wrapped library +#-------------------------------------------------------------------------- + +# +# this unpacks the contents of the wrapped jar artifact inside the bundle +# to also inline dependencies of this artifact add Embed-Transitive: true +# +Embed-Dependency: *;scope=compile|runtime;type=!pom;inline=true