Move SLC Support
authorMathieu Baudier <mbaudier@argeo.org>
Fri, 13 Feb 2015 12:51:37 +0000 (12:51 +0000)
committerMathieu Baudier <mbaudier@argeo.org>
Fri, 13 Feb 2015 12:51:37 +0000 (12:51 +0000)
git-svn-id: https://svn.argeo.org/slc/trunk@7843 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc

264 files changed:
org.argeo.slc.repo/bnd.bnd
org.argeo.slc.repo/pom.xml
org.argeo.slc.repo/src/org/argeo/slc/repo/ArgeoOsgiDistribution.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactDistribution.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/FreeLicense.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/JarFileIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/JavaRepoManager.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/MavenProxyService.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionFactory.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexerVisitor.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiBundlesProvider.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiFactory.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/PdeSourcesIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RepoConstants.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RepoService.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RepoSync.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RepoUtils.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RpmIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/RpmRepoManager.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/SlcRepoManager.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/AbstractJcrRepoManager.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/JavaRepoManagerImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/RepoServiceImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/RpmRepoManagerImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/SlcRepoManagerImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/core/WorkspaceIndexer.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/apache-2.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/bsd-3-clause.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/cddl-1.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/epl-1.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-2.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-3.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-2.1.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-3.0.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/license/mit.txt [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ConvertPoms_01_03.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/GenerateBinaries.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ImportMavenDependencies.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/IndexDistribution.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenConventionsUtils.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/maven/Migration_01_03.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveWrapper.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/BndWrapper.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ImportBundlesZip.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.6.profile [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.7.profile [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/MavenWrapper.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/NormalizeGroup.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ObrWrapper.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiProfile.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ProcessDistribution.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/SourcesProvider.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/UriWrapper.java [new file with mode: 0644]
org.argeo.slc.repo/src/org/argeo/slc/repo/repo.cnd [new file with mode: 0644]
org.argeo.slc.support/bnd.bnd
org.argeo.slc.support/ext/test/log4j.properties [new file with mode: 0644]
org.argeo.slc.support/ext/test/org/argeo/slc/diff/LineTokenizerTest.java [new file with mode: 0644]
org.argeo.slc.support/pom.xml
org.argeo.slc.support/src/org/argeo/slc/diff/DataInterpreter.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/Diff.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssue.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssueKey.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffKey.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissing.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissingXml.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffNotMatched.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffPosition.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/DiffResult.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/KeyColumnsDiff.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/LineTokenizer.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/RelatedFile.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/TableDiffPosition.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/Tolerance.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/ToleranceDiff.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/XPathDiffPosition.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/diff/package.html [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/AbstractJschTask.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/CallbackHandlerUserInfo.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/JschContextSession.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/JschExecutor.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/JschMultiTasks.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/RemoteExec.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/ScpFrom.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/ScpTo.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/SimpleUserInfo.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/SshFilesDeployment.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/SshShell.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/SshTarget.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/jsch/SwingUserInfo.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRpmDistribution.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/DeployLxcContainer.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatDeploymentData.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatHostManager.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/RpmDistribution.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/ScriptCall.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/SimpleLinuxHost.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-guest.sh [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-host.sh [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/redhat.xml [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/svn/SvnKitDriver.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxMachine.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxManager.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxNat.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxPortMapping.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/log4j/SlcExecutionAppender.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/mail/SendMail.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServer.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeployment.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerManager.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerTargetData.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/SimpleHttpdApplication.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebApplication.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebServer.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/DbModel.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/JdbcAware.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResource.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceFactory.java [new file with mode: 0644]
org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceSet.java [new file with mode: 0644]
pom.xml
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArgeoOsgiDistribution.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactDistribution.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/FreeLicense.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JarFileIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JavaRepoManager.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/MavenProxyService.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionFactory.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexerVisitor.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiBundlesProvider.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiFactory.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/PdeSourcesIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoConstants.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoService.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoSync.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoUtils.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmRepoManager.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/SlcRepoManager.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/AbstractJcrRepoManager.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/JavaRepoManagerImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RepoServiceImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RpmRepoManagerImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/SlcRepoManagerImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/WorkspaceIndexer.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ConvertPoms_01_03.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/GenerateBinaries.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ImportMavenDependencies.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/IndexDistribution.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenConventionsUtils.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/Migration_01_03.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveWrapper.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/BndWrapper.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ImportBundlesZip.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/MavenWrapper.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/NormalizeGroup.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ObrWrapper.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiProfile.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ProcessDistribution.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/SourcesProvider.java [deleted file]
runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/UriWrapper.java [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/apache-2.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/bsd-3-clause.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/cddl-1.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/epl-1.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-2.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-3.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-2.1.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-3.0.txt [deleted file]
runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/mit.txt [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DataInterpreter.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Diff.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssue.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssueKey.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffKey.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissing.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissingXml.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffNotMatched.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffPosition.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffResult.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/KeyColumnsDiff.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/LineTokenizer.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/RelatedFile.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/TableDiffPosition.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Tolerance.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/ToleranceDiff.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/XPathDiffPosition.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/package.html [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/AbstractJschTask.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/CallbackHandlerUserInfo.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschContextSession.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschExecutor.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschMultiTasks.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/RemoteExec.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpFrom.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpTo.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SimpleUserInfo.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshFilesDeployment.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshShell.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshTarget.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SwingUserInfo.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRpmDistribution.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DeployLxcContainer.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatDeploymentData.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatHostManager.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RpmDistribution.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/ScriptCall.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/SimpleLinuxHost.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/svn/SvnKitDriver.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxMachine.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxManager.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxNat.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxPortMapping.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/log4j/SlcExecutionAppender.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/mail/SendMail.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServer.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeployment.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerManager.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerTargetData.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/SimpleHttpdApplication.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebApplication.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebServer.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/DbModel.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/JdbcAware.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResource.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceFactory.java [deleted file]
runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceSet.java [deleted file]
runtime/org.argeo.slc.support.simple/src/test/java/org/argeo/slc/diff/LineTokenizerTest.java [deleted file]

index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..8bc8df01251f09705d7ee76c3828ef77e2ce2062 100644 (file)
@@ -0,0 +1,6 @@
+Import-Package: org.w3c.dom.*,\
+org.xml.sax.*,\
+javax.xml.transform.*,\
+javax.xml.parsers.*,\
+javax.jcr.nodetype,\
+*
index 737cd0b00eee4ae634ec9a7895c96c629660abd7..8ba17d7ede61d97be18e4bd3ea00be7e11a9256a 100644 (file)
@@ -1,4 +1,5 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
                <groupId>org.argeo.slc</groupId>
@@ -8,4 +9,24 @@
        </parent>
        <artifactId>org.argeo.slc.repo</artifactId>
        <name>SLC Repo</name>
+       <dependencies>
+               <!-- SLC Runtime -->
+               <dependency>
+                       <groupId>org.argeo.slc</groupId>
+                       <artifactId>org.argeo.slc.support</artifactId>
+                       <version>2.1.1-SNAPSHOT</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.argeo.slc</groupId>
+                       <artifactId>org.argeo.slc.core</artifactId>
+                       <version>2.1.1-SNAPSHOT</version>
+               </dependency>
+
+               <!-- Commons -->
+               <dependency>
+                       <groupId>org.argeo.commons</groupId>
+                       <artifactId>org.argeo.server.jcr</artifactId>
+                       <version>${version.argeo-commons}</version>
+               </dependency>
+       </dependencies>
 </project>
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/ArgeoOsgiDistribution.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/ArgeoOsgiDistribution.java
new file mode 100644 (file)
index 0000000..493486e
--- /dev/null
@@ -0,0 +1,11 @@
+package org.argeo.slc.repo;
+
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.build.ModularDistribution;
+
+/** Aether compatible OSGi distribution */
+public interface ArgeoOsgiDistribution extends Distribution,
+               CategorizedNameVersion, ModularDistribution {
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactDistribution.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactDistribution.java
new file mode 100644 (file)
index 0000000..d76da46
--- /dev/null
@@ -0,0 +1,63 @@
+package org.argeo.slc.repo;
+
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.build.Distribution;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/** A {@link Distribution} based on an Aether {@link Artifact} */
+public class ArtifactDistribution implements Distribution,
+               CategorizedNameVersion {
+       private final Artifact artifact;
+
+       public ArtifactDistribution(Artifact artifact) {
+               this.artifact = artifact;
+       }
+
+       public ArtifactDistribution(String coords) {
+               this(new DefaultArtifact(coords));
+       }
+
+       /** Aether coordinates of the underlying artifact. */
+       public String getDistributionId() {
+               return artifact.toString();
+       }
+
+       public Artifact getArtifact() {
+               return artifact;
+       }
+
+       public String getName() {
+               return getArtifact().getArtifactId();
+       }
+
+       public String getVersion() {
+               return getArtifact().getVersion();
+       }
+
+       public String getCategory() {
+               return getArtifact().getGroupId();
+       }
+
+       @Override
+       public int hashCode() {
+               return artifact.hashCode();
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if (obj instanceof CategorizedNameVersion) {
+                       CategorizedNameVersion cnv = (CategorizedNameVersion) obj;
+                       return getCategory().equals(cnv.getCategory())
+                                       && getName().equals(cnv.getName())
+                                       && getVersion().equals(cnv.getVersion());
+               } else
+                       return artifact.equals(obj);
+       }
+
+       @Override
+       public String toString() {
+               return getDistributionId();
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/ArtifactIndexer.java
new file mode 100644 (file)
index 0000000..27c6806
--- /dev/null
@@ -0,0 +1,271 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherUtils;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.osgi.framework.Constants;
+import org.sonatype.aether.artifact.Artifact;
+
+/**
+ * Add {@link Artifact} properties to a {@link Node}. Does nothing if the node
+ * name doesn't start with the artifact id (in order to skip Maven metadata XML
+ * files and other non artifact files).
+ */
+public class ArtifactIndexer implements NodeIndexer, SlcNames {
+       private Log log = LogFactory.getLog(ArtifactIndexer.class);
+       private Boolean force = false;
+
+       public Boolean support(String path) {
+               String relativePath = getRelativePath(path);
+               if (relativePath == null)
+                       return false;
+               Artifact artifact = null;
+               try {
+                       artifact = AetherUtils.convertPathToArtifact(relativePath, null);
+               } catch (Exception e) {
+                       if (log.isTraceEnabled())
+                               log.trace("Malformed path " + path + ", skipping silently", e);
+               }
+               return artifact != null;
+       }
+
+       public void index(Node fileNode) {
+               Artifact artifact = null;
+               try {
+                       if (!support(fileNode.getPath()))
+                               return;
+
+                       // Already indexed
+                       if (!force && fileNode.isNodeType(SlcTypes.SLC_ARTIFACT))
+                               return;
+
+                       if (!fileNode.isNodeType(NodeType.NT_FILE))
+                               return;
+
+                       String relativePath = getRelativePath(fileNode.getPath());
+                       if (relativePath == null)
+                               return;
+                       artifact = AetherUtils.convertPathToArtifact(relativePath, null);
+                       // support() guarantees that artifact won't be null, no NPE check
+                       fileNode.addMixin(SlcTypes.SLC_ARTIFACT);
+                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_ID,
+                                       artifact.getArtifactId());
+                       fileNode.setProperty(SlcNames.SLC_GROUP_ID, artifact.getGroupId());
+                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_VERSION,
+                                       artifact.getVersion());
+                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_EXTENSION,
+                                       artifact.getExtension());
+                       // can be null but ok for JCR API
+                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_CLASSIFIER,
+                                       artifact.getClassifier());
+                       JcrUtils.updateLastModified(fileNode);
+
+                       // make sure there are checksums
+                       String shaNodeName = fileNode.getName() + ".sha1";
+                       if (!fileNode.getParent().hasNode(shaNodeName)) {
+                               String sha = JcrUtils.checksumFile(fileNode, "SHA-1");
+                               JcrUtils.copyBytesAsFile(fileNode.getParent(), shaNodeName,
+                                               sha.getBytes());
+                       }
+                       String md5NodeName = fileNode.getName() + ".md5";
+                       if (!fileNode.getParent().hasNode(md5NodeName)) {
+                               String md5 = JcrUtils.checksumFile(fileNode, "MD5");
+                               JcrUtils.copyBytesAsFile(fileNode.getParent(), md5NodeName,
+                                               md5.getBytes());
+                       }
+
+                       // Create a default pom if none already exist
+                       String fileNodeName = fileNode.getName();
+                       String pomName = null;
+                       if (fileNodeName.endsWith(".jar"))
+                               pomName = fileNodeName.substring(0, fileNodeName.length()
+                                               - ".jar".length())
+                                               + ".pom";
+
+                       if (pomName != null && !fileNode.getParent().hasNode(pomName)) {
+                               String pom = generatePomForBundle(fileNode);
+                               Node pomNode = JcrUtils.copyBytesAsFile(fileNode.getParent(),
+                                               pomName, pom.getBytes());
+                               // corresponding check sums
+                               String sha = JcrUtils.checksumFile(pomNode, "SHA-1");
+                               JcrUtils.copyBytesAsFile(fileNode.getParent(), pomName
+                                               + ".sha1", sha.getBytes());
+                               String md5 = JcrUtils.checksumFile(fileNode, "MD5");
+                               JcrUtils.copyBytesAsFile(fileNode.getParent(),
+                                               pomName + ".md5", md5.getBytes());
+                       }
+
+                       // set higher levels
+                       Node artifactVersionBase = fileNode.getParent();
+                       if (!artifactVersionBase
+                                       .isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
+                               artifactVersionBase
+                                               .addMixin(SlcTypes.SLC_ARTIFACT_VERSION_BASE);
+                               artifactVersionBase.setProperty(SlcNames.SLC_ARTIFACT_VERSION,
+                                               artifact.getBaseVersion());
+                               artifactVersionBase.setProperty(SlcNames.SLC_ARTIFACT_ID,
+                                               artifact.getArtifactId());
+                               artifactVersionBase.setProperty(SlcNames.SLC_GROUP_ID,
+                                               artifact.getGroupId());
+                       }
+                       JcrUtils.updateLastModified(artifactVersionBase);
+
+                       // pom
+                       if (artifact.getExtension().equals("pom")) {
+                               // TODO read to make it a distribution
+                       }
+
+                       Node artifactBase = artifactVersionBase.getParent();
+                       if (!artifactBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
+                               artifactBase.addMixin(SlcTypes.SLC_ARTIFACT_BASE);
+                               artifactBase.setProperty(SlcNames.SLC_ARTIFACT_ID,
+                                               artifact.getArtifactId());
+                               artifactBase.setProperty(SlcNames.SLC_GROUP_ID,
+                                               artifact.getGroupId());
+                       }
+                       JcrUtils.updateLastModified(artifactBase);
+
+                       Node groupBase = artifactBase.getParent();
+                       if (!groupBase.isNodeType(SlcTypes.SLC_GROUP_BASE)) {
+                               // if (groupBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
+                               // log.warn("Group base " + groupBase.getPath()
+                               // + " is also artifact base");
+                               // }
+                               groupBase.addMixin(SlcTypes.SLC_GROUP_BASE);
+                               groupBase.setProperty(SlcNames.SLC_GROUP_BASE_ID,
+                                               artifact.getGroupId());
+                       }
+                       JcrUtils.updateLastModifiedAndParents(groupBase,
+                                       RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH);
+
+                       if (log.isTraceEnabled())
+                               log.trace("Indexed artifact " + artifact + " on " + fileNode);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot index artifact " + artifact
+                                       + " metadata on node " + fileNode, e);
+               }
+       }
+
+       private String getRelativePath(String nodePath) {
+               String basePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+               if (!nodePath.startsWith(basePath))
+                       return null;
+               String relativePath = nodePath.substring(basePath.length());
+               return relativePath;
+       }
+
+       public void setForce(Boolean force) {
+               this.force = force;
+       }
+
+       private String generatePomForBundle(Node n) throws RepositoryException {
+               StringBuffer p = new StringBuffer();
+               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
+               p.append("<modelVersion>4.0.0</modelVersion>");
+
+               // Categorized name version
+               p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
+                               .append("</groupId>\n");
+               p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
+                               .append("</artifactId>\n");
+               p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
+                               .append("</version>\n");
+               // TODO make it more generic
+               p.append("<packaging>jar</packaging>\n");
+               if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
+                       p.append("<name>")
+                                       .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
+                                       .append("</name>\n");
+               if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
+                       p.append("<description>")
+                                       .append(JcrUtils
+                                                       .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
+                                       .append("</description>\n");
+
+               // Dependencies in case of a distribution
+               if (n.isNodeType(SlcTypes.SLC_MODULAR_DISTRIBUTION)) {
+                       p.append(getDependenciesSnippet(n.getNode(SlcNames.SLC_MODULES)
+                                       .getNodes()));
+                       p.append(getDependencyManagementSnippet(n.getNode(
+                                       SlcNames.SLC_MODULES).getNodes()));
+               }
+               p.append("</project>\n");
+               return p.toString();
+       }
+
+       private String getDependenciesSnippet(NodeIterator nit)
+                       throws RepositoryException {
+               StringBuilder b = new StringBuilder();
+               b.append("<dependencies>\n");
+               while (nit.hasNext()) {
+                       Node currModule = nit.nextNode();
+                       if (currModule.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
+                               b.append(getDependencySnippet(
+                                               currModule.getProperty(SlcNames.SLC_CATEGORY)
+                                                               .getString(),
+                                               currModule.getProperty(SlcNames.SLC_NAME).getString(),
+                                               null));
+                       }
+               }
+               b.append("</dependencies>\n");
+               return b.toString();
+       }
+
+       private String getDependencyManagementSnippet(NodeIterator nit)
+                       throws RepositoryException {
+               StringBuilder b = new StringBuilder();
+               b.append("<dependencyManagement>\n");
+               b.append("<dependencies>\n");
+               while (nit.hasNext()) {
+                       Node currModule = nit.nextNode();
+                       if (currModule.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
+                               b.append(getDependencySnippet(
+                                               currModule.getProperty(SlcNames.SLC_CATEGORY)
+                                                               .getString(),
+                                               currModule.getProperty(SlcNames.SLC_NAME).getString(),
+                                               currModule.getProperty(SlcNames.SLC_VERSION)
+                                                               .getString()));
+                       }
+               }
+               b.append("</dependencies>\n");
+               b.append("</dependencyManagement>\n");
+               return b.toString();
+       }
+
+       private String getDependencySnippet(String category, String name,
+                       String version) {
+               StringBuilder b = new StringBuilder();
+               b.append("<dependency>\n");
+               b.append("\t<groupId>").append(category).append("</groupId>\n");
+               b.append("\t<artifactId>").append(name).append("</artifactId>\n");
+               if (version != null)
+                       b.append("\t<version>").append(version).append("</version>\n");
+               b.append("</dependency>\n");
+               return b.toString();
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/FreeLicense.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/FreeLicense.java
new file mode 100644 (file)
index 0000000..1b83666
--- /dev/null
@@ -0,0 +1,166 @@
+package org.argeo.slc.repo;
+
+import java.io.InputStream;
+import java.net.URL;
+
+import org.apache.commons.io.IOUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.build.License;
+
+/** A free software license */
+public abstract class FreeLicense implements License {
+       final static String RESOURCES = "/org/argeo/slc/repo/license/";
+
+       /** GNU */
+       public final static FreeLicense GPL_v3 = new FreeLicense(
+                       "GNU General Public License, version 3.0",
+                       "http://www.gnu.org/licenses/gpl-3.0.txt",
+                       "http://www.gnu.org/licenses/", RESOURCES + "gpl-3.0.txt") {
+       };
+
+       public final static FreeLicense GPL_v2 = new FreeLicense(
+                       "GNU General Public License, version 2.0",
+                       "http://www.gnu.org/licenses/gpl-2.0.txt",
+                       "http://www.gnu.org/licenses/", RESOURCES + "gpl-2.0.txt") {
+       };
+       public final static FreeLicense GPL = GPL_v3;
+
+       public final static FreeLicense LGPL_v3 = new FreeLicense(
+                       "GNU Lesser General Public License, version 3.0",
+                       "http://www.gnu.org/licenses/lgpl-3.0.txt",
+                       "http://www.gnu.org/licenses/", RESOURCES + "lgpl-3.0.txt") {
+       };
+
+       public final static FreeLicense LGPL_v2 = new FreeLicense(
+                       "GNU Lesser General Public License, version 2.1",
+                       "http://www.gnu.org/licenses/lgpl-2.1.txt",
+                       "http://www.gnu.org/licenses/", RESOURCES + "lgpl-2.1.txt") {
+       };
+       public final static FreeLicense LGPL = LGPL_v3;
+
+       /** Apache */
+       public final static FreeLicense APACHE_v2 = new FreeLicense(
+                       "Apache License, Version 2.0",
+                       "http://www.apache.org/licenses/LICENSE-2.0.txt",
+                       "http://www.apache.org/licenses/", RESOURCES + "apache-2.0.txt") {
+       };
+       public final static FreeLicense APACHE = APACHE_v2;
+
+       /** Eclipse */
+       public final static FreeLicense EPL_v1 = new FreeLicense(
+                       "Eclipse Public License, Version 1.0",
+                       "http://www.eclipse.org/legal/epl-v10.html",
+                       "http://www.eclipse.org/legal/eplfaq.php", RESOURCES
+                                       + "epl-1.0.txt") {
+       };
+       public final static FreeLicense EPL = EPL_v1;
+
+       /** Miscellaneous */
+       public final static FreeLicense MIT = new FreeLicense("The MIT License",
+                       "http://opensource.org/licenses/MIT", null, RESOURCES + "mit.txt") {
+       };
+
+       public final static FreeLicense BSD_NEW = new FreeLicense(
+                       "The BSD 3-Clause License",
+                       "http://opensource.org/licenses/BSD-3-Clause", null, RESOURCES
+                                       + "bsd-3-clause.txt") {
+       };
+
+       public final static FreeLicense BSD = BSD_NEW;
+
+       public final static FreeLicense CDDL_v1 = new FreeLicense(
+                       "Common Development and Distribution License",
+                       "http://opensource.org/licenses/CDDL-1.0", null, RESOURCES
+                                       + "cddl-1.0.txt") {
+       };
+       public final static FreeLicense CDDL = CDDL_v1;
+
+       /** Public domain corner case */
+       public final static License PUBLIC_DOMAIN = new License() {
+
+               public String getUri() {
+                       return "http://creativecommons.org/about/pdm";
+               }
+
+               public String getText() {
+                       return "This work is free of known copyright restrictions.";
+               }
+
+               public String getName() {
+                       return "Public Domain License";
+               }
+
+               public String getLink() {
+                       return "http://wiki.creativecommons.org/PDM_FAQ";
+               }
+       };
+
+       private final String name, uri, link, resource;
+
+       public FreeLicense(String name, String uri) {
+               this(name, uri, null, null);
+       }
+
+       public FreeLicense(String name, String uri, String link) {
+               this(name, uri, link, null);
+       }
+
+       public FreeLicense(String name, String uri, String link, String resource) {
+               if (uri == null)
+                       throw new SlcException("URI cannot be null");
+               this.name = name;
+               this.uri = uri;
+               this.link = link;
+               this.resource = resource;
+               getText();
+       }
+
+       public String getName() {
+               return name;
+       }
+
+       public String getUri() {
+               return uri;
+       }
+
+       public String getLink() {
+               return link;
+       }
+
+       @Override
+       public String getText() {
+               InputStream in = null;
+               URL url = null;
+               try {
+                       if (resource != null)
+                               url = getClass().getClassLoader().getResource(resource);
+                       else
+                               url = new URL(uri);
+                       in = url.openStream();
+                       String text = IOUtils.toString(in);
+                       return text;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot retrieve license " + name + " from "
+                                       + url, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if (!(obj instanceof License))
+                       return false;
+               return ((License) obj).getUri().equals(getUri());
+       }
+
+       @Override
+       public int hashCode() {
+               return getUri().hashCode();
+       }
+
+       @Override
+       public String toString() {
+               return name + " (" + uri + ")";
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/JarFileIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/JarFileIndexer.java
new file mode 100644 (file)
index 0000000..b07cade
--- /dev/null
@@ -0,0 +1,498 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Attributes;
+import java.util.jar.Attributes.Name;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+
+import javax.jcr.Binary;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Version;
+
+/**
+ * Indexes jar file, currently supports standard J2SE and OSGi metadata (both
+ * from MANIFEST)
+ */
+public class JarFileIndexer implements NodeIndexer, SlcNames {
+       private final static Log log = LogFactory.getLog(JarFileIndexer.class);
+       private Boolean force = false;
+
+       public Boolean support(String path) {
+               return FilenameUtils.getExtension(path).equals("jar");
+       }
+
+       public void index(Node fileNode) {
+               Binary fileBinary = null;
+               JarInputStream jarIn = null;
+               ByteArrayOutputStream bo = null;
+               ByteArrayInputStream bi = null;
+               Binary manifestBinary = null;
+               try {
+                       if (!support(fileNode.getPath()))
+                               return;
+
+                       // Already indexed
+                       if (!force && fileNode.isNodeType(SlcTypes.SLC_JAR_FILE))
+                               return;
+
+                       if (!fileNode.isNodeType(NodeType.NT_FILE))
+                               return;
+
+                       Session jcrSession = fileNode.getSession();
+                       Node contentNode = fileNode.getNode(Node.JCR_CONTENT);
+                       fileBinary = contentNode.getProperty(Property.JCR_DATA).getBinary();
+
+                       jarIn = new JarInputStream(fileBinary.getStream());
+                       Manifest manifest = jarIn.getManifest();
+                       if (manifest == null) {
+                               log.error(fileNode + " has no MANIFEST");
+                               return;
+                       }
+
+                       bo = new ByteArrayOutputStream();
+                       manifest.write(bo);
+                       byte[] newManifest = bo.toByteArray();
+                       if (fileNode.hasProperty(SLC_MANIFEST)) {
+                               byte[] storedManifest = JcrUtils.getBinaryAsBytes(fileNode
+                                               .getProperty(SLC_MANIFEST));
+                               if (Arrays.equals(newManifest, storedManifest)) {
+                                       if (log.isTraceEnabled())
+                                               log.trace("Manifest not changed, doing nothing "
+                                                               + fileNode);
+                                       return;
+                               }
+                       }
+
+                       bi = new ByteArrayInputStream(newManifest);
+                       manifestBinary = jcrSession.getValueFactory().createBinary(bi);
+
+                       // standard jar file
+                       fileNode.addMixin(SlcTypes.SLC_JAR_FILE);
+
+                       fileNode.setProperty(SlcNames.SLC_MANIFEST, manifestBinary);
+                       Attributes attrs = manifest.getMainAttributes();
+
+                       getI18nValues(fileBinary, attrs);
+
+                       // standard J2SE MANIFEST attributes
+                       addAttr(Attributes.Name.MANIFEST_VERSION, fileNode, attrs);
+                       addAttr(Attributes.Name.SIGNATURE_VERSION, fileNode, attrs);
+                       addAttr(Attributes.Name.CLASS_PATH, fileNode, attrs);
+                       addAttr(Attributes.Name.MAIN_CLASS, fileNode, attrs);
+                       addAttr(Attributes.Name.EXTENSION_NAME, fileNode, attrs);
+                       addAttr(Attributes.Name.IMPLEMENTATION_VERSION, fileNode, attrs);
+                       addAttr(Attributes.Name.IMPLEMENTATION_VENDOR, fileNode, attrs);
+                       addAttr(Attributes.Name.IMPLEMENTATION_VENDOR_ID, fileNode, attrs);
+                       addAttr(Attributes.Name.SPECIFICATION_TITLE, fileNode, attrs);
+                       addAttr(Attributes.Name.SPECIFICATION_VERSION, fileNode, attrs);
+                       addAttr(Attributes.Name.SPECIFICATION_VENDOR, fileNode, attrs);
+                       addAttr(Attributes.Name.SEALED, fileNode, attrs);
+
+                       // OSGi
+                       if (attrs.containsKey(new Name(Constants.BUNDLE_SYMBOLICNAME))) {
+                               addOsgiMetadata(fileNode, attrs);
+                               if (log.isTraceEnabled())
+                                       log.trace("Indexed OSGi bundle " + fileNode);
+                       } else {
+                               if (log.isTraceEnabled())
+                                       log.trace("Indexed JAR file " + fileNode);
+                       }
+
+                       JcrUtils.updateLastModified(fileNode);
+
+               } catch (Exception e) {
+                       throw new SlcException("Cannot index jar " + fileNode, e);
+               } finally {
+                       IOUtils.closeQuietly(bi);
+                       IOUtils.closeQuietly(bo);
+                       IOUtils.closeQuietly(jarIn);
+                       JcrUtils.closeQuietly(manifestBinary);
+                       JcrUtils.closeQuietly(fileBinary);
+               }
+
+       }
+
+       private void getI18nValues(Binary fileBinary, Attributes attrs)
+                       throws IOException {
+               JarInputStream jarIn = null;
+               try {
+                       jarIn = new JarInputStream(fileBinary.getStream());
+                       String bundleLocalization = null;
+
+                       String blKey = Constants.BUNDLE_LOCALIZATION; // "Bundle-Localization";
+                       Name blkName = new Name(blKey);
+
+                       browse: for (Object obj : attrs.keySet()) {
+                               String value = attrs.getValue((Attributes.Name) obj);
+                               if (value.startsWith("%")) {
+                                       if (attrs.containsKey(blkName)) {
+                                               bundleLocalization = attrs.getValue(blkName);
+                                               break browse;
+                                       }
+                               }
+                       }
+
+                       JarEntry jarEntry = null;
+                       byte[] propBytes = null;
+                       ByteArrayOutputStream baos = null;
+                       browse: if (bundleLocalization != null) {
+                               JarEntry entry = jarIn.getNextJarEntry();
+                               while (entry != null) {
+                                       if (entry.getName().equals(
+                                                       bundleLocalization + ".properties")) {
+                                               jarEntry = entry;
+
+                                               // if(je.getSize() != -1){
+                                               // propBytes = new byte[(int)je.getSize()];
+                                               // int len = (int) je.getSize();
+                                               // int offset = 0;
+                                               // while (offset != len)
+                                               // offset += jarIn.read(propBytes, offset, len -
+                                               // offset);
+                                               // } else {
+                                               baos = new ByteArrayOutputStream();
+                                               while (true) {
+                                                       int qwe = jarIn.read();
+                                                       if (qwe == -1)
+                                                               break;
+                                                       baos.write(qwe);
+                                               }
+                                               propBytes = baos.toByteArray();
+                                               break browse;
+                                       }
+                                       entry = jarIn.getNextJarEntry();
+                               }
+                       }
+
+                       if (jarEntry != null) {
+                               Properties prop = new Properties();
+                               InputStream is = new ByteArrayInputStream(propBytes);
+                               prop.load(is);
+
+                               for (Object obj : attrs.keySet()) {
+                                       String value = attrs.getValue((Attributes.Name) obj);
+                                       if (value.startsWith("%")) {
+                                               String newVal = prop.getProperty(value.substring(1));
+                                               if (newVal != null)
+                                                       attrs.put(obj, newVal);
+                                       }
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException(
+                                       "Error while reading the jar binary content " + fileBinary,
+                                       e);
+               } catch (IOException ioe) {
+                       throw new SlcException("unable to get internationalized values",
+                                       ioe);
+               } finally {
+                       IOUtils.closeQuietly(jarIn);
+               }
+       }
+
+       protected void addOsgiMetadata(Node fileNode, Attributes attrs)
+                       throws RepositoryException {
+
+               // TODO remove this ?
+               // Compulsory for the time being, because bundle artifact extends
+               // artifact
+               if (!fileNode.isNodeType(SlcTypes.SLC_ARTIFACT)) {
+                       ArtifactIndexer indexer = new ArtifactIndexer();
+                       indexer.index(fileNode);
+               }
+
+               fileNode.addMixin(SlcTypes.SLC_BUNDLE_ARTIFACT);
+
+               // symbolic name
+               String symbolicName = attrs.getValue(Constants.BUNDLE_SYMBOLICNAME);
+               // make sure there is no directive
+               symbolicName = symbolicName.split(";")[0];
+               fileNode.setProperty(SlcNames.SLC_SYMBOLIC_NAME, symbolicName);
+
+               // direct mapping
+               addAttr(Constants.BUNDLE_SYMBOLICNAME, fileNode, attrs);
+               addAttr(Constants.BUNDLE_NAME, fileNode, attrs);
+               addAttr(Constants.BUNDLE_DESCRIPTION, fileNode, attrs);
+               addAttr(Constants.BUNDLE_MANIFESTVERSION, fileNode, attrs);
+               addAttr(Constants.BUNDLE_CATEGORY, fileNode, attrs);
+               addAttr(Constants.BUNDLE_ACTIVATIONPOLICY, fileNode, attrs);
+               addAttr(Constants.BUNDLE_COPYRIGHT, fileNode, attrs);
+               addAttr(Constants.BUNDLE_VENDOR, fileNode, attrs);
+               addAttr("Bundle-License", fileNode, attrs);
+               addAttr(Constants.BUNDLE_DOCURL, fileNode, attrs);
+               addAttr(Constants.BUNDLE_CONTACTADDRESS, fileNode, attrs);
+               addAttr(Constants.BUNDLE_ACTIVATOR, fileNode, attrs);
+               addAttr(Constants.BUNDLE_UPDATELOCATION, fileNode, attrs);
+               addAttr(Constants.BUNDLE_LOCALIZATION, fileNode, attrs);
+
+               // required execution environment
+               if (attrs.containsKey(new Name(
+                               Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)))
+                       fileNode.setProperty(SlcNames.SLC_
+                                       + Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, attrs
+                                       .getValue(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)
+                                       .split(","));
+
+               // bundle classpath
+               if (attrs.containsKey(new Name(Constants.BUNDLE_CLASSPATH)))
+                       fileNode.setProperty(SlcNames.SLC_ + Constants.BUNDLE_CLASSPATH,
+                                       attrs.getValue(Constants.BUNDLE_CLASSPATH).split(","));
+
+               // version
+               Version version = new Version(attrs.getValue(Constants.BUNDLE_VERSION));
+               fileNode.setProperty(SlcNames.SLC_BUNDLE_VERSION, version.toString());
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.BUNDLE_VERSION);
+               Node bundleVersionNode = fileNode.addNode(SlcNames.SLC_
+                               + Constants.BUNDLE_VERSION, SlcTypes.SLC_OSGI_VERSION);
+               mapOsgiVersion(version, bundleVersionNode);
+
+               // fragment
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.FRAGMENT_HOST);
+               if (attrs.containsKey(new Name(Constants.FRAGMENT_HOST))) {
+                       String fragmentHost = attrs.getValue(Constants.FRAGMENT_HOST);
+                       String[] tokens = fragmentHost.split(";");
+                       Node node = fileNode.addNode(SlcNames.SLC_
+                                       + Constants.FRAGMENT_HOST, SlcTypes.SLC_FRAGMENT_HOST);
+                       node.setProperty(SlcNames.SLC_SYMBOLIC_NAME, tokens[0]);
+                       for (int i = 1; i < tokens.length; i++) {
+                               if (tokens[i].startsWith(Constants.BUNDLE_VERSION_ATTRIBUTE)) {
+                                       node.setProperty(SlcNames.SLC_BUNDLE_VERSION,
+                                                       attributeValue(tokens[i]));
+                               }
+                       }
+               }
+
+               // imported packages
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.IMPORT_PACKAGE);
+               if (attrs.containsKey(new Name(Constants.IMPORT_PACKAGE))) {
+                       String importPackages = attrs.getValue(Constants.IMPORT_PACKAGE);
+                       List<String> packages = parseCommaSeparated(importPackages);
+                       for (String pkg : packages) {
+                               String[] tokens = pkg.split(";");
+                               Node node = fileNode.addNode(SlcNames.SLC_
+                                               + Constants.IMPORT_PACKAGE,
+                                               SlcTypes.SLC_IMPORTED_PACKAGE);
+                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
+                               for (int i = 1; i < tokens.length; i++) {
+                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
+                                               node.setProperty(SlcNames.SLC_VERSION,
+                                                               attributeValue(tokens[i]));
+                                       } else if (tokens[i]
+                                                       .startsWith(Constants.RESOLUTION_DIRECTIVE)) {
+                                               node.setProperty(
+                                                               SlcNames.SLC_OPTIONAL,
+                                                               directiveValue(tokens[i]).equals(
+                                                                               Constants.RESOLUTION_OPTIONAL));
+                                       }
+                               }
+                       }
+               }
+
+               // dynamic import package
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.DYNAMICIMPORT_PACKAGE);
+               if (attrs.containsKey(new Name(Constants.DYNAMICIMPORT_PACKAGE))) {
+                       String importPackages = attrs
+                                       .getValue(Constants.DYNAMICIMPORT_PACKAGE);
+                       List<String> packages = parseCommaSeparated(importPackages);
+                       for (String pkg : packages) {
+                               String[] tokens = pkg.split(";");
+                               Node node = fileNode.addNode(SlcNames.SLC_
+                                               + Constants.DYNAMICIMPORT_PACKAGE,
+                                               SlcTypes.SLC_DYNAMIC_IMPORTED_PACKAGE);
+                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
+                               for (int i = 1; i < tokens.length; i++) {
+                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
+                                               node.setProperty(SlcNames.SLC_VERSION,
+                                                               attributeValue(tokens[i]));
+                                       }
+                               }
+                       }
+               }
+
+               // exported packages
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.EXPORT_PACKAGE);
+               if (attrs.containsKey(new Name(Constants.EXPORT_PACKAGE))) {
+                       String exportPackages = attrs.getValue(Constants.EXPORT_PACKAGE);
+                       List<String> packages = parseCommaSeparated(exportPackages);
+                       for (String pkg : packages) {
+                               String[] tokens = pkg.split(";");
+                               Node node = fileNode.addNode(SlcNames.SLC_
+                                               + Constants.EXPORT_PACKAGE,
+                                               SlcTypes.SLC_EXPORTED_PACKAGE);
+                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
+                               // TODO: are these cleans really necessary?
+                               cleanSubNodes(node, SlcNames.SLC_USES);
+                               cleanSubNodes(node, SlcNames.SLC_VERSION);
+                               for (int i = 1; i < tokens.length; i++) {
+                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
+                                               String versionStr = attributeValue(tokens[i]);
+                                               Node versionNode = node.addNode(SlcNames.SLC_VERSION,
+                                                               SlcTypes.SLC_OSGI_VERSION);
+                                               mapOsgiVersion(new Version(versionStr), versionNode);
+                                       } else if (tokens[i].startsWith(Constants.USES_DIRECTIVE)) {
+                                               String usedPackages = directiveValue(tokens[i]);
+                                               // log.debug("uses='" + usedPackages + "'");
+                                               for (String usedPackage : usedPackages.split(",")) {
+                                                       // log.debug("usedPackage='" +
+                                                       // usedPackage +
+                                                       // "'");
+                                                       Node usesNode = node.addNode(SlcNames.SLC_USES,
+                                                                       SlcTypes.SLC_JAVA_PACKAGE);
+                                                       usesNode.setProperty(SlcNames.SLC_NAME, usedPackage);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               // required bundle
+               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.REQUIRE_BUNDLE);
+               if (attrs.containsKey(new Name(Constants.REQUIRE_BUNDLE))) {
+                       String requireBundle = attrs.getValue(Constants.REQUIRE_BUNDLE);
+                       List<String> bundles = parseCommaSeparated(requireBundle);
+                       for (String bundle : bundles) {
+                               String[] tokens = bundle.split(";");
+                               Node node = fileNode.addNode(SlcNames.SLC_
+                                               + Constants.REQUIRE_BUNDLE,
+                                               SlcTypes.SLC_REQUIRED_BUNDLE);
+                               node.setProperty(SlcNames.SLC_SYMBOLIC_NAME, tokens[0]);
+                               for (int i = 1; i < tokens.length; i++) {
+                                       if (tokens[i]
+                                                       .startsWith(Constants.BUNDLE_VERSION_ATTRIBUTE)) {
+                                               node.setProperty(SlcNames.SLC_BUNDLE_VERSION,
+                                                               attributeValue(tokens[i]));
+                                       } else if (tokens[i]
+                                                       .startsWith(Constants.RESOLUTION_DIRECTIVE)) {
+                                               node.setProperty(
+                                                               SlcNames.SLC_OPTIONAL,
+                                                               directiveValue(tokens[i]).equals(
+                                                                               Constants.RESOLUTION_OPTIONAL));
+                                       }
+                               }
+                       }
+               }
+
+       }
+
+       private void addAttr(String key, Node node, Attributes attrs)
+                       throws RepositoryException {
+               addAttr(new Name(key), node, attrs);
+       }
+
+       private void addAttr(Name key, Node node, Attributes attrs)
+                       throws RepositoryException {
+               if (attrs.containsKey(key)) {
+                       String value = attrs.getValue(key);
+                       node.setProperty(SlcNames.SLC_ + key, value);
+               }
+       }
+
+       private void cleanSubNodes(Node node, String name)
+                       throws RepositoryException {
+               if (node.hasNode(name)) {
+                       NodeIterator nit = node.getNodes(name);
+                       while (nit.hasNext())
+                               nit.nextNode().remove();
+               }
+       }
+
+       private String attributeValue(String str) {
+               return extractValue(str, "=");
+       }
+
+       private String directiveValue(String str) {
+               return extractValue(str, ":=");
+       }
+
+       private String extractValue(String str, String eq) {
+               String[] tokens = str.split(eq);
+               // String key = tokens[0];
+               String value = tokens[1].trim();
+               // TODO: optimize?
+               if (value.startsWith("\""))
+                       value = value.substring(1);
+               if (value.endsWith("\""))
+                       value = value.substring(0, value.length() - 1);
+               return value;
+       }
+
+       /** Parse package list with nested directive with ',' */
+       private List<String> parseCommaSeparated(String str) {
+               List<String> res = new ArrayList<String>();
+               StringBuffer curr = new StringBuffer("");
+               boolean in = false;
+               for (char c : str.toCharArray()) {
+                       if (c == ',') {
+                               if (!in) {// new package
+                                       res.add(curr.toString());
+                                       curr = new StringBuffer("");
+                               } else {// a ',' within " "
+                                       curr.append(c);
+                               }
+                       } else if (c == '\"') {
+                               in = !in;
+                               curr.append(c);
+                       } else {
+                               curr.append(c);
+                       }
+               }
+               res.add(curr.toString());
+               // log.debug(res);
+               return res;
+       }
+
+       protected void mapOsgiVersion(Version version, Node versionNode)
+                       throws RepositoryException {
+               versionNode.setProperty(SlcNames.SLC_AS_STRING, version.toString());
+               versionNode.setProperty(SlcNames.SLC_MAJOR, version.getMajor());
+               versionNode.setProperty(SlcNames.SLC_MINOR, version.getMinor());
+               versionNode.setProperty(SlcNames.SLC_MICRO, version.getMicro());
+               if (!version.getQualifier().equals(""))
+                       versionNode.setProperty(SlcNames.SLC_QUALIFIER,
+                                       version.getQualifier());
+       }
+
+       public void setForce(Boolean force) {
+               this.force = force;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/JavaRepoManager.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/JavaRepoManager.java
new file mode 100644 (file)
index 0000000..4d7c3ef
--- /dev/null
@@ -0,0 +1,7 @@
+package org.argeo.slc.repo;
+
+/** Java-specific operations */
+public interface JavaRepoManager {
+       public void createWorkspace(String workspaceName);
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/MavenProxyService.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/MavenProxyService.java
new file mode 100644 (file)
index 0000000..8df4a53
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import org.argeo.jcr.proxy.ResourceProxy;
+
+/** Marker interface (useful for OSGi servcies references), maybe extended later */
+public interface MavenProxyService extends ResourceProxy {
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionFactory.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionFactory.java
new file mode 100644 (file)
index 0000000..79d3b51
--- /dev/null
@@ -0,0 +1,538 @@
+package org.argeo.slc.repo;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.osgi.framework.Constants;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Creates a jar bundle from an ArgeoOsgiDistribution. This jar is then
+ * persisted and indexed in a java repository using the OSGI Factory.
+ * 
+ * It does the following <list><li>Creates a Manifest</li><li>Creates files
+ * indexes (csv, feature.xml ...)</li><li>Populate the corresponding jar</li><li>
+ * Save it in the repository</li><li>Index the node and creates corresponding
+ * sha1 and md5 files</li> </list>
+ * 
+ */
+public class ModularDistributionFactory implements Runnable {
+
+       private OsgiFactory osgiFactory;
+       private Session javaSession;
+       private ArgeoOsgiDistribution osgiDistribution;
+       private String modularDistributionSeparator = ",";
+       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+       private String artifactType = "jar";
+
+       // Constants
+       private final static String CSV_FILE_NAME = "modularDistribution.csv";
+
+       // private final static String FEATURE_FILE_NAME = "feature.xml";
+       // private static int BUFFER_SIZE = 10240;
+
+       /** Convenience constructor with minimal configuration */
+       public ModularDistributionFactory(OsgiFactory osgiFactory,
+                       ArgeoOsgiDistribution osgiDistribution) {
+               this.osgiFactory = osgiFactory;
+               this.osgiDistribution = osgiDistribution;
+       }
+
+       @Override
+       public void run() {
+               byte[] distFile = null;
+               try {
+                       javaSession = osgiFactory.openJavaSession();
+
+                       if (artifactType == "jar")
+                               distFile = generateJarFile();
+                       else if (artifactType == "pom")
+                               distFile = generatePomFile();
+                       else
+                               throw new SlcException(
+                                               "Unimplemented distribution artifact type: "
+                                                               + artifactType + " for "
+                                                               + osgiDistribution.toString());
+
+                       // Save in java repository
+                       Artifact osgiArtifact = new DefaultArtifact(
+                                       osgiDistribution.getCategory(), osgiDistribution.getName(),
+                                       artifactType, osgiDistribution.getVersion());
+
+                       Node distNode = RepoUtils.copyBytesAsArtifact(
+                                       javaSession.getNode(artifactBasePath), osgiArtifact,
+                                       distFile);
+
+                       // index
+                       osgiFactory.indexNode(distNode);
+
+                       // We use a specific session. Save before closing
+                       javaSession.save();
+               } catch (RepositoryException e) {
+                       throw new SlcException(
+                                       "JCR error while persisting modular distribution in JCR "
+                                                       + osgiDistribution.toString(), e);
+               } finally {
+                       JcrUtils.logoutQuietly(javaSession);
+               }
+       }
+
+       private byte[] generateJarFile() {
+               ByteArrayOutputStream byteOut = null;
+               JarOutputStream jarOut = null;
+               try {
+                       byteOut = new ByteArrayOutputStream();
+                       jarOut = new JarOutputStream(byteOut, createManifest());
+                       // Create various indexes
+                       addToJar(createCsvDescriptor(), CSV_FILE_NAME, jarOut);
+                       jarOut.close();
+                       return byteOut.toByteArray();
+               } catch (IOException e) {
+                       throw new SlcException(
+                                       "IO error while generating modular distribution "
+                                                       + osgiDistribution.toString(), e);
+               } finally {
+                       IOUtils.closeQuietly(byteOut);
+                       IOUtils.closeQuietly(jarOut);
+               }
+       }
+
+       // private void indexDistribution(Node distNode) throws RepositoryException
+       // {
+       // distNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
+       // distNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
+       // distNode.setProperty(SlcNames.SLC_CATEGORY,
+       // osgiDistribution.getCategory());
+       // distNode.setProperty(SlcNames.SLC_NAME, osgiDistribution.getName());
+       // distNode.setProperty(SlcNames.SLC_VERSION,
+       // osgiDistribution.getVersion());
+       //
+       // if (distNode.hasNode(SlcNames.SLC_MODULES))
+       // distNode.getNode(SlcNames.SLC_MODULES).remove();
+       // Node modules = distNode.addNode(SlcNames.SLC_MODULES,
+       // NodeType.NT_UNSTRUCTURED);
+       //
+       // for (Iterator<? extends NameVersion> it = osgiDistribution
+       // .nameVersions(); it.hasNext();)
+       // addModule(modules, it.next());
+       // }
+
+       private Manifest createManifest() {
+               Manifest manifest = new Manifest();
+
+               // TODO make this configurable
+               manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
+                               "1.0");
+               addManifestAttribute(manifest,
+                               Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "JavaSE-1.6");
+               addManifestAttribute(manifest, Constants.BUNDLE_VENDOR, "Argeo");
+               addManifestAttribute(manifest, Constants.BUNDLE_MANIFESTVERSION, "2");
+               addManifestAttribute(manifest, "Bundle-License",
+                               "http://www.apache.org/licenses/LICENSE-2.0.txt");
+
+               // TODO define a user friendly name
+               addManifestAttribute(manifest, Constants.BUNDLE_NAME,
+                               osgiDistribution.getName());
+
+               // Categorized name version
+               addManifestAttribute(manifest, RepoConstants.SLC_GROUP_ID,
+                               osgiDistribution.getCategory());
+               addManifestAttribute(manifest, Constants.BUNDLE_SYMBOLICNAME,
+                               osgiDistribution.getName());
+               addManifestAttribute(manifest, Constants.BUNDLE_VERSION,
+                               osgiDistribution.getVersion());
+
+               return manifest;
+       }
+
+       private void addManifestAttribute(Manifest manifest, String name,
+                       String value) {
+               manifest.getMainAttributes().put(new Attributes.Name(name), value);
+       }
+
+       private byte[] createCsvDescriptor() {
+               Writer writer = null;
+               try {
+                       // FIXME remove use of tmp file.
+                       File tmpFile = File.createTempFile("modularDistribution", "csv");
+                       tmpFile.deleteOnExit();
+                       writer = new FileWriter(tmpFile);
+                       // Populate the file
+                       for (Iterator<? extends NameVersion> it = osgiDistribution
+                                       .nameVersions(); it.hasNext();)
+                               writer.write(getCsvLine(it.next()));
+                       writer.flush();
+                       return FileUtils.readFileToByteArray(tmpFile);
+               } catch (Exception e) {
+                       throw new SlcException(
+                                       "unable to create csv distribution file for "
+                                                       + osgiDistribution.toString(), e);
+               } finally {
+                       IOUtils.closeQuietly(writer);
+               }
+       }
+
+       @SuppressWarnings("unused")
+       private byte[] createFeatureDescriptor() {
+               // Directly retrieved from Argeo maven plugin
+               // Does not work due to the lack of org.codehaus.plexus/plexus-archiver
+               // third party dependency
+
+               throw new SlcException("Unimplemented method");
+
+               // // protected void writeFeatureDescriptor() throws
+               // MojoExecutionException {
+               // File featureDesc = File.createTempFile("feature", "xml");
+               // featureDesc.deleteOnExit();
+               //
+               // Writer writer = null;
+               // try {
+               // writer = new FileWriter(featureDesc);
+               // PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
+               // xmlWriter.startElement("feature");
+               // xmlWriter.addAttribute("id", project.getArtifactId());
+               // xmlWriter.addAttribute("label", project.getName());
+               //
+               // // Version
+               // String projectVersion = project.getVersion();
+               // int indexSnapshot = projectVersion.indexOf("-SNAPSHOT");
+               // if (indexSnapshot > -1)
+               // projectVersion = projectVersion.substring(0, indexSnapshot);
+               // projectVersion = projectVersion + ".qualifier";
+               //
+               // // project.
+               // xmlWriter.addAttribute("version", projectVersion);
+               //
+               // Organization organization = project.getOrganization();
+               // if (organization != null && organization.getName() != null)
+               // xmlWriter.addAttribute("provider-name", organization.getName());
+               //
+               // if (project.getDescription() != null || project.getUrl() != null) {
+               // xmlWriter.startElement("description");
+               // if (project.getUrl() != null)
+               // xmlWriter.addAttribute("url", project.getUrl());
+               // if (project.getDescription() != null)
+               // xmlWriter.writeText(project.getDescription());
+               // xmlWriter.endElement();// description
+               // }
+               //
+               // if (feature != null && feature.getCopyright() != null
+               // || (organization != null && organization.getUrl() != null)) {
+               // xmlWriter.startElement("copyright");
+               // if (organization != null && organization.getUrl() != null)
+               // xmlWriter.addAttribute("url", organization.getUrl());
+               // if (feature.getCopyright() != null)
+               // xmlWriter.writeText(feature.getCopyright());
+               // xmlWriter.endElement();// copyright
+               // }
+               //
+               // if (feature != null && feature.getUpdateSite() != null) {
+               // xmlWriter.startElement("url");
+               // xmlWriter.startElement("update");
+               // xmlWriter.addAttribute("url", feature.getUpdateSite());
+               // xmlWriter.endElement();// update
+               // xmlWriter.endElement();// url
+               // }
+               //
+               // List licenses = project.getLicenses();
+               // if (licenses.size() > 0) {
+               // // take the first one
+               // License license = (License) licenses.get(0);
+               // xmlWriter.startElement("license");
+               //
+               // if (license.getUrl() != null)
+               // xmlWriter.addAttribute("url", license.getUrl());
+               // if (license.getComments() != null)
+               // xmlWriter.writeText(license.getComments());
+               // else if (license.getName() != null)
+               // xmlWriter.writeText(license.getName());
+               // xmlWriter.endElement();// license
+               // }
+               //
+               // // deploymentRepository.pathOf(null);
+               // if (jarDirectory == null) {
+               // Set dependencies = mavenDependencyManager
+               // .getTransitiveProjectDependencies(project, remoteRepos,
+               // local);
+               // // // protected void writeFeatureDescriptor() throws
+               // MojoExecutionException {
+               // File featureDesc = File.createTempFile("feature", "xml");
+               // featureDesc.deleteOnExit();
+               //
+               // Writer writer = null;
+               // try {
+               // writer = new FileWriter(featureDesc);
+               // PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
+               // xmlWriter.startElement("feature");
+               // xmlWriter.addAttribute("id", project.getArtifactId());
+               // xmlWriter.addAttribute("label", project.getName());
+               //
+               // // Version
+               // String projectVersion = project.getVersion();
+               // int indexSnapshot = projectVersion.indexOf("-SNAPSHOT");
+               // if (indexSnapshot > -1)
+               // projectVersion = projectVersion.substring(0, indexSnapshot);
+               // projectVersion = projectVersion + ".qualifier";
+               //
+               // // project.
+               // xmlWriter.addAttribute("version", projectVersion);
+               //
+               // Organization organization = project.getOrganization();
+               // if (organization != null && organization.getName() != null)
+               // xmlWriter.addAttribute("provider-name", organization.getName());
+               //
+               // if (project.getDescription() != null || project.getUrl() != null) {
+               // xmlWriter.startElement("description");
+               // if (project.getUrl() != null)
+               // xmlWriter.addAttribute("url", project.getUrl());
+               // if (project.getDescription() != null)
+               // xmlWriter.writeText(project.getDescription());
+               // xmlWriter.endElement();// description
+               // }
+               //
+               // if (feature != null && feature.getCopyright() != null
+               // || (organization != null && organization.getUrl() != null)) {
+               // xmlWriter.startElement("copyright");
+               // if (organization != null && organization.getUrl() != null)
+               // xmlWriter.addAttribute("url", organization.getUrl());
+               // if (feature.getCopyright() != null)
+               // xmlWriter.writeText(feature.getCopyright());
+               // xmlWriter.endElement();// copyright
+               // }
+               //
+               // if (feature != null && feature.getUpdateSite() != null) {
+               // xmlWriter.startElement("url");
+               // xmlWriter.startElement("update");
+               // xmlWriter.addAttribute("url", feature.getUpdateSite());
+               // xmlWriter.endElement();// update
+               // xmlWriter.endElement();// url
+               // }
+               //
+               // List licenses = project.getLicenses();
+               // if (licenses.size() > 0) {
+               // // take the first one
+               // License license = (License) licenses.get(0);
+               // xmlWriter.startElement("license");
+               //
+               // if (license.getUrl() != null)
+               // xmlWriter.addAttribute("url", license.getUrl());
+               // if (license.getComments() != null)
+               // xmlWriter.writeText(license.getComments());
+               // else if (license.getName() != null)
+               // xmlWriter.writeText(license.getName());
+               // xmlWriter.endElement();// license
+               // }
+               //
+               // // deploymentRepository.pathOf(null);
+               // if (jarDirectory == null) {
+               // Set dependencies = mavenDependencyManager
+               // .getTransitiveProjectDependencies(project, remoteRepos,
+               // local);
+               // for (Iterator it = dependencies.iterator(); it.hasNext();) {
+               // Artifact artifact = (Artifact) it.next();
+               // writeFeaturePlugin(xmlWriter, artifact.getFile());
+               // }
+               // } else {
+               // // TODO: filter jars
+               // File[] jars = jarDirectory.listFiles();
+               // if (jars == null)
+               // throw new MojoExecutionException("No jar found in "
+               // + jarDirectory);
+               // for (int i = 0; i < jars.length; i++) {
+               // writeFeaturePlugin(xmlWriter, jars[i]);
+               // }
+               // }
+               //
+               // xmlWriter.endElement();// feature
+               //
+               // if (getLog().isDebugEnabled())
+               // getLog().debug("Wrote Eclipse feature descriptor.");
+               // } catch (Exception e) {
+               // throw new MojoExecutionException("Cannot write feature descriptor",
+               // e);
+               // } finally {
+               // IOUtil.close(writer);
+               // }for (Iterator it = dependencies.iterator(); it.hasNext();) {
+               // Artifact artifact = (Artifact) it.next();
+               // writeFeaturePlugin(xmlWriter, artifact.getFile());
+               // }
+               // } else {
+               // // TODO: filter jars
+               // File[] jars = jarDirectory.listFiles();
+               // if (jars == null)
+               // throw new MojoExecutionException("No jar found in "
+               // + jarDirectory);
+               // for (int i = 0; i < jars.length; i++) {
+               // writeFeaturePlugin(xmlWriter, jars[i]);
+               // }
+               // }
+               //
+               // xmlWriter.endElement();// feature
+               //
+               // if (getLog().isDebugEnabled())
+               // getLog().debug("Wrote Eclipse feature descriptor.");
+               // } catch (Exception e) {
+               // throw new MojoExecutionException("Cannot write feature descriptor",
+               // e);
+               // } finally {
+               // IOUtil.close(writer);
+               // }
+       }
+
+       /** Create an Aether like distribution artifact */
+       private byte[] generatePomFile() {
+               StringBuilder b = new StringBuilder();
+               // XML header
+               b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+               b.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
+               b.append("<modelVersion>4.0.0</modelVersion>");
+
+               // Artifact
+               b.append("<groupId>").append(osgiDistribution.getCategory())
+                               .append("</groupId>\n");
+               b.append("<artifactId>").append(osgiDistribution.getName())
+                               .append("</artifactId>\n");
+               b.append("<version>").append(osgiDistribution.getVersion())
+                               .append("</version>\n");
+               b.append("<packaging>pom</packaging>\n");
+               // p.append("<name>").append("Bundle Name").append("</name>\n");
+               // p.append("<description>").append("Bundle Description").append("</description>\n");
+
+               // Dependencies
+               b.append("<dependencies>\n");
+               for (Iterator<? extends NameVersion> it = osgiDistribution
+                               .nameVersions(); it.hasNext();) {
+                       NameVersion nameVersion = it.next();
+                       if (!(nameVersion instanceof CategorizedNameVersion))
+                               throw new SlcException("Unsupported type "
+                                               + nameVersion.getClass());
+                       CategorizedNameVersion nv = (CategorizedNameVersion) nameVersion;
+                       b.append(getDependencySnippet(nv, false));
+               }
+               b.append("</dependencies>\n");
+
+               // Dependency management
+               b.append("<dependencyManagement>\n");
+               b.append("<dependencies>\n");
+
+               for (Iterator<? extends NameVersion> it = osgiDistribution
+                               .nameVersions(); it.hasNext();)
+                       b.append(getDependencySnippet((CategorizedNameVersion) it.next(),
+                                       true));
+               b.append("</dependencies>\n");
+               b.append("</dependencyManagement>\n");
+
+               b.append("</project>\n");
+               return b.toString().getBytes();
+       }
+
+       private String getDependencySnippet(CategorizedNameVersion cnv,
+                       boolean includeVersion) { // , String type, String scope
+               StringBuilder b = new StringBuilder();
+               b.append("<dependency>\n");
+               b.append("\t<groupId>").append(cnv.getCategory())
+                               .append("</groupId>\n");
+               b.append("\t<artifactId>").append(cnv.getName())
+                               .append("</artifactId>\n");
+               if (includeVersion)
+                       b.append("\t<version>").append(cnv.getVersion())
+                                       .append("</version>\n");
+               // if (type!= null)
+               // p.append("\t<type>").append(type).append("</type>\n");
+               // if (type!= null)
+               // p.append("\t<scope>").append(scope).append("</scope>\n");
+               b.append("</dependency>\n");
+               return b.toString();
+       }
+
+       // Helpers
+       private void addToJar(byte[] content, String name, JarOutputStream target)
+                       throws IOException {
+               ByteArrayInputStream in = null;
+               try {
+                       target.putNextEntry(new JarEntry(name));
+                       in = new ByteArrayInputStream(content);
+                       byte[] buffer = new byte[1024];
+                       while (true) {
+                               int count = in.read(buffer);
+                               if (count == -1)
+                                       break;
+                               target.write(buffer, 0, count);
+                       }
+                       target.closeEntry();
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+       }
+
+       private String getCsvLine(NameVersion nameVersion)
+                       throws RepositoryException {
+               if (!(nameVersion instanceof CategorizedNameVersion))
+                       throw new SlcException("Unsupported type " + nameVersion.getClass());
+               CategorizedNameVersion cnv = (CategorizedNameVersion) nameVersion;
+               StringBuilder builder = new StringBuilder();
+
+               builder.append(cnv.getName());
+               builder.append(modularDistributionSeparator);
+               builder.append(nameVersion.getVersion());
+               builder.append(modularDistributionSeparator);
+               builder.append(cnv.getCategory().replace('.', '/'));
+               // MavenConventionsUtils.groupPath("", cnv.getCategory());
+               builder.append('/');
+               builder.append(cnv.getName());
+               builder.append('/');
+               builder.append(cnv.getVersion());
+               builder.append('/');
+               builder.append(cnv.getName());
+               builder.append('-');
+               builder.append(cnv.getVersion());
+               builder.append('.');
+               // TODO make this dynamic
+               builder.append("jar");
+               builder.append("\n");
+
+               return builder.toString();
+       }
+
+       /** Enable dependency injection */
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+
+       public void setOsgiDistribution(ArgeoOsgiDistribution osgiDistribution) {
+               this.osgiDistribution = osgiDistribution;
+       }
+
+       public void setModularDistributionSeparator(
+                       String modularDistributionSeparator) {
+               this.modularDistributionSeparator = modularDistributionSeparator;
+       }
+
+       public void setArtifactBasePath(String artifactBasePath) {
+               this.artifactBasePath = artifactBasePath;
+       }
+
+       public void setArtifactType(String artifactType) {
+               this.artifactType = artifactType;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/ModularDistributionIndexer.java
new file mode 100644 (file)
index 0000000..bca0496
--- /dev/null
@@ -0,0 +1,322 @@
+package org.argeo.slc.repo;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+
+import javax.jcr.Binary;
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherUtils;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.osgi.framework.Constants;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Create or update JCR meta-data for an SLC Modular Distribution
+ * 
+ * Currently, following types are managed: <list><li>* .jar: dependency
+ * artifacts with csv index</li> <li>@Deprecated : .pom: artifact (binaries)
+ * that indexes a group, the .pom file contains a tag "dependencyManagement"
+ * that list all modules</li> </list>
+ */
+public class ModularDistributionIndexer implements NodeIndexer, SlcNames {
+       private final static Log log = LogFactory
+                       .getLog(ModularDistributionIndexer.class);
+
+       // Constants for csv indexing
+       private final static String INDEX_FILE_NAME = "modularDistribution.csv";
+       private String separator = ",";
+
+       // TODO remove this: binaries have been replaced by modular distribution
+       // // Artifact indexing
+       // private final static List<String> BINARIES_ARTIFACTS_NAME;
+       // static {
+       // List<String> tmpList = new ArrayList<String>();
+       // tmpList.add(RepoConstants.BINARIES_ARTIFACT_ID);
+       // // tmpList.add(RepoConstants.SOURCES_ARTIFACT_ID);
+       // // tmpList.add(RepoConstants.SDK_ARTIFACT_ID);
+       // BINARIES_ARTIFACTS_NAME = Collections.unmodifiableList(tmpList);
+       // }
+
+       private Manifest manifest;
+
+       public Boolean support(String path) {
+               if (FilenameUtils.getExtension(path).equals("jar"))
+                       return true;
+               // if (FilenameUtils.getExtension(path).equals("pom")
+               // && BINARIES_ARTIFACTS_NAME.contains(FilenameUtils.getName(path)
+               // .split("-")[0]))
+               // return true;
+               return false;
+       }
+
+       public void index(Node fileNode) {
+               Binary fileBinary = null;
+               try {
+
+                       String fileNodePath = fileNode.getPath();
+                       if (!support(fileNodePath))
+                               return;
+
+                       if (!fileNode.isNodeType(NodeType.NT_FILE))
+                               return;
+
+                       Node contentNode = fileNode.getNode(Node.JCR_CONTENT);
+                       fileBinary = contentNode.getProperty(Property.JCR_DATA).getBinary();
+
+                       MyModularDistribution currDist = null;
+                       if (FilenameUtils.getExtension(fileNode.getPath()).equals("jar"))
+                               currDist = listModulesFromCsvIndex(fileNode, fileBinary);
+                       // else if (FilenameUtils.getExtension(fileNode.getPath()).equals(
+                       // "pom"))
+                       // currDist = listModulesFromPomIndex(fileNode, fileBinary);
+
+                       if (fileNode.isNodeType(SlcTypes.SLC_MODULAR_DISTRIBUTION)
+                                       || currDist == null || !currDist.nameVersions().hasNext())
+                               return; // already indexed or no modules found
+                       else {
+                               fileNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
+                               fileNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
+                               if (currDist.getCategory() != null)
+                                       fileNode.setProperty(SLC_CATEGORY, currDist.getCategory());
+                               fileNode.setProperty(SLC_NAME, currDist.getName());
+                               fileNode.setProperty(SLC_VERSION, currDist.getVersion());
+                               indexDistribution(currDist, fileNode);
+                       }
+
+                       if (log.isTraceEnabled())
+                               log.trace("Indexed " + fileNode + " as modular distribution");
+               } catch (Exception e) {
+                       throw new SlcException("Cannot list dependencies from " + fileNode,
+                                       e);
+               }
+       }
+
+       private void indexDistribution(ArgeoOsgiDistribution osgiDist, Node distNode)
+                       throws RepositoryException {
+               distNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
+               distNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
+               distNode.setProperty(SlcNames.SLC_CATEGORY, osgiDist.getCategory());
+               distNode.setProperty(SlcNames.SLC_NAME, osgiDist.getName());
+               distNode.setProperty(SlcNames.SLC_VERSION, osgiDist.getVersion());
+               if (distNode.hasNode(SLC_MODULES))
+                       distNode.getNode(SLC_MODULES).remove();
+               Node modules = distNode.addNode(SLC_MODULES, NodeType.NT_UNSTRUCTURED);
+
+               for (Iterator<? extends NameVersion> it = osgiDist.nameVersions(); it
+                               .hasNext();)
+                       addModule(modules, it.next());
+       }
+
+       // Helpers
+       private Node addModule(Node modules, NameVersion nameVersion)
+                       throws RepositoryException {
+               CategorizedNameVersion cnv = (CategorizedNameVersion) nameVersion;
+               Node moduleCoord = null;
+               moduleCoord = modules.addNode(cnv.getName(),
+                               SlcTypes.SLC_MODULE_COORDINATES);
+               moduleCoord.setProperty(SlcNames.SLC_CATEGORY, cnv.getCategory());
+               moduleCoord.setProperty(SlcNames.SLC_NAME, cnv.getName());
+               moduleCoord.setProperty(SlcNames.SLC_VERSION, cnv.getVersion());
+               return moduleCoord;
+       }
+
+       private MyModularDistribution listModulesFromCsvIndex(Node fileNode,
+                       Binary fileBinary) {
+               JarInputStream jarIn = null;
+               BufferedReader reader = null;
+               try {
+                       jarIn = new JarInputStream(fileBinary.getStream());
+
+                       List<CategorizedNameVersion> modules = new ArrayList<CategorizedNameVersion>();
+
+                       // meta data
+                       manifest = jarIn.getManifest();
+                       if (manifest == null) {
+                               log.error(fileNode + " has no MANIFEST");
+                               return null;
+                       }
+                       String category = manifest.getMainAttributes().getValue(
+                                       RepoConstants.SLC_GROUP_ID);
+                       String name = manifest.getMainAttributes().getValue(
+                                       Constants.BUNDLE_SYMBOLICNAME);
+                       String version = manifest.getMainAttributes().getValue(
+                                       Constants.BUNDLE_VERSION);
+
+                       Artifact distribution = new DefaultArtifact(category, name, "jar",
+                                       version);
+                       // Retrieve the index file
+                       JarEntry indexEntry;
+                       while ((indexEntry = jarIn.getNextJarEntry()) != null) {
+                               String entryName = indexEntry.getName();
+                               if (entryName.equals(INDEX_FILE_NAME)) {
+                                       break;
+                               }
+                               try {
+                                       jarIn.closeEntry();
+                               } catch (SecurityException se) {
+                                       log.error("Invalid signature file digest "
+                                                       + "for Manifest main attributes: " + entryName
+                                                       + " while looking for an index in bundle " + name);
+                               }
+                       }
+                       if (indexEntry == null)
+                               return null; // Not a modular definition
+
+                       // Process the index
+                       reader = new BufferedReader(new InputStreamReader(jarIn));
+                       String line = null;
+                       while ((line = reader.readLine()) != null) {
+                               StringTokenizer st = new StringTokenizer(line, separator);
+                               st.nextToken(); // moduleName
+                               st.nextToken(); // moduleVersion
+                               String relativeUrl = st.nextToken();
+                               Artifact currModule = AetherUtils.convertPathToArtifact(
+                                               relativeUrl, null);
+                               modules.add(new MyCategorizedNameVersion(currModule
+                                               .getGroupId(), currModule.getArtifactId(), currModule
+                                               .getVersion()));
+                       }
+                       return new MyModularDistribution(distribution, modules);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot list artifacts", e);
+               } finally {
+                       IOUtils.closeQuietly(jarIn);
+                       IOUtils.closeQuietly(reader);
+               }
+       }
+
+       // private MyModularDistribution listModulesFromPomIndex(Node fileNode,
+       // Binary fileBinary) {
+       // InputStream input = null;
+       // List<CategorizedNameVersion> modules = new
+       // ArrayList<CategorizedNameVersion>();
+       // try {
+       // input = fileBinary.getStream();
+       //
+       // DocumentBuilder documentBuilder = DocumentBuilderFactory
+       // .newInstance().newDocumentBuilder();
+       // Document doc = documentBuilder.parse(input);
+       // // properties
+       // Properties props = new Properties();
+       // // props.setProperty("project.version",
+       // // pomArtifact.getBaseVersion());
+       // NodeList properties = doc.getElementsByTagName("properties");
+       // if (properties.getLength() > 0) {
+       // NodeList propertiesElems = properties.item(0).getChildNodes();
+       // for (int i = 0; i < propertiesElems.getLength(); i++) {
+       // if (propertiesElems.item(i) instanceof Element) {
+       // Element property = (Element) propertiesElems.item(i);
+       // props.put(property.getNodeName(),
+       // property.getTextContent());
+       // }
+       // }
+       // }
+       //
+       // // full coordinates are under <dependencyManagement><dependencies>
+       // NodeList dependencies = ((Element) doc.getElementsByTagName(
+       // "dependencyManagement").item(0))
+       // .getElementsByTagName("dependency");
+       // for (int i = 0; i < dependencies.getLength(); i++) {
+       // Element dependency = (Element) dependencies.item(i);
+       // String groupId = dependency.getElementsByTagName("groupId")
+       // .item(0).getTextContent().trim();
+       // String artifactId = dependency
+       // .getElementsByTagName("artifactId").item(0)
+       // .getTextContent().trim();
+       // String version = dependency.getElementsByTagName("version")
+       // .item(0).getTextContent().trim();
+       // modules.add(new MyCategorizedNameVersion(groupId, artifactId,
+       // version));
+       // }
+       //
+       // String groupId = doc.getElementsByTagName("groupId").item(0)
+       // .getTextContent().trim();
+       // String artifactId = doc.getElementsByTagName("artifactId").item(0)
+       // .getTextContent().trim();
+       // String version = doc.getElementsByTagName("version").item(0)
+       // .getTextContent().trim();
+       //
+       // Artifact currDist = new DefaultArtifact(groupId, artifactId, "pom",
+       // version);
+       //
+       // return new MyModularDistribution(currDist, modules);
+       // } catch (Exception e) {
+       // throw new SlcException("Cannot process pom " + fileNode, e);
+       // } finally {
+       // IOUtils.closeQuietly(input);
+       // }
+       // }
+
+       /** The created modular distribution */
+       private static class MyCategorizedNameVersion extends DefaultNameVersion
+                       implements CategorizedNameVersion {
+               private final String category;
+
+               public MyCategorizedNameVersion(String category, String name,
+                               String version) {
+                       super(name, version);
+                       this.category = category;
+               }
+
+               public String getCategory() {
+                       return category;
+               }
+       }
+
+       /**
+        * A consistent and versioned OSGi distribution, which can be built and
+        * tested.
+        */
+       private class MyModularDistribution extends ArtifactDistribution implements
+                       ArgeoOsgiDistribution {
+
+               private List<CategorizedNameVersion> modules;
+
+               public MyModularDistribution(Artifact artifact,
+                               List<CategorizedNameVersion> modules) {
+                       super(artifact);
+                       this.modules = modules;
+               }
+
+               public Iterator<CategorizedNameVersion> nameVersions() {
+                       return modules.iterator();
+               }
+
+               // Modular distribution interface methods. Not yet used.
+               public Distribution getModuleDistribution(String moduleName,
+                               String moduleVersion) {
+                       return null;
+               }
+
+               public Object getModulesDescriptor(String descriptorType) {
+                       return null;
+               }
+       }
+
+       /** Separator used to parse the tabular file, default is "," */
+       public void setSeparator(String modulesUrlSeparator) {
+               this.separator = modulesUrlSeparator;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexer.java
new file mode 100644 (file)
index 0000000..77798ab
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import javax.jcr.Node;
+import javax.jcr.observation.EventListener;
+
+/**
+ * Adds metadata to an existing node, ideally via observation after it has been
+ * added. There is a similar concept in ModeShape with which this abstraction
+ * may be merged in the future.
+ */
+public interface NodeIndexer {
+       /**
+        * Whether the node at this path will be supported. This is typically use in
+        * an {@link EventListener} before the node is loaded, and would apply on
+        * information contained in the path / file name: file extension, base path,
+        * etc. If the node needs to be loaded, the recommended approach is to
+        * return <code>true</code> here and wait for index to be called, possibly
+        * returning without processing if the node should not be indexed. While
+        * not strictly a requirement, this avoids to open sessions in the indexer,
+        * centralizing such tasks in the caller.
+        */
+       public Boolean support(String path);
+
+       /**
+        * Adds the metadata. This is the responsibility of the caller to save the
+        * underlying session.
+        */
+       public void index(Node node);
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexerVisitor.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/NodeIndexerVisitor.java
new file mode 100644 (file)
index 0000000..c0f90d1
--- /dev/null
@@ -0,0 +1,48 @@
+package org.argeo.slc.repo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.jcr.ItemVisitor;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+
+/**
+ * Recursively visit a sub tree and apply the list of node indexer on supported
+ * nodes.
+ */
+public class NodeIndexerVisitor implements ItemVisitor {
+       /** order may be important */
+       private List<NodeIndexer> nodeIndexers = new ArrayList<NodeIndexer>();
+
+       public NodeIndexerVisitor() {
+       }
+
+       /** Convenience constructor */
+       public NodeIndexerVisitor(NodeIndexer nodeIndexer) {
+               nodeIndexers.add(nodeIndexer);
+       }
+
+       public NodeIndexerVisitor(List<NodeIndexer> nodeIndexers) {
+               this.nodeIndexers = nodeIndexers;
+       }
+
+       public void visit(Node node) throws RepositoryException {
+               for (NodeIndexer nodeIndexer : nodeIndexers)
+                       if (nodeIndexer.support(node.getPath()))
+                               nodeIndexer.index(node);
+
+               for (NodeIterator it = node.getNodes(); it.hasNext();)
+                       visit(it.nextNode());
+       }
+
+       public void visit(Property property) throws RepositoryException {
+       }
+
+       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
+               this.nodeIndexers = nodeIndexers;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiBundlesProvider.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiBundlesProvider.java
new file mode 100644 (file)
index 0000000..de5f03c
--- /dev/null
@@ -0,0 +1,12 @@
+package org.argeo.slc.repo;
+
+import java.util.List;
+
+/**
+ * Provides OSGi bundles either by linking to them, by wrapping existing
+ * archives or by building them.
+ */
+public interface OsgiBundlesProvider {
+       /** The provided bundles in the order they will be retrieved/wrapped/built. */
+       public List<ArtifactDistribution> provides();
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiFactory.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/OsgiFactory.java
new file mode 100644 (file)
index 0000000..8178493
--- /dev/null
@@ -0,0 +1,28 @@
+package org.argeo.slc.repo;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+/** OSGi Factory */
+public interface OsgiFactory {
+       public Session openJavaSession() throws RepositoryException;
+
+       public Session openDistSession() throws RepositoryException;
+
+       public void indexNode(Node node);
+
+       /**
+        * Provide access to a third party archive in the 'dist' repository,
+        * downloading it if it is not available.
+        */
+       public Node getDist(Session distSession, String uri)
+                       throws RepositoryException;
+
+       /**
+        * Provide access to a cached maven ardifact identified by its coordinates
+        * the 'dist' repository, downloading it if it is not available.
+        */
+       public Node getMaven(Session distSession, String coords)
+                       throws RepositoryException;
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/PdeSourcesIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/PdeSourcesIndexer.java
new file mode 100644 (file)
index 0000000..97ca286
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import javax.jcr.Binary;
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Creates pde sources from a source {@link Artifact} with name
+ * "...-sources.jar"
+ */
+public class PdeSourcesIndexer implements NodeIndexer {
+       private Log log = LogFactory.getLog(PdeSourcesIndexer.class);
+
+       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+
+       // private ArtifactIndexer artifactIndexer;
+       // private JarFileIndexer jarFileIndexer;
+
+       // public PdeSourcesIndexer(){
+       // // ArtifactIndexer artifactIndexer,
+       // // JarFileIndexer jarFileIndexer) {
+       // // this.artifactIndexer = artifactIndexer;
+       // // this.jarFileIndexer = jarFileIndexer;
+       // }
+
+       public Boolean support(String path) {
+               // TODO implement clean management of same name siblings
+               String name = FilenameUtils.getBaseName(path);
+               // int lastInd = name.lastIndexOf("[");
+               // if (lastInd != -1)
+               // name = name.substring(0, lastInd);
+               return name.endsWith("-sources")
+                               && FilenameUtils.getExtension(path).equals("jar");
+       }
+
+       public void index(Node sourcesNode) {
+               try {
+                       if (!support(sourcesNode.getPath()))
+                               return;
+
+                       packageSourcesAsPdeSource(sourcesNode);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot generate pde sources for node "
+                                       + sourcesNode, e);
+               }
+       }
+
+       protected void packageSourcesAsPdeSource(Node sourcesNode) {
+               Binary origBinary = null;
+               Binary osgiBinary = null;
+               try {
+                       Session session = sourcesNode.getSession();
+                       Artifact sourcesArtifact = AetherUtils.convertPathToArtifact(
+                                       sourcesNode.getPath(), null);
+
+                       // read name version from manifest
+                       Artifact osgiArtifact = new DefaultArtifact(
+                                       sourcesArtifact.getGroupId(),
+                                       sourcesArtifact.getArtifactId(),
+                                       sourcesArtifact.getExtension(),
+                                       sourcesArtifact.getVersion());
+                       String osgiPath = MavenConventionsUtils.artifactPath(
+                                       artifactBasePath, osgiArtifact);
+                       osgiBinary = session.getNode(osgiPath).getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary();
+
+                       NameVersion nameVersion = RepoUtils.readNameVersion(osgiBinary
+                                       .getStream());
+
+                       // create PDe sources artifact
+                       Artifact pdeSourceArtifact = new DefaultArtifact(
+                                       sourcesArtifact.getGroupId(),
+                                       sourcesArtifact.getArtifactId() + ".source",
+                                       sourcesArtifact.getExtension(),
+                                       sourcesArtifact.getVersion());
+                       String targetSourceParentPath = MavenConventionsUtils
+                                       .artifactParentPath(artifactBasePath, pdeSourceArtifact);
+                       String targetSourceFileName = MavenConventionsUtils
+                                       .artifactFileName(pdeSourceArtifact);
+                       // String targetSourceJarPath = targetSourceParentPath + '/'
+                       // + targetSourceFileName;
+
+                       Node targetSourceParentNode = JcrUtils.mkfolders(session,
+                                       targetSourceParentPath);
+                       origBinary = sourcesNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary();
+                       byte[] targetJarBytes = RepoUtils.packageAsPdeSource(
+                                       origBinary.getStream(), nameVersion);
+                       JcrUtils.copyBytesAsFile(targetSourceParentNode,
+                                       targetSourceFileName, targetJarBytes);
+
+                       // reindex
+                       // Automagically done via the various listeners or manually
+                       // triggered.
+                       // Node targetSourceJarNode = session.getNode(targetSourceJarPath);
+                       // artifactIndexer.index(targetSourceJarNode);
+                       // jarFileIndexer.index(targetSourceJarNode);
+                       if (log.isTraceEnabled())
+                               log.trace("Created pde source artifact " + pdeSourceArtifact
+                                               + " from " + sourcesNode);
+
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot add PDE sources for " + sourcesNode,
+                                       e);
+               } finally {
+                       JcrUtils.closeQuietly(origBinary);
+                       JcrUtils.closeQuietly(osgiBinary);
+               }
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoConstants.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoConstants.java
new file mode 100644 (file)
index 0000000..4358e98
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+/** SLC repository constants */
+public interface RepoConstants {
+       public final static String DEFAULT_JAVA_REPOSITORY_ALIAS = "java";
+       public final static String DEFAULT_JAVA_REPOSITORY_LABEL = "Internal Java Repository";
+
+       public final static String DEFAULT_ARTIFACTS_BASE_PATH = "/";
+       public final static String REPO_BASEPATH = "/slc:repo";
+       public final static String PROXIED_REPOSITORIES = REPO_BASEPATH
+                       + "/slc:sources";
+       public final static String DISTRIBUTIONS_BASE_PATH = REPO_BASEPATH
+                       + "/slc:distributions";
+       public final static String REPOSITORIES_BASE_PATH = REPO_BASEPATH
+                       + "/slc:repositories";
+       public final static String BINARIES_ARTIFACT_ID = "binaries";
+       public final static String SOURCES_ARTIFACT_ID = "sources";
+       public final static String SDK_ARTIFACT_ID = "sdk";
+       
+       // TODO might exists somewhere else
+       public final static String SLC_GROUP_ID = "SLC-GroupId";
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoService.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoService.java
new file mode 100644 (file)
index 0000000..9b9bc66
--- /dev/null
@@ -0,0 +1,14 @@
+package org.argeo.slc.repo;
+
+import javax.jcr.Session;
+
+/** Start factorisation of the session management using a manager service */
+public interface RepoService {
+
+       /**
+        * Returns a corresponding session given the current context. Caller must
+        * close the session once it has been used
+        */
+       public Session getRemoteSession(String repoNodePath, String uri,
+                       String workspaceName);
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoSync.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoSync.java
new file mode 100644 (file)
index 0000000..7f1e1e3
--- /dev/null
@@ -0,0 +1,633 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+
+import javax.jcr.Binary;
+import javax.jcr.Credentials;
+import javax.jcr.NoSuchWorkspaceException;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import javax.jcr.PropertyType;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.RepositoryFactory;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.nodetype.NodeType;
+import javax.jcr.query.Query;
+import javax.jcr.query.QueryResult;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.xml.sax.SAXException;
+
+/**
+ * Synchronise workspaces from a remote software repository to the local
+ * repository (Synchronisation in the other direction does not work).
+ * 
+ * Workspaces are retrieved by name given a map that links the source with a
+ * target name. If a target workspace does not exist, it is created. Otherwise
+ * we copy the content of the source workspace into the target one.
+ */
+public class RepoSync implements Runnable {
+       private final static Log log = LogFactory.getLog(RepoSync.class);
+
+       // Centralizes definition of workspaces that must be ignored by the sync.
+       private final static List<String> IGNORED_WKSP_LIST = Arrays.asList(
+                       "security", "localrepo");
+
+       private final Calendar zero;
+       private Session sourceDefaultSession = null;
+       private Session targetDefaultSession = null;
+
+       private Repository sourceRepository;
+       private Credentials sourceCredentials;
+       private Repository targetRepository;
+       private Credentials targetCredentials;
+
+       // if Repository and Credentials objects are not explicitly set
+       private String sourceRepoUri;
+       private String sourceUsername;
+       private char[] sourcePassword;
+       private String targetRepoUri;
+       private String targetUsername;
+       private char[] targetPassword;
+
+       private RepositoryFactory repositoryFactory;
+
+       private ArgeoMonitor monitor;
+       private Map<String, String> workspaceMap;
+
+       // TODO fix monitor
+       private Boolean filesOnly = false;
+
+       public RepoSync() {
+               zero = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+               zero.setTimeInMillis(0);
+       }
+
+       /**
+        * 
+        * Shortcut to instantiate a RepoSync with already known repositories and
+        * credentials.
+        * 
+        * @param sourceRepository
+        * @param sourceCredentials
+        * @param targetRepository
+        * @param targetCredentials
+        */
+       public RepoSync(Repository sourceRepository, Credentials sourceCredentials,
+                       Repository targetRepository, Credentials targetCredentials) {
+               this();
+               this.sourceRepository = sourceRepository;
+               this.sourceCredentials = sourceCredentials;
+               this.targetRepository = targetRepository;
+               this.targetCredentials = targetCredentials;
+       }
+
+       public void run() {
+               try {
+                       long begin = System.currentTimeMillis();
+
+                       // Setup
+                       if (sourceRepository == null)
+                               sourceRepository = ArgeoJcrUtils.getRepositoryByUri(
+                                               repositoryFactory, sourceRepoUri);
+                       if (sourceCredentials == null && sourceUsername != null)
+                               sourceCredentials = new SimpleCredentials(sourceUsername,
+                                               sourcePassword);
+                       sourceDefaultSession = sourceRepository.login(sourceCredentials);
+
+                       if (targetRepository == null)
+                               targetRepository = ArgeoJcrUtils.getRepositoryByUri(
+                                               repositoryFactory, targetRepoUri);
+                       if (targetCredentials == null && targetUsername != null)
+                               targetCredentials = new SimpleCredentials(targetUsername,
+                                               targetPassword);
+                       targetDefaultSession = targetRepository.login(targetCredentials);
+
+                       Map<String, Exception> errors = new HashMap<String, Exception>();
+                       for (String sourceWorkspaceName : sourceDefaultSession
+                                       .getWorkspace().getAccessibleWorkspaceNames()) {
+                               if (monitor != null && monitor.isCanceled())
+                                       break;
+
+                               if (workspaceMap != null
+                                               && !workspaceMap.containsKey(sourceWorkspaceName))
+                                       continue;
+                               if (IGNORED_WKSP_LIST.contains(sourceWorkspaceName))
+                                       continue;
+
+                               Session sourceSession = null;
+                               Session targetSession = null;
+                               String targetWorkspaceName = workspaceMap
+                                               .get(sourceWorkspaceName);
+                               try {
+                                       try {
+                                               targetSession = targetRepository.login(
+                                                               targetCredentials, targetWorkspaceName);
+                                       } catch (NoSuchWorkspaceException e) {
+                                               targetDefaultSession.getWorkspace().createWorkspace(
+                                                               targetWorkspaceName);
+                                               targetSession = targetRepository.login(
+                                                               targetCredentials, targetWorkspaceName);
+                                       }
+                                       sourceSession = sourceRepository.login(sourceCredentials,
+                                                       sourceWorkspaceName);
+                                       syncWorkspace(sourceSession, targetSession);
+                               } catch (Exception e) {
+                                       errors.put("Could not sync workspace "
+                                                       + sourceWorkspaceName, e);
+                                       if (log.isErrorEnabled())
+                                               e.printStackTrace();
+
+                               } finally {
+                                       JcrUtils.logoutQuietly(sourceSession);
+                                       JcrUtils.logoutQuietly(targetSession);
+                               }
+                       }
+
+                       if (monitor != null && monitor.isCanceled())
+                               log.info("Sync has been canceled by user");
+
+                       long duration = (System.currentTimeMillis() - begin) / 1000;// s
+                       log.info("Sync " + sourceRepoUri + " to " + targetRepoUri + " in "
+                                       + (duration / 60)
+
+                                       + "min " + (duration % 60) + "s");
+
+                       if (errors.size() > 0) {
+                               throw new SlcException("Sync failed " + errors);
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot sync " + sourceRepoUri + " to "
+                                       + targetRepoUri, e);
+               } finally {
+                       JcrUtils.logoutQuietly(sourceDefaultSession);
+                       JcrUtils.logoutQuietly(targetDefaultSession);
+               }
+       }
+
+       private long getNodesNumber(Session session) {
+               if (IGNORED_WKSP_LIST.contains(session.getWorkspace().getName()))
+                       return 0l;
+               try {
+                       Query countQuery = session
+                                       .getWorkspace()
+                                       .getQueryManager()
+                                       .createQuery(
+                                                       "select file from ["
+                                                                       + (true ? NodeType.NT_FILE
+                                                                                       : NodeType.NT_BASE) + "] as file",
+                                                       Query.JCR_SQL2);
+
+                       QueryResult result = countQuery.execute();
+                       Long expectedCount = result.getNodes().getSize();
+                       return expectedCount;
+               } catch (RepositoryException e) {
+                       throw new SlcException("Unexpected error while computing "
+                                       + "the size of the fetch for workspace "
+                                       + session.getWorkspace().getName(), e);
+               }
+       }
+
+       protected void syncWorkspace(Session sourceSession, Session targetSession) {
+               if (monitor != null) {
+                       monitor.beginTask("Computing fetch size...", -1);
+                       Long totalAmount = getNodesNumber(sourceSession);
+                       monitor.beginTask("Fetch", totalAmount.intValue());
+               }
+
+               try {
+                       String msg = "Synchronizing workspace: "
+                                       + sourceSession.getWorkspace().getName();
+                       if (monitor != null)
+                               monitor.setTaskName(msg);
+                       if (log.isDebugEnabled())
+                               log.debug(msg);
+
+                       if (filesOnly) {
+                               JcrUtils.copyFiles(sourceSession.getRootNode(),
+                                               targetSession.getRootNode(), true, monitor);
+                       } else {
+                               for (NodeIterator it = sourceSession.getRootNode().getNodes(); it
+                                               .hasNext();) {
+                                       Node node = it.nextNode();
+                                       if (node.getName().equals("jcr:system"))
+                                               continue;
+                                       syncNode(node, targetSession);
+                               }
+                       }
+                       if (log.isDebugEnabled())
+                               log.debug("Synced " + sourceSession.getWorkspace().getName());
+               } catch (Exception e) {
+                       e.printStackTrace();
+                       throw new SlcException("Cannot sync "
+                                       + sourceSession.getWorkspace().getName() + " to "
+                                       + targetSession.getWorkspace().getName(), e);
+               }
+       }
+
+       /** factorizes monitor management */
+       private void updateMonitor(String msg) {
+               updateMonitor(msg, false);
+       }
+
+       protected void syncNode(Node sourceNode, Session targetSession)
+                       throws RepositoryException, SAXException {
+               // Boolean singleLevel = singleLevel(sourceNode);
+               try {
+                       if (monitor != null && monitor.isCanceled()) {
+                               updateMonitor("Fetched has been canceled, "
+                                               + "process is terminating");
+                               return;
+                       }
+
+                       Node targetParentNode = targetSession.getNode(sourceNode
+                                       .getParent().getPath());
+                       Node targetNode;
+                       if (monitor != null
+                                       && sourceNode.isNodeType(NodeType.NT_HIERARCHY_NODE))
+                               monitor.subTask("Process " + sourceNode.getPath());
+
+                       final Boolean isNew;
+                       if (!targetSession.itemExists(sourceNode.getPath())) {
+                               isNew = true;
+                               targetNode = targetParentNode.addNode(sourceNode.getName(),
+                                               sourceNode.getPrimaryNodeType().getName());
+                       } else {
+                               isNew = false;
+                               targetNode = targetSession.getNode(sourceNode.getPath());
+                               if (!targetNode.getPrimaryNodeType().getName()
+                                               .equals(sourceNode.getPrimaryNodeType().getName()))
+                                       targetNode.setPrimaryType(sourceNode.getPrimaryNodeType()
+                                                       .getName());
+                       }
+
+                       // export
+                       // sourceNode.getSession().exportSystemView(sourceNode.getPath(),
+                       // contentHandler, false, singleLevel);
+
+                       // if (singleLevel) {
+                       // if (targetSession.hasPendingChanges()) {
+                       // // updateMonitor(
+                       // // (isNew ? "Added " : "Updated ") + targetNode.getPath(),
+                       // // true);
+                       // if (doSave)
+                       // targetSession.save();
+                       // } else {
+                       // // updateMonitor("Checked " + targetNode.getPath(), false);
+                       // }
+                       // }
+
+                       // mixin and properties
+                       for (NodeType nt : sourceNode.getMixinNodeTypes()) {
+                               if (!targetNode.isNodeType(nt.getName())
+                                               && targetNode.canAddMixin(nt.getName()))
+                                       targetNode.addMixin(nt.getName());
+                       }
+                       copyProperties(sourceNode, targetNode);
+
+                       // next level
+                       NodeIterator ni = sourceNode.getNodes();
+                       while (ni != null && ni.hasNext()) {
+                               Node sourceChild = ni.nextNode();
+                               syncNode(sourceChild, targetSession);
+                       }
+
+                       copyTimestamps(sourceNode, targetNode);
+
+                       if (sourceNode.isNodeType(NodeType.NT_HIERARCHY_NODE)) {
+                               if (targetSession.hasPendingChanges()) {
+                                       if (sourceNode.isNodeType(NodeType.NT_FILE))
+                                               updateMonitor((isNew ? "Added " : "Updated ")
+                                                               + targetNode.getPath(), true);
+                                       // if (doSave)
+                                       targetSession.save();
+                               } else {
+                                       if (sourceNode.isNodeType(NodeType.NT_FILE))
+                                               updateMonitor("Checked " + targetNode.getPath(), false);
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot sync source node " + sourceNode, e);
+               }
+       }
+
+       private void copyTimestamps(Node sourceNode, Node targetNode)
+                       throws RepositoryException {
+               if (sourceNode.getDefinition().isProtected())
+                       return;
+               if (targetNode.getDefinition().isProtected())
+                       return;
+               copyTimestamp(sourceNode, targetNode, Property.JCR_CREATED);
+               copyTimestamp(sourceNode, targetNode, Property.JCR_CREATED_BY);
+               copyTimestamp(sourceNode, targetNode, Property.JCR_LAST_MODIFIED);
+               copyTimestamp(sourceNode, targetNode, Property.JCR_LAST_MODIFIED_BY);
+       }
+
+       private void copyTimestamp(Node sourceNode, Node targetNode, String property)
+                       throws RepositoryException {
+               if (sourceNode.hasProperty(property)) {
+                       Property p = sourceNode.getProperty(property);
+                       if (p.getDefinition().isProtected())
+                               return;
+                       if (targetNode.hasProperty(property)
+                                       && targetNode
+                                                       .getProperty(property)
+                                                       .getValue()
+                                                       .equals(sourceNode.getProperty(property).getValue()))
+                               return;
+                       targetNode.setProperty(property, sourceNode.getProperty(property)
+                                       .getValue());
+               }
+       }
+
+       private void copyProperties(Node sourceNode, Node targetNode)
+                       throws RepositoryException {
+               properties: for (PropertyIterator pi = sourceNode.getProperties(); pi
+                               .hasNext();) {
+                       Property p = pi.nextProperty();
+                       if (p.getDefinition().isProtected())
+                               continue properties;
+                       if (p.getName().equals(Property.JCR_CREATED)
+                                       || p.getName().equals(Property.JCR_CREATED_BY)
+                                       || p.getName().equals(Property.JCR_LAST_MODIFIED)
+                                       || p.getName().equals(Property.JCR_LAST_MODIFIED_BY))
+                               continue properties;
+
+                       if (p.getType() == PropertyType.BINARY) {
+                               copyBinary(p, targetNode);
+                       } else {
+
+                               if (p.isMultiple()) {
+                                       if (!targetNode.hasProperty(p.getName())
+                                                       || !Arrays.equals(
+                                                                       targetNode.getProperty(p.getName())
+                                                                                       .getValues(), p.getValues()))
+                                               targetNode.setProperty(p.getName(), p.getValues());
+                               } else {
+                                       if (!targetNode.hasProperty(p.getName())
+                                                       || !targetNode.getProperty(p.getName()).getValue()
+                                                                       .equals(p.getValue()))
+                                               targetNode.setProperty(p.getName(), p.getValue());
+                               }
+                       }
+               }
+       }
+
+       private static void copyBinary(Property p, Node targetNode)
+                       throws RepositoryException {
+               InputStream in = null;
+               Binary sourceBinary = null;
+               Binary targetBinary = null;
+               try {
+                       sourceBinary = p.getBinary();
+                       if (targetNode.hasProperty(p.getName()))
+                               targetBinary = targetNode.getProperty(p.getName()).getBinary();
+
+                       // optim FIXME make it more configurable
+                       if (targetBinary != null)
+                               if (sourceBinary.getSize() == targetBinary.getSize()) {
+                                       if (log.isTraceEnabled())
+                                               log.trace("Skipped " + p.getPath());
+                                       return;
+                               }
+
+                       in = sourceBinary.getStream();
+                       targetBinary = targetNode.getSession().getValueFactory()
+                                       .createBinary(in);
+                       targetNode.setProperty(p.getName(), targetBinary);
+               } catch (Exception e) {
+                       throw new SlcException("Could not transfer " + p, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       JcrUtils.closeQuietly(sourceBinary);
+                       JcrUtils.closeQuietly(targetBinary);
+               }
+       }
+
+       /** factorizes monitor management */
+       private void updateMonitor(String msg, Boolean doLog) {
+               if (doLog && log.isDebugEnabled())
+                       log.debug(msg);
+               if (monitor != null) {
+                       monitor.worked(1);
+                       monitor.subTask(msg);
+               }
+       }
+
+       // private void syncNode_old(Node sourceNode, Node targetParentNode)
+       // throws RepositoryException, SAXException {
+       //
+       // // enable cancelation of the current fetch process
+       // // FIXME insure the repository stays in a stable state
+       // if (monitor != null && monitor.isCanceled()) {
+       // updateMonitor("Fetched has been canceled, "
+       // + "process is terminating");
+       // return;
+       // }
+       //
+       // Boolean noRecurse = singleLevel(sourceNode);
+       // Calendar sourceLastModified = null;
+       // if (sourceNode.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
+       // sourceLastModified = sourceNode.getProperty(
+       // Property.JCR_LAST_MODIFIED).getDate();
+       // }
+       //
+       // if (sourceNode.getDefinition().isProtected())
+       // log.warn(sourceNode + " is protected.");
+       //
+       // if (!targetParentNode.hasNode(sourceNode.getName())) {
+       // String msg = "Adding " + sourceNode.getPath();
+       // updateMonitor(msg);
+       // if (log.isDebugEnabled())
+       // log.debug(msg);
+       // ContentHandler contentHandler = targetParentNode
+       // .getSession()
+       // .getWorkspace()
+       // .getImportContentHandler(targetParentNode.getPath(),
+       // ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
+       // sourceNode.getSession().exportSystemView(sourceNode.getPath(),
+       // contentHandler, false, noRecurse);
+       // } else {
+       // Node targetNode = targetParentNode.getNode(sourceNode.getName());
+       // if (sourceLastModified != null) {
+       // Calendar targetLastModified = null;
+       // if (targetNode.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
+       // targetLastModified = targetNode.getProperty(
+       // Property.JCR_LAST_MODIFIED).getDate();
+       // }
+       //
+       // if (targetLastModified == null
+       // || targetLastModified.before(sourceLastModified)) {
+       // String msg = "Updating " + targetNode.getPath();
+       // updateMonitor(msg);
+       // if (log.isDebugEnabled())
+       // log.debug(msg);
+       // ContentHandler contentHandler = targetParentNode
+       // .getSession()
+       // .getWorkspace()
+       // .getImportContentHandler(
+       // targetParentNode.getPath(),
+       // ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
+       // sourceNode.getSession().exportSystemView(
+       // sourceNode.getPath(), contentHandler, false,
+       // noRecurse);
+       // } else {
+       // String msg = "Skipped up to date " + targetNode.getPath();
+       // updateMonitor(msg);
+       // if (log.isDebugEnabled())
+       // log.debug(msg);
+       // return;
+       // }
+       // }
+       // }
+       //
+       // if (noRecurse) {
+       // // recurse
+       // Node targetNode = targetParentNode.getNode(sourceNode.getName());
+       // if (sourceLastModified != null) {
+       // Calendar zero = new GregorianCalendar();
+       // zero.setTimeInMillis(0);
+       // targetNode.setProperty(Property.JCR_LAST_MODIFIED, zero);
+       // targetNode.getSession().save();
+       // }
+       //
+       // for (NodeIterator it = sourceNode.getNodes(); it.hasNext();) {
+       // syncNode_old(it.nextNode(), targetNode);
+       // }
+       //
+       // if (sourceLastModified != null) {
+       // targetNode.setProperty(Property.JCR_LAST_MODIFIED,
+       // sourceLastModified);
+       // targetNode.getSession().save();
+       // }
+       // }
+       // }
+
+       protected Boolean singleLevel(Node sourceNode) throws RepositoryException {
+               if (sourceNode.isNodeType(NodeType.NT_FILE))
+                       return false;
+               return true;
+       }
+
+       /**
+        * Synchronises only one workspace, retrieved by name without changing its
+        * name.
+        */
+       public void setSourceWksp(String sourceWksp) {
+               if (sourceWksp != null && !sourceWksp.trim().equals("")) {
+                       Map<String, String> map = new HashMap<String, String>();
+                       map.put(sourceWksp, sourceWksp);
+                       setWkspMap(map);
+               }
+       }
+
+       /**
+        * Synchronises a map of workspaces that will be retrieved by name. If the
+        * target name is not defined (eg null or an empty string) for a given
+        * source workspace, we use the source name as target name.
+        */
+       public void setWkspMap(Map<String, String> workspaceMap) {
+               // clean the list to ease later use
+               this.workspaceMap = new HashMap<String, String>();
+               if (workspaceMap != null) {
+                       workspaceNames: for (String srcName : workspaceMap.keySet()) {
+                               String targetName = workspaceMap.get(srcName);
+
+                               // Sanity check
+                               if (srcName.trim().equals(""))
+                                       continue workspaceNames;
+                               if (targetName == null || "".equals(targetName.trim()))
+                                       targetName = srcName;
+                               this.workspaceMap.put(srcName, targetName);
+                       }
+               }
+               // clean the map to ease later use
+               if (this.workspaceMap.size() == 0)
+                       this.workspaceMap = null;
+       }
+
+       public void setMonitor(ArgeoMonitor monitor) {
+               this.monitor = monitor;
+       }
+
+       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
+               this.repositoryFactory = repositoryFactory;
+       }
+
+       public void setSourceRepoUri(String sourceRepoUri) {
+               this.sourceRepoUri = sourceRepoUri;
+       }
+
+       public void setSourceUsername(String sourceUsername) {
+               this.sourceUsername = sourceUsername;
+       }
+
+       public void setSourcePassword(char[] sourcePassword) {
+               this.sourcePassword = sourcePassword;
+       }
+
+       public void setTargetRepoUri(String targetRepoUri) {
+               this.targetRepoUri = targetRepoUri;
+       }
+
+       public void setTargetUsername(String targetUsername) {
+               this.targetUsername = targetUsername;
+       }
+
+       public void setTargetPassword(char[] targetPassword) {
+               this.targetPassword = targetPassword;
+       }
+
+       public void setSourceRepository(Repository sourceRepository) {
+               this.sourceRepository = sourceRepository;
+       }
+
+       public void setSourceCredentials(Credentials sourceCredentials) {
+               this.sourceCredentials = sourceCredentials;
+       }
+
+       public void setTargetRepository(Repository targetRepository) {
+               this.targetRepository = targetRepository;
+       }
+
+       public void setTargetCredentials(Credentials targetCredentials) {
+               this.targetCredentials = targetCredentials;
+       }
+
+       public void setFilesOnly(Boolean filesOnly) {
+               this.filesOnly = filesOnly;
+       }
+
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoUtils.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RepoUtils.java
new file mode 100644 (file)
index 0000000..4a175ac
--- /dev/null
@@ -0,0 +1,652 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarInputStream;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipInputStream;
+
+import javax.jcr.Credentials;
+import javax.jcr.GuestCredentials;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.RepositoryFactory;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.ArgeoTypes;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.ArtifactIdComparator;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.argeo.util.security.Keyring;
+import org.osgi.framework.Constants;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/** Utilities around repo */
+public class RepoUtils implements ArgeoNames, SlcNames {
+       private final static Log log = LogFactory.getLog(RepoUtils.class);
+
+       /** Packages a regular sources jar as PDE source. */
+       public static void packagesAsPdeSource(File sourceFile,
+                       NameVersion nameVersion, OutputStream out) throws IOException {
+               if (isAlreadyPdeSource(sourceFile)) {
+                       FileInputStream in = new FileInputStream(sourceFile);
+                       IOUtils.copy(in, out);
+                       IOUtils.closeQuietly(in);
+               } else {
+                       String sourceSymbolicName = nameVersion.getName() + ".source";
+
+                       Manifest sourceManifest = null;
+                       sourceManifest = new Manifest();
+                       sourceManifest.getMainAttributes().put(
+                                       Attributes.Name.MANIFEST_VERSION, "1.0");
+                       sourceManifest.getMainAttributes().putValue("Bundle-SymbolicName",
+                                       sourceSymbolicName);
+                       sourceManifest.getMainAttributes().putValue("Bundle-Version",
+                                       nameVersion.getVersion());
+                       sourceManifest.getMainAttributes().putValue(
+                                       "Eclipse-SourceBundle",
+                                       nameVersion.getName() + ";version="
+                                                       + nameVersion.getVersion());
+                       copyJar(sourceFile, out, sourceManifest);
+               }
+       }
+
+       public static byte[] packageAsPdeSource(InputStream sourceJar,
+                       NameVersion nameVersion) {
+               String sourceSymbolicName = nameVersion.getName() + ".source";
+
+               Manifest sourceManifest = null;
+               sourceManifest = new Manifest();
+               sourceManifest.getMainAttributes().put(
+                               Attributes.Name.MANIFEST_VERSION, "1.0");
+               sourceManifest.getMainAttributes().putValue("Bundle-SymbolicName",
+                               sourceSymbolicName);
+               sourceManifest.getMainAttributes().putValue("Bundle-Version",
+                               nameVersion.getVersion());
+               sourceManifest.getMainAttributes().putValue("Eclipse-SourceBundle",
+                               nameVersion.getName() + ";version=" + nameVersion.getVersion());
+
+               return modifyManifest(sourceJar, sourceManifest);
+       }
+
+       /**
+        * Check whether the file as already been packaged as PDE source, in order
+        * not to mess with Jar signing
+        */
+       private static boolean isAlreadyPdeSource(File sourceFile) {
+               JarInputStream jarInputStream = null;
+
+               try {
+                       jarInputStream = new JarInputStream(new FileInputStream(sourceFile));
+
+                       Manifest manifest = jarInputStream.getManifest();
+                       Iterator<?> it = manifest.getMainAttributes().keySet().iterator();
+                       boolean res = false;
+                       // containsKey() does not work, iterating...
+                       while (it.hasNext())
+                               if (it.next().toString().equals("Eclipse-SourceBundle")) {
+                                       res = true;
+                                       break;
+                               }
+                       // boolean res = manifest.getMainAttributes().get(
+                       // "Eclipse-SourceBundle") != null;
+                       if (res)
+                               log.info(sourceFile + " is already a PDE source");
+                       return res;
+               } catch (Exception e) {
+                       // probably not a jar, skipping
+                       if (log.isDebugEnabled())
+                               log.debug("Skipping " + sourceFile + " because of "
+                                               + e.getMessage());
+                       return false;
+               } finally {
+                       IOUtils.closeQuietly(jarInputStream);
+               }
+       }
+
+       /**
+        * Copy a jar, replacing its manifest with the provided one
+        * 
+        * @param manifest
+        *            can be null
+        */
+       private static void copyJar(File source, OutputStream out, Manifest manifest)
+                       throws IOException {
+               JarFile sourceJar = null;
+               JarOutputStream output = null;
+               try {
+                       output = manifest != null ? new JarOutputStream(out, manifest)
+                                       : new JarOutputStream(out);
+                       sourceJar = new JarFile(source);
+
+                       entries: for (Enumeration<?> entries = sourceJar.entries(); entries
+                                       .hasMoreElements();) {
+                               JarEntry entry = (JarEntry) entries.nextElement();
+                               if (manifest != null
+                                               && entry.getName().equals("META-INF/MANIFEST.MF"))
+                                       continue entries;
+
+                               InputStream entryStream = sourceJar.getInputStream(entry);
+                               JarEntry newEntry = new JarEntry(entry.getName());
+                               // newEntry.setMethod(JarEntry.DEFLATED);
+                               output.putNextEntry(newEntry);
+                               IOUtils.copy(entryStream, output);
+                       }
+               } finally {
+                       IOUtils.closeQuietly(output);
+                       try {
+                               if (sourceJar != null)
+                                       sourceJar.close();
+                       } catch (IOException e) {
+                               // silent
+                       }
+               }
+       }
+
+       /** Copy a jar changing onlythe manifest */
+       public static void copyJar(InputStream in, OutputStream out,
+                       Manifest manifest) {
+               JarInputStream jarIn = null;
+               JarOutputStream jarOut = null;
+               try {
+                       jarIn = new JarInputStream(in);
+                       jarOut = new JarOutputStream(out, manifest);
+                       JarEntry jarEntry = null;
+                       while ((jarEntry = jarIn.getNextJarEntry()) != null) {
+                               if (!jarEntry.getName().equals("META-INF/MANIFEST.MF")) {
+                                       JarEntry newJarEntry = new JarEntry(jarEntry.getName());
+                                       jarOut.putNextEntry(newJarEntry);
+                                       IOUtils.copy(jarIn, jarOut);
+                                       jarIn.closeEntry();
+                                       jarOut.closeEntry();
+                               }
+                       }
+               } catch (IOException e) {
+                       throw new SlcException("Could not copy jar with MANIFEST "
+                                       + manifest.getMainAttributes(), e);
+               } finally {
+                       if (!(in instanceof ZipInputStream))
+                               IOUtils.closeQuietly(jarIn);
+                       IOUtils.closeQuietly(jarOut);
+               }
+       }
+
+       /** Reads a jar file, modify its manifest */
+       public static byte[] modifyManifest(InputStream in, Manifest manifest) {
+               ByteArrayOutputStream out = new ByteArrayOutputStream(200 * 1024);
+               try {
+                       copyJar(in, out, manifest);
+                       return out.toByteArray();
+               } finally {
+                       IOUtils.closeQuietly(out);
+               }
+       }
+
+       /** Read the OSGi {@link NameVersion} */
+       public static NameVersion readNameVersion(Artifact artifact) {
+               File artifactFile = artifact.getFile();
+               if (artifact.getExtension().equals("pom")) {
+                       // hack to process jars which weirdly appear as POMs
+                       File jarFile = new File(artifactFile.getParentFile(),
+                                       FilenameUtils.getBaseName(artifactFile.getPath()) + ".jar");
+                       if (jarFile.exists()) {
+                               log.warn("Use " + jarFile + " instead of " + artifactFile
+                                               + " for " + artifact);
+                               artifactFile = jarFile;
+                       }
+               }
+               return readNameVersion(artifactFile);
+       }
+
+       /** Read the OSGi {@link NameVersion} */
+       public static NameVersion readNameVersion(File artifactFile) {
+               try {
+                       return readNameVersion(new FileInputStream(artifactFile));
+               } catch (Exception e) {
+                       // probably not a jar, skipping
+                       if (log.isDebugEnabled()) {
+                               log.debug("Skipping " + artifactFile + " because of " + e);
+                               // e.printStackTrace();
+                       }
+               }
+               return null;
+       }
+
+       /** Read the OSGi {@link NameVersion} */
+       public static NameVersion readNameVersion(InputStream in) {
+               JarInputStream jarInputStream = null;
+               try {
+                       jarInputStream = new JarInputStream(in);
+                       return readNameVersion(jarInputStream.getManifest());
+               } catch (Exception e) {
+                       // probably not a jar, skipping
+                       if (log.isDebugEnabled()) {
+                               log.debug("Skipping because of " + e);
+                               e.printStackTrace();
+                       }
+               } finally {
+                       IOUtils.closeQuietly(jarInputStream);
+               }
+               return null;
+       }
+
+       /** Read the OSGi {@link NameVersion} */
+       public static NameVersion readNameVersion(Manifest manifest) {
+               DefaultNameVersion nameVersion = new DefaultNameVersion();
+               nameVersion.setName(manifest.getMainAttributes().getValue(
+                               Constants.BUNDLE_SYMBOLICNAME));
+
+               // Skip additional specs such as
+               // ; singleton:=true
+               if (nameVersion.getName().indexOf(';') > -1) {
+                       nameVersion
+                                       .setName(new StringTokenizer(nameVersion.getName(), " ;")
+                                                       .nextToken());
+               }
+
+               nameVersion.setVersion(manifest.getMainAttributes().getValue(
+                               Constants.BUNDLE_VERSION));
+
+               return nameVersion;
+       }
+
+       /*
+        * DATA MODEL
+        */
+       /** The artifact described by this node */
+       public static Artifact asArtifact(Node node) throws RepositoryException {
+               if (node.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
+                       // FIXME update data model to store packaging at this level
+                       String extension = "jar";
+                       return new DefaultArtifact(node.getProperty(SLC_GROUP_ID)
+                                       .getString(),
+                                       node.getProperty(SLC_ARTIFACT_ID).getString(), extension,
+                                       node.getProperty(SLC_ARTIFACT_VERSION).getString());
+               } else if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
+                       return new DefaultArtifact(node.getProperty(SLC_GROUP_ID)
+                                       .getString(),
+                                       node.getProperty(SLC_ARTIFACT_ID).getString(), node
+                                                       .getProperty(SLC_ARTIFACT_CLASSIFIER).getString(),
+                                       node.getProperty(SLC_ARTIFACT_EXTENSION).getString(), node
+                                                       .getProperty(SLC_ARTIFACT_VERSION).getString());
+               } else if (node.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
+                       return new DefaultArtifact(node.getProperty(SLC_CATEGORY)
+                                       .getString(), node.getProperty(SLC_NAME).getString(),
+                                       "jar", node.getProperty(SLC_VERSION).getString());
+               } else {
+                       throw new SlcException("Unsupported node type for " + node);
+               }
+       }
+
+       /**
+        * The path to the PDE source related to this artifact (or artifact version
+        * base). There may or there may not be a node at this location (the
+        * returned path will typically be used to test whether PDE sources are
+        * attached to this artifact).
+        */
+       public static String relatedPdeSourcePath(String artifactBasePath,
+                       Node artifactNode) throws RepositoryException {
+               Artifact artifact = asArtifact(artifactNode);
+               Artifact pdeSourceArtifact = new DefaultArtifact(artifact.getGroupId(),
+                               artifact.getArtifactId() + ".source", artifact.getExtension(),
+                               artifact.getVersion());
+               return MavenConventionsUtils.artifactPath(artifactBasePath,
+                               pdeSourceArtifact);
+       }
+
+       /**
+        * Copy this bytes array as an artifact, relative to the root of the
+        * repository (typically the workspace root node)
+        */
+       public static Node copyBytesAsArtifact(Node artifactsBase,
+                       Artifact artifact, byte[] bytes) throws RepositoryException {
+               String parentPath = MavenConventionsUtils.artifactParentPath(
+                               artifactsBase.getPath(), artifact);
+               Node folderNode = JcrUtils.mkfolders(artifactsBase.getSession(),
+                               parentPath);
+               return JcrUtils.copyBytesAsFile(folderNode,
+                               MavenConventionsUtils.artifactFileName(artifact), bytes);
+       }
+
+       private RepoUtils() {
+       }
+
+       /** If a source return the base bundle name, does not change otherwise */
+       public static String extractBundleNameFromSourceName(String sourceBundleName) {
+               if (sourceBundleName.endsWith(".source"))
+                       return sourceBundleName.substring(0, sourceBundleName.length()
+                                       - ".source".length());
+               else
+                       return sourceBundleName;
+       }
+
+       /*
+        * SOFTWARE REPOSITORIES
+        */
+
+       /** Retrieve repository based on information in the repo node */
+       public static Repository getRepository(RepositoryFactory repositoryFactory,
+                       Keyring keyring, Node repoNode) {
+               try {
+                       Repository repository;
+                       if (repoNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
+                               String uri = repoNode.getProperty(ARGEO_URI).getString();
+                               if (uri.startsWith("http")) {// http, https
+                                       repository = ArgeoJcrUtils.getRepositoryByUri(
+                                                       repositoryFactory, uri);
+                               } else if (uri.startsWith("vm:")) {// alias
+                                       repository = ArgeoJcrUtils.getRepositoryByUri(
+                                                       repositoryFactory, uri);
+                               } else {
+                                       throw new SlcException("Unsupported repository uri " + uri);
+                               }
+                               return repository;
+                       } else {
+                               throw new SlcException("Unsupported node type " + repoNode);
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot connect to repository " + repoNode,
+                                       e);
+               }
+       }
+
+       /**
+        * Reads credentials from node, using keyring if there is a password. Can
+        * return null if no credentials needed (local repo) at all, but returns
+        * {@link GuestCredentials} if user id is 'anonymous' .
+        */
+       public static Credentials getRepositoryCredentials(Keyring keyring,
+                       Node repoNode) {
+               try {
+                       if (repoNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
+                               if (!repoNode.hasProperty(ARGEO_USER_ID))
+                                       return null;
+
+                               String userId = repoNode.getProperty(ARGEO_USER_ID).getString();
+                               if (userId.equals("anonymous"))// FIXME hardcoded userId
+                                       return new GuestCredentials();
+                               char[] password = keyring.getAsChars(repoNode.getPath() + '/'
+                                               + ARGEO_PASSWORD);
+                               Credentials credentials = new SimpleCredentials(userId,
+                                               password);
+                               return credentials;
+                       } else {
+                               throw new SlcException("Unsupported node type " + repoNode);
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot connect to repository " + repoNode,
+                                       e);
+               }
+       }
+
+       /**
+        * Shortcut to retrieve a session given variable information: Handle the
+        * case where we only have an URI of the repository, that we want to connect
+        * as anonymous or the case of a identified connection to a local or remote
+        * repository.
+        * 
+        * Callers must close the session once it has been used
+        */
+       public static Session getRemoteSession(RepositoryFactory repositoryFactory,
+                       Keyring keyring, Node repoNode, String uri, String workspaceName) {
+               try {
+                       if (repoNode == null && uri == null)
+                               throw new SlcException(
+                                               "At least one of repoNode and uri must be defined");
+                       Repository currRepo = null;
+                       Credentials credentials = null;
+                       // Anonymous URI only workspace
+                       if (repoNode == null)
+                               // Anonymous
+                               currRepo = ArgeoJcrUtils.getRepositoryByUri(repositoryFactory,
+                                               uri);
+                       else {
+                               currRepo = RepoUtils.getRepository(repositoryFactory, keyring,
+                                               repoNode);
+                               credentials = RepoUtils.getRepositoryCredentials(keyring,
+                                               repoNode);
+                       }
+                       return currRepo.login(credentials, workspaceName);
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot connect to workspace "
+                                       + workspaceName + " of repository " + repoNode
+                                       + " with URI " + uri, e);
+               }
+       }
+
+       /**
+        * Shortcut to retrieve a session on a remote Jrc Repository from
+        * information stored in a local argeo node or from an URI: Handle the case
+        * where we only have an URI of the repository, that we want to connect as
+        * anonymous or the case of a identified connection to a local or remote
+        * repository.
+        * 
+        * Callers must close the session once it has been used
+        */
+       public static Session getRemoteSession(RepositoryFactory repositoryFactory,
+                       Keyring keyring, Repository localRepository, String repoNodePath,
+                       String uri, String workspaceName) {
+               Session localSession = null;
+               Node repoNode = null;
+               try {
+                       localSession = localRepository.login();
+                       if (repoNodePath != null && localSession.nodeExists(repoNodePath))
+                               repoNode = localSession.getNode(repoNodePath);
+
+                       return RepoUtils.getRemoteSession(repositoryFactory, keyring,
+                                       repoNode, uri, workspaceName);
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot log to workspace " + workspaceName
+                                       + " for repo defined in " + repoNodePath, e);
+               } finally {
+                       JcrUtils.logoutQuietly(localSession);
+               }
+       }
+
+       /**
+        * Write group indexes: 'binaries' lists all bundles and their versions,
+        * 'sources' list their sources, and 'sdk' aggregates both.
+        */
+       public static void writeGroupIndexes(Session session,
+                       String artifactBasePath, String groupId, String version,
+                       Set<Artifact> binaries, Set<Artifact> sources) {
+               try {
+                       Set<Artifact> indexes = new TreeSet<Artifact>(
+                                       new ArtifactIdComparator());
+                       Artifact binariesArtifact = writeIndex(session, artifactBasePath,
+                                       groupId, RepoConstants.BINARIES_ARTIFACT_ID, version,
+                                       binaries);
+                       indexes.add(binariesArtifact);
+                       if (sources != null) {
+                               Artifact sourcesArtifact = writeIndex(session,
+                                               artifactBasePath, groupId,
+                                               RepoConstants.SOURCES_ARTIFACT_ID, version, sources);
+                               indexes.add(sourcesArtifact);
+                       }
+                       // sdk
+                       writeIndex(session, artifactBasePath, groupId,
+                                       RepoConstants.SDK_ARTIFACT_ID, version, indexes);
+                       session.save();
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot write indexes for group " + groupId,
+                                       e);
+               }
+       }
+
+       /** Write a group index. */
+       private static Artifact writeIndex(Session session,
+                       String artifactBasePath, String groupId, String artifactId,
+                       String version, Set<Artifact> artifacts) throws RepositoryException {
+               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
+                               version);
+               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
+                               artifacts, null);
+               Node node = RepoUtils.copyBytesAsArtifact(
+                               session.getNode(artifactBasePath), artifact, pom.getBytes());
+               addMavenChecksums(node);
+               return artifact;
+       }
+
+       /** Add files containing the SHA-1 and MD5 checksums. */
+       public static void addMavenChecksums(Node node) throws RepositoryException {
+               // TODO optimize
+               String sha = JcrUtils.checksumFile(node, "SHA-1");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
+                               sha.getBytes());
+               String md5 = JcrUtils.checksumFile(node, "MD5");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
+                               md5.getBytes());
+       }
+
+       /**
+        * Custom copy since the one in commons does not fit the needs when copying
+        * a workspace completely.
+        */
+       public static void copy(Node fromNode, Node toNode) {
+               copy(fromNode, toNode, null);
+       }
+
+       public static void copy(Node fromNode, Node toNode, ArgeoMonitor monitor) {
+               try {
+                       String fromPath = fromNode.getPath();
+                       if (monitor != null)
+                               monitor.subTask("copying node :" + fromPath);
+                       if (log.isDebugEnabled())
+                               log.debug("copy node :" + fromPath);
+
+                       // FIXME : small hack to enable specific workspace copy
+                       if (fromNode.isNodeType("rep:ACL")
+                                       || fromNode.isNodeType("rep:system")) {
+                               if (log.isTraceEnabled())
+                                       log.trace("node " + fromNode + " skipped");
+                               return;
+                       }
+
+                       // add mixins
+                       for (NodeType mixinType : fromNode.getMixinNodeTypes()) {
+                               toNode.addMixin(mixinType.getName());
+                       }
+
+                       // Double check
+                       for (NodeType mixinType : toNode.getMixinNodeTypes()) {
+                               if (log.isDebugEnabled())
+                                       log.debug(mixinType.getName());
+                       }
+
+                       // process properties
+                       PropertyIterator pit = fromNode.getProperties();
+                       properties: while (pit.hasNext()) {
+                               Property fromProperty = pit.nextProperty();
+                               String propName = fromProperty.getName();
+                               try {
+                                       String propertyName = fromProperty.getName();
+                                       if (toNode.hasProperty(propertyName)
+                                                       && toNode.getProperty(propertyName).getDefinition()
+                                                                       .isProtected())
+                                               continue properties;
+
+                                       if (fromProperty.getDefinition().isProtected())
+                                               continue properties;
+
+                                       if (propertyName.equals("jcr:created")
+                                                       || propertyName.equals("jcr:createdBy")
+                                                       || propertyName.equals("jcr:lastModified")
+                                                       || propertyName.equals("jcr:lastModifiedBy"))
+                                               continue properties;
+
+                                       if (fromProperty.isMultiple()) {
+                                               toNode.setProperty(propertyName,
+                                                               fromProperty.getValues());
+                                       } else {
+                                               toNode.setProperty(propertyName,
+                                                               fromProperty.getValue());
+                                       }
+                               } catch (RepositoryException e) {
+                                       throw new SlcException("Cannot property " + propName, e);
+                               }
+                       }
+
+                       // recursively process children nodes
+                       NodeIterator nit = fromNode.getNodes();
+                       while (nit.hasNext()) {
+                               Node fromChild = nit.nextNode();
+                               Integer index = fromChild.getIndex();
+                               String nodeRelPath = fromChild.getName() + "[" + index + "]";
+                               Node toChild;
+                               if (toNode.hasNode(nodeRelPath))
+                                       toChild = toNode.getNode(nodeRelPath);
+                               else
+                                       toChild = toNode.addNode(fromChild.getName(), fromChild
+                                                       .getPrimaryNodeType().getName());
+                               copy(fromChild, toChild);
+                       }
+
+                       // update jcr:lastModified and jcr:lastModifiedBy in toNode in
+                       // case
+                       // they existed
+                       if (!toNode.getDefinition().isProtected()
+                                       && toNode.isNodeType(NodeType.MIX_LAST_MODIFIED))
+                               JcrUtils.updateLastModified(toNode);
+
+                       // Workaround to reduce session size: artifact is a saveable
+                       // unity
+                       if (toNode.isNodeType(SlcTypes.SLC_ARTIFACT))
+                               toNode.getSession().save();
+
+                       if (monitor != null)
+                               monitor.worked(1);
+
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot copy " + fromNode + " to " + toNode,
+                                       e);
+               }
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RpmIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RpmIndexer.java
new file mode 100644 (file)
index 0000000..57b93b8
--- /dev/null
@@ -0,0 +1,116 @@
+package org.argeo.slc.repo;
+
+import static org.freecompany.redline.header.Header.HeaderTag.HEADERIMMUTABLE;
+import static org.freecompany.redline.header.Signature.SignatureTag.SIGNATURES;
+
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.freecompany.redline.ChannelWrapper.Key;
+import org.freecompany.redline.ReadableChannelWrapper;
+import org.freecompany.redline.header.AbstractHeader;
+import org.freecompany.redline.header.Format;
+import org.freecompany.redline.header.Header;
+
+/** Indexes an RPM file. */
+public class RpmIndexer implements NodeIndexer, SlcNames {
+       private Boolean force = false;
+
+       @Override
+       public Boolean support(String path) {
+               return FilenameUtils.getExtension(path).equals("rpm");
+       }
+
+       @Override
+       public void index(Node node) {
+               try {
+                       if (!support(node.getPath()))
+                               return;
+
+                       // Already indexed
+                       if (!force && node.isNodeType(SlcTypes.SLC_RPM))
+                               return;
+
+                       if (!node.isNodeType(NodeType.NT_FILE))
+                               return;
+
+                       InputStream in = node.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
+                       ReadableChannelWrapper channel = new ReadableChannelWrapper(
+                                       Channels.newChannel(in));
+                       Format format = readRpmInfo(channel);
+
+                       node.addMixin(SlcTypes.SLC_RPM);
+                       node.setProperty(SLC_NAME, readTag(format, Header.HeaderTag.NAME));
+                       String rpmVersion = readTag(format, Header.HeaderTag.VERSION);
+                       String rpmRelease = readTag(format, Header.HeaderTag.RELEASE);
+                       node.setProperty(SLC_RPM_VERSION, rpmVersion);
+                       node.setProperty(SLC_RPM_RELEASE, rpmRelease);
+                       node.setProperty(SLC_VERSION, rpmVersion + "-" + rpmRelease);
+
+                       String arch = readTag(format, Header.HeaderTag.ARCH);
+                       if (arch != null)
+                               node.setProperty(SLC_RPM_ARCH, arch);
+
+                       String archiveSize = readTag(format, Header.HeaderTag.ARCHIVESIZE);
+                       if (archiveSize != null)
+                               node.setProperty(SLC_RPM_ARCHIVE_SIZE,
+                                               Long.parseLong(archiveSize));
+
+                       node.getSession().save();
+               } catch (Exception e) {
+                       throw new SlcException("Cannot index " + node, e);
+               }
+
+       }
+
+       @SuppressWarnings("unused")
+       public Format readRpmInfo(ReadableChannelWrapper channel) throws Exception {
+               Format format = new Format();
+
+               Key<Integer> lead = channel.start();
+               format.getLead().read(channel);
+               // System.out.println( "Lead ended at '" + in.finish( lead) + "'.");
+
+               Key<Integer> signature = channel.start();
+               int count = format.getSignature().read(channel);
+               int expected = ByteBuffer
+                               .wrap((byte[]) format.getSignature().getEntry(SIGNATURES)
+                                               .getValues(), 8, 4).getInt()
+                               / -16;
+               // System.out.println( "Signature ended at '" + in.finish( signature) +
+               // "' and contained '" + count + "' headers (expected '" + expected +
+               // "').");
+
+               Key<Integer> header = channel.start();
+               count = format.getHeader().read(channel);
+               expected = ByteBuffer.wrap(
+                               (byte[]) format.getHeader().getEntry(HEADERIMMUTABLE)
+                                               .getValues(), 8, 4).getInt()
+                               / -16;
+               // System.out.println( "Header ended at '" + in.finish( header) +
+               // " and contained '" + count + "' headers (expected '" + expected +
+               // "').");
+
+               return format;
+       }
+
+       private String readTag(Format format, Header.HeaderTag tag) {
+               AbstractHeader.Entry<?> entry = format.getHeader().getEntry(tag);
+               if (entry == null)
+                       return null;
+               if (entry.getValues() == null)
+                       return null;
+               Object[] values = (Object[]) entry.getValues();
+               return values[0].toString().trim();
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/RpmRepoManager.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/RpmRepoManager.java
new file mode 100644 (file)
index 0000000..7535468
--- /dev/null
@@ -0,0 +1,5 @@
+package org.argeo.slc.repo;
+
+public interface RpmRepoManager {
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/SlcRepoManager.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/SlcRepoManager.java
new file mode 100644 (file)
index 0000000..a0ba8e0
--- /dev/null
@@ -0,0 +1,10 @@
+package org.argeo.slc.repo;
+
+/** Coordinator of the various type of repository (Java, RPM, etc.) */
+public interface SlcRepoManager {
+       /** @return null if Java not supported. */
+       public JavaRepoManager getJavaRepoManager();
+
+       /** @return null if RPM not supported. */
+       public RpmRepoManager getRpmRepoManager();
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/AbstractJcrRepoManager.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/AbstractJcrRepoManager.java
new file mode 100644 (file)
index 0000000..4bdda83
--- /dev/null
@@ -0,0 +1,106 @@
+package org.argeo.slc.repo.core;
+
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import javax.jcr.NoSuchWorkspaceException;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcConstants;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.NodeIndexer;
+
+/** Generic operations on a JCR-based repo. */
+abstract class AbstractJcrRepoManager {
+       private final static Log log = LogFactory
+                       .getLog(AbstractJcrRepoManager.class);
+       private String securityWorkspace = "security";
+
+       private Repository jcrRepository;
+       private Session adminSession;
+       private List<NodeIndexer> nodeIndexers;
+
+       // registries
+       private Map<String, Session> workspaceSessions = new TreeMap<String, Session>();
+       private Map<String, WorkspaceIndexer> workspaceIndexers = new TreeMap<String, WorkspaceIndexer>();
+
+       public void init() {
+               try {
+                       adminSession = jcrRepository.login();
+                       String[] workspaceNames = adminSession.getWorkspace()
+                                       .getAccessibleWorkspaceNames();
+                       for (String workspaceName : workspaceNames) {
+                               if (workspaceName.equals(securityWorkspace))
+                                       continue;
+                               if (workspaceName.equals(adminSession.getWorkspace().getName()))
+                                       continue;
+                               workspaceInit(workspaceName);
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot initialize repo manager", e);
+               }
+       }
+
+       public void destroy() {
+               for (String key : workspaceIndexers.keySet()) {
+                       workspaceIndexers.get(key).close();
+               }
+
+               for (String key : workspaceSessions.keySet()) {
+                       JcrUtils.logoutQuietly(workspaceSessions.get(key));
+               }
+               JcrUtils.logoutQuietly(adminSession);
+       }
+
+       public void createWorkspace(String workspaceName) {
+               try {
+                       try {
+                               jcrRepository.login(workspaceName);
+                               throw new SlcException("Workspace " + workspaceName
+                                               + " exists already.");
+                       } catch (NoSuchWorkspaceException e) {
+                               // try to create workspace
+                               adminSession.getWorkspace().createWorkspace(workspaceName);
+                               workspaceInit(workspaceName);
+                       }
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot create workspace " + workspaceName,
+                                       e);
+               }
+       }
+
+       protected void workspaceInit(String workspaceName) {
+               Session workspaceAdminSession = null;
+               try {
+                       workspaceAdminSession = jcrRepository.login(workspaceName);
+                       workspaceSessions.put(workspaceName, adminSession);
+                       JcrUtils.addPrivilege(workspaceAdminSession, "/",
+                                       SlcConstants.ROLE_SLC, "jcr:all");
+                       WorkspaceIndexer workspaceIndexer = new WorkspaceIndexer(
+                                       workspaceAdminSession, nodeIndexers);
+                       workspaceIndexers.put(workspaceName, workspaceIndexer);
+               } catch (RepositoryException e) {
+                       log.error("Cannot initialize workspace " + workspaceName, e);
+               } finally {
+                       JcrUtils.logoutQuietly(workspaceAdminSession);
+               }
+       }
+
+       public void setJcrRepository(Repository jcrRepository) {
+               this.jcrRepository = jcrRepository;
+       }
+
+       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
+               this.nodeIndexers = nodeIndexers;
+       }
+
+       public void setSecurityWorkspace(String securityWorkspace) {
+               this.securityWorkspace = securityWorkspace;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/JavaRepoManagerImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/JavaRepoManagerImpl.java
new file mode 100644 (file)
index 0000000..dfd0c8a
--- /dev/null
@@ -0,0 +1,8 @@
+package org.argeo.slc.repo.core;
+
+import org.argeo.slc.repo.JavaRepoManager;
+
+/** Java-specific operations */
+public class JavaRepoManagerImpl extends AbstractJcrRepoManager implements
+               JavaRepoManager {
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/RepoServiceImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/RepoServiceImpl.java
new file mode 100644 (file)
index 0000000..45ea83a
--- /dev/null
@@ -0,0 +1,43 @@
+package org.argeo.slc.repo.core;
+
+import javax.jcr.Repository;
+import javax.jcr.RepositoryFactory;
+import javax.jcr.Session;
+
+import org.argeo.slc.repo.RepoService;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+
+/**
+ * Work in Progress - enhance this. First implementation of a service that
+ * centralizes session management in an argeo SLC context, repositories are
+ * either defined using an URI and a workspace name in a anonymous context or
+ * using connection information that are store in a corresponding node in the
+ * local repository home
+ */
+public class RepoServiceImpl implements RepoService {
+
+       /* DEPENDENCY INJECTION */
+       private Repository nodeRepository;
+       private RepositoryFactory repositoryFactory;
+       private Keyring keyring;
+
+       public Session getRemoteSession(String repoNodePath, String uri,
+                       String workspaceName) {
+               return RepoUtils.getRemoteSession(repositoryFactory, keyring,
+                               nodeRepository, repoNodePath, uri, workspaceName);
+       }
+
+       /* DEPENDENCY INJECTION */
+       public void setNodeRepository(Repository nodeRepository) {
+               this.nodeRepository = nodeRepository;
+       }
+
+       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
+               this.repositoryFactory = repositoryFactory;
+       }
+
+       public void setKeyring(Keyring keyring) {
+               this.keyring = keyring;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/RpmRepoManagerImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/RpmRepoManagerImpl.java
new file mode 100644 (file)
index 0000000..6e83523
--- /dev/null
@@ -0,0 +1,8 @@
+package org.argeo.slc.repo.core;
+
+import org.argeo.slc.repo.RpmRepoManager;
+
+/** RPM-specific operations */
+public class RpmRepoManagerImpl extends AbstractJcrRepoManager implements
+               RpmRepoManager {
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/SlcRepoManagerImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/SlcRepoManagerImpl.java
new file mode 100644 (file)
index 0000000..bce6f03
--- /dev/null
@@ -0,0 +1,38 @@
+package org.argeo.slc.repo.core;
+
+import org.argeo.slc.repo.JavaRepoManager;
+import org.argeo.slc.repo.RpmRepoManager;
+import org.argeo.slc.repo.SlcRepoManager;
+
+/** Coordinator of the various repositories. */
+public class SlcRepoManagerImpl implements SlcRepoManager {
+       private JavaRepoManager javaRepoManager;
+       private RpmRepoManager rpmRepoManager;
+
+       public void init() {
+
+       }
+
+       public void destroy() {
+
+       }
+
+       @Override
+       public JavaRepoManager getJavaRepoManager() {
+               return javaRepoManager;
+       }
+
+       public void setJavaRepoManager(JavaRepoManager javaRepoManager) {
+               this.javaRepoManager = javaRepoManager;
+       }
+
+       @Override
+       public RpmRepoManager getRpmRepoManager() {
+               return rpmRepoManager;
+       }
+
+       public void setRpmRepoManager(RpmRepoManager rpmRepoManager) {
+               this.rpmRepoManager = rpmRepoManager;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/core/WorkspaceIndexer.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/core/WorkspaceIndexer.java
new file mode 100644 (file)
index 0000000..e5622aa
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.core;
+
+import java.util.List;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.observation.Event;
+import javax.jcr.observation.EventIterator;
+import javax.jcr.observation.EventListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.NodeIndexer;
+
+/** Maintains the metadata of a workspace, using listeners */
+public class WorkspaceIndexer {
+       private final static Log log = LogFactory.getLog(WorkspaceIndexer.class);
+
+       private final Session adminSession;
+       private IndexingListener artifactListener;
+       /** order may be important */
+       private final List<NodeIndexer> nodeIndexers;
+
+       public WorkspaceIndexer(Session adminSession, List<NodeIndexer> nodeIndexers) {
+               this.adminSession = adminSession;
+               this.nodeIndexers = nodeIndexers;
+               try {
+                       artifactListener = new IndexingListener();
+                       adminSession
+                                       .getWorkspace()
+                                       .getObservationManager()
+                                       .addEventListener(artifactListener, Event.NODE_ADDED, "/",
+                                                       true, null, null, true);
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot initialize repository backend", e);
+               }
+       }
+
+       public void close() {
+               try {
+                       adminSession.getWorkspace().getObservationManager()
+                                       .removeEventListener(artifactListener);
+               } catch (RepositoryException e) {
+                       log.error("Cannot close workspace indexer "
+                                       + adminSession.getWorkspace().getName(), e);
+               }
+       }
+
+       class IndexingListener implements EventListener {
+
+               public void onEvent(EventIterator events) {
+                       while (events.hasNext()) {
+                               Event event = events.nextEvent();
+                               try {
+                                       String newNodePath = event.getPath();
+                                       Node newNode = null;
+                                       for (NodeIndexer nodeIndexer : nodeIndexers) {
+                                               try {
+                                                       if (nodeIndexer.support(newNodePath)) {
+                                                               if (newNode == null)
+                                                                       newNode = adminSession.getNode(newNodePath);
+                                                               nodeIndexer.index(newNode);
+                                                       }
+                                               } catch (RuntimeException e) {
+                                                       e.printStackTrace();
+                                                       throw e;
+                                               }
+                                       }
+                                       if (newNode != null)
+                                               adminSession.save();
+                               } catch (RepositoryException e) {
+                                       throw new SlcException("Cannot process event " + event, e);
+                               } finally {
+                                       JcrUtils.discardQuietly(adminSession);
+                               }
+                       }
+               }
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/apache-2.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/apache-2.0.txt
new file mode 100644 (file)
index 0000000..d645695
--- /dev/null
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed 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.
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/bsd-3-clause.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/bsd-3-clause.txt
new file mode 100644 (file)
index 0000000..ed0116e
--- /dev/null
@@ -0,0 +1,12 @@
+Copyright (c) <YEAR>, <OWNER>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/cddl-1.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/cddl-1.0.txt
new file mode 100644 (file)
index 0000000..9dc4442
--- /dev/null
@@ -0,0 +1,93 @@
+ COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 1.
+
+Definitions.
+
+1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications.
+
+1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
+
+1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
+
+1.4. Executable means the Covered Software in any form other than Source Code.
+
+1.5. Initial Developer means the individual or entity that first makes Original Software available under this License.
+
+1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
+
+1.7. License means this document.
+
+1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
+
+1.9. Modifications means the Source Code and Executable form of any of the following: A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; B. Any new file that contains any part of the Original Software or previous Modification; or C. Any new file that is contributed or otherwise made available under the terms of this License.
+
+1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License.
+
+1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
+
+1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
+
+1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
+
+2. License Grants.
+
+ 2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
+
+(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof);
+
+ (c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License;
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices.
+
+2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
+
+(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
+
+(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
+
+(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
+
+3. Distribution Obligations.
+
+3.1. Availability of Source Code. Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
+
+3.2. Modifications. The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
+
+3.3. Required Notices. You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
+
+3.4. Application of Additional Terms. You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
+
+3.5. Distribution of Executable Versions. You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
+
+3.6. Larger Works. You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
+
+4. Versions of the License.
+
+4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
+
+4.2. Effect of New Versions. You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
+
+4.3. Modified Versions. When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License.
+
+5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+6. TERMINATION.
+
+6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
+
+6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
+
+6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
+
+7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+8. U.S. GOVERNMENT END USERS. The Covered Software is a commercial item, as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R.  252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
+
+9. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
+
+10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
+
+NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) The code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California. 
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/epl-1.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/epl-1.0.txt
new file mode 100644 (file)
index 0000000..795c0c3
--- /dev/null
@@ -0,0 +1,73 @@
+ THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
+
+1. DEFINITIONS
+
+"Contribution" means:
+
+    a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
+    b) in the case of each subsequent Contributor:
+    i) changes to the Program, and
+    ii) additions to the Program; 
+
+where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
+
+"Contributor" means any person or entity that distributes the Program.
+
+"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
+
+"Program" means the Contributions distributed in accordance with this Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
+
+2. GRANT OF RIGHTS
+
+    a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
+    b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
+    c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
+    d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 
+
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
+
+    a) it complies with the terms and conditions of this Agreement; and
+    b) its license agreement:
+    i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
+    ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
+    iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
+    iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 
+
+When the Program is made available in source code form:
+
+    a) it must be made available under this Agreement; and
+    b) a copy of this Agreement must be included with each copy of the Program. 
+
+Contributors may not remove or alter any copyright notices contained within the Program.
+
+Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
+
+This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-2.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-2.0.txt
new file mode 100644 (file)
index 0000000..d159169
--- /dev/null
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-3.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/gpl-3.0.txt
new file mode 100644 (file)
index 0000000..94a9ed0
--- /dev/null
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-2.1.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-2.1.txt
new file mode 100644 (file)
index 0000000..4362b49
--- /dev/null
@@ -0,0 +1,502 @@
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+                  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                            NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-3.0.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/lgpl-3.0.txt
new file mode 100644 (file)
index 0000000..65c5ca8
--- /dev/null
@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/license/mit.txt b/org.argeo.slc.repo/src/org/argeo/slc/repo/license/mit.txt
new file mode 100644 (file)
index 0000000..e14c371
--- /dev/null
@@ -0,0 +1,17 @@
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ConvertPoms_01_03.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ConvertPoms_01_03.java
new file mode 100644 (file)
index 0000000..12cf490
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.io.File;
+import java.util.HashMap;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/** Recursively migrate all the POMs to Argeo Distribution v1.3 */
+public class ConvertPoms_01_03 implements Runnable {
+       final String SPRING_SOURCE_PREFIX = "com.springsource";
+
+       private HashMap<String, String> artifactMapping = new HashMap<String, String>();
+
+       private File rootDir;
+
+       public ConvertPoms_01_03(String rootDirPath) {
+               this(new File(rootDirPath));
+       }
+
+       public ConvertPoms_01_03(File rootDir) {
+               this.rootDir = rootDir;
+
+               artifactMapping.put("org.argeo.dep.jacob", "com.jacob");
+               artifactMapping.put("org.argeo.dep.jacob.win32.x86",
+                               "com.jacob.win32.x86");
+               artifactMapping.put("org.argeo.dep.osgi.activemq",
+                               "org.apache.activemq");
+               artifactMapping.put("org.argeo.dep.osgi.activemq.optional",
+                               "org.apache.activemq.optional");
+               artifactMapping.put("org.argeo.dep.osgi.activemq.xmpp",
+                               "org.apache.activemq.xmpp");
+               artifactMapping.put("org.argeo.dep.osgi.aether", "org.sonatype.aether");
+               artifactMapping.put("org.argeo.dep.osgi.boilerpipe",
+                               "de.l3s.boilerpipe");
+               artifactMapping.put("org.argeo.dep.osgi.commons.cli",
+                               "org.apache.commons.cli");
+               artifactMapping.put("org.argeo.dep.osgi.commons.exec",
+                               "org.apache.commons.exec");
+               artifactMapping.put("org.argeo.dep.osgi.directory.shared.asn.codec",
+                               "org.apache.directory.shared.asn.codec");
+               artifactMapping.put("org.argeo.dep.osgi.drewnoakes.metadata_extractor",
+                               "com.drewnoakes.metadata_extractor");
+               artifactMapping.put("org.argeo.dep.osgi.geoapi", "org.opengis");
+               artifactMapping.put("org.argeo.dep.osgi.geotools", "org.geotools");
+               artifactMapping.put("org.argeo.dep.osgi.google.collections",
+                               "com.google.collections");
+               artifactMapping.put("org.argeo.dep.osgi.hibernatespatial",
+                               "org.hibernatespatial");
+               artifactMapping.put("org.argeo.dep.osgi.jackrabbit",
+                               "org.apache.jackrabbit");
+               artifactMapping.put("org.argeo.dep.osgi.jai.imageio",
+                               "com.sun.media.jai.imageio");
+               artifactMapping.put("org.argeo.dep.osgi.java3d", "javax.vecmath");
+               artifactMapping.put("org.argeo.dep.osgi.jcr", "javax.jcr");
+               artifactMapping.put("org.argeo.dep.osgi.jsr275", "javax.measure");
+               artifactMapping.put("org.argeo.dep.osgi.jts", "com.vividsolutions.jts");
+               artifactMapping.put("org.argeo.dep.osgi.mina.filter.ssl",
+                               "org.apache.mina.filter.ssl");
+               artifactMapping.put("org.argeo.dep.osgi.modeshape", "org.modeshape");
+               artifactMapping.put("org.argeo.dep.osgi.netcdf",
+                               "edu.ucar.unidata.netcdf");
+               artifactMapping.put("org.argeo.dep.osgi.pdfbox", "org.apache.pdfbox");
+               artifactMapping.put("org.argeo.dep.osgi.poi", "org.apache.poi");
+               artifactMapping.put("org.argeo.dep.osgi.postgis.jdbc",
+                               "org.postgis.jdbc");
+               artifactMapping.put("org.argeo.dep.osgi.springframework.ldap",
+                               "org.springframework.ldap");
+               artifactMapping.put("org.argeo.dep.osgi.tagsoup",
+                               "org.ccil.cowan.tagsoup");
+               artifactMapping.put("org.argeo.dep.osgi.tika", "org.apache.tika");
+       }
+
+       public void run() {
+               traverse(rootDir);
+       }
+
+       protected void traverse(File dir) {
+               for (File file : dir.listFiles()) {
+                       String fileName = file.getName();
+                       if (file.isDirectory() && !skipDirName(fileName)) {
+                               traverse(file);
+                       } else if (fileName.equals("pom.xml")) {
+                               processPom(file);
+                       }
+               }
+       }
+
+       protected Boolean skipDirName(String fileName) {
+               return fileName.equals(".svn") || fileName.equals("target")
+                               || fileName.equals("META-INF") || fileName.equals("src");
+       }
+
+       protected void processPom(File pomFile) {
+               try {
+                       Boolean wasChanged = false;
+                       DocumentBuilderFactory dbFactory = DocumentBuilderFactory
+                                       .newInstance();
+                       DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+                       Document doc = dBuilder.parse(pomFile);
+                       doc.getDocumentElement().normalize();
+
+                       Element dependenciesElement = null;
+                       NodeList rootChildren = doc.getDocumentElement().getChildNodes();
+                       for (int temp = 0; temp < rootChildren.getLength(); temp++) {
+                               Node n = rootChildren.item(temp);
+                               if (n.getNodeName().equals("dependencies"))
+                                       dependenciesElement = (Element) n;
+                       }
+
+                       if (dependenciesElement != null) {
+                               stdOut("\n## " + pomFile);
+                               NodeList dependencyElements = dependenciesElement
+                                               .getElementsByTagName("dependency");
+
+                               for (int temp = 0; temp < dependencyElements.getLength(); temp++) {
+                                       Element eElement = (Element) dependencyElements.item(temp);
+                                       String groupId = getTagValue(eElement, "groupId");
+                                       String artifactId = getTagValue(eElement, "artifactId");
+                                       // stdOut(groupId + ":" + artifactId);
+
+                                       String newGroupId = null;
+                                       String newArtifactId = null;
+                                       if (groupId.startsWith("org.argeo.dep")) {
+                                               newGroupId = "org.argeo.tp";
+                                       } else if (!(groupId.startsWith("org.argeo")
+                                                       || groupId.startsWith("com.capco")
+                                                       || groupId.startsWith("com.agfa") || groupId
+                                                       .startsWith("org.ibboost"))) {
+                                               newGroupId = "org.argeo.tp";
+                                       }
+
+                                       if (artifactMapping.containsKey(artifactId)) {
+                                               newArtifactId = artifactMapping.get(artifactId);
+                                       } else if (artifactId.startsWith(SPRING_SOURCE_PREFIX)
+                                                       && !artifactId.equals(SPRING_SOURCE_PREFIX
+                                                                       + ".json")) {
+                                               newArtifactId = artifactId
+                                                               .substring(SPRING_SOURCE_PREFIX.length() + 1);
+                                       }
+
+                                       // modify
+                                       if (newGroupId != null || newArtifactId != null) {
+                                               if (newGroupId == null)
+                                                       newGroupId = groupId;
+                                               if (newArtifactId == null)
+                                                       newArtifactId = artifactId;
+                                               stdOut(groupId + ":" + artifactId + " => " + newGroupId
+                                                               + ":" + newArtifactId);
+                                               setTagValue(eElement, "groupId", newGroupId);
+                                               setTagValue(eElement, "artifactId", newArtifactId);
+                                               wasChanged = true;
+                                       }
+                               }
+                       }
+
+                       if (wasChanged) {
+                               // pomFile.renameTo(new File(pomFile.getParentFile(),
+                               // "pom-old.xml"));
+                               // save in place
+                               Source source = new DOMSource(doc);
+                               Result result = new StreamResult(pomFile);
+                               Transformer xformer = TransformerFactory.newInstance()
+                                               .newTransformer();
+                               xformer.transform(source, result);
+                       }
+               } catch (Exception e) {
+                       throw new RuntimeException("Cannot process " + pomFile, e);
+               }
+
+       }
+
+       private String getTagValue(Element eElement, String sTag) {
+               NodeList nList = eElement.getElementsByTagName(sTag);
+               if (nList.getLength() > 0) {
+                       NodeList nlList = nList.item(0).getChildNodes();
+                       Node nValue = (Node) nlList.item(0);
+                       return nValue.getNodeValue();
+               } else
+                       return null;
+       }
+
+       private void setTagValue(Element eElement, String sTag, String value) {
+               NodeList nList = eElement.getElementsByTagName(sTag);
+               if (nList.getLength() > 0) {
+                       NodeList nlList = nList.item(0).getChildNodes();
+                       Node nValue = (Node) nlList.item(0);
+                       nValue.setNodeValue(value);
+               }
+       }
+
+       public static void stdOut(Object obj) {
+               System.out.println(obj);
+       }
+
+       public static void main(String argv[]) {
+               new ConvertPoms_01_03(argv[0]).run();
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/GenerateBinaries.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/GenerateBinaries.java
new file mode 100644 (file)
index 0000000..cd5283d
--- /dev/null
@@ -0,0 +1,584 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+import javax.jcr.Credentials;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.ArtifactIdComparator;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.osgi.framework.Version;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Generates binaries-, sources- and sdk-version.pom artifacts for a given
+ * group.
+ */
+public class GenerateBinaries implements Runnable, SlcNames {
+       private final static Log log = LogFactory.getLog(GenerateBinaries.class);
+
+       // Connection info
+       private Repository repository;
+       private Credentials credentials;
+       private String workspace;
+
+       // Business info
+       private String groupId;
+       private String parentPomCoordinates;
+       private String version = null;
+
+       // Constants
+       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+       private List<String> excludedSuffixes = new ArrayList<String>();
+
+       // Indexes
+       private Set<Artifact> binaries = new TreeSet<Artifact>(
+                       new ArtifactIdComparator());
+       private Set<Artifact> sources = new TreeSet<Artifact>(
+                       new ArtifactIdComparator());
+
+       // local cache
+       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
+       private Node allArtifactsHighestVersion;
+
+       public void run() {
+               Session session = null;
+               try {
+                       session = repository.login(credentials, workspace);
+                       Node groupNode = session.getNode(MavenConventionsUtils.groupPath(
+                                       artifactBasePath, groupId));
+                       internalPreProcessing(groupNode, null);
+                       internalProcessing(groupNode, null);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot normalize group " + groupId + " in "
+                                       + workspace, e);
+               } finally {
+                       JcrUtils.logoutQuietly(session);
+               }
+       }
+
+       /**
+        * Generates binaries-, sources- and sdk-version.pom artifacts for the given
+        * version (or the highest of all children version if none is precised).
+        * 
+        * By default, it includes each latest version of all artifact of this
+        * group.
+        * 
+        * The 3 generated artifacts are then marked as modular distributions and
+        * indexed.
+        */
+       public static void processGroupNode(Node groupNode, String version,
+                       ArgeoMonitor monitor) throws RepositoryException {
+               // TODO set artifactsBase based on group node
+               GenerateBinaries gb = new GenerateBinaries();
+               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
+                               .getString();
+               gb.setGroupId(groupId);
+               gb.setVersion(version);
+               // TODO use already done pre-processing
+               gb.internalPreProcessing(groupNode, monitor);
+               gb.internalProcessing(groupNode, monitor);
+       }
+
+       /** Only builds local indexes. Does not change anything in the local Session */
+       public static GenerateBinaries preProcessGroupNode(Node groupNode,
+                       ArgeoMonitor monitor) throws RepositoryException {
+               // TODO set artifactsBase based on group node
+               GenerateBinaries gb = new GenerateBinaries();
+               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
+                               .getString();
+               gb.setGroupId(groupId);
+               // gb.setVersion(version);
+               // gb.setOverridePoms(overridePoms);
+               gb.internalPreProcessing(groupNode, monitor);
+               return gb;
+       }
+
+       // exposes indexes. to display results of the pre-processing phase.
+       public Set<Artifact> getBinaries() {
+               return binaries;
+       }
+
+       public Artifact getHighestArtifactVersion() throws RepositoryException {
+               return allArtifactsHighestVersion == null ? null : RepoUtils
+                               .asArtifact(allArtifactsHighestVersion);
+       }
+
+       // //////////////////////////////////////
+       // INTERNAL METHODS
+
+       /**
+        * Browse all children of a Node considered as a folder that follows Aether
+        * conventions i.e that has Aether's artifact base as children.
+        * 
+        * Each of such child contains a set of Aether artifact versions. This
+        * methods build the binaries {@code Set<Artifact>} and other indexes. It
+        * does not impact the
+        */
+       protected void internalPreProcessing(Node groupNode, ArgeoMonitor monitor)
+                       throws RepositoryException {
+               if (monitor != null)
+                       monitor.subTask("Pre processing group " + groupId);
+
+               // Process all direct children nodes,
+               // gathering latest versions of each artifact
+               allArtifactsHighestVersion = null;
+
+               aBases: for (NodeIterator aBases = groupNode.getNodes(); aBases
+                               .hasNext();) {
+                       Node aBase = aBases.nextNode();
+                       if (aBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
+                               Node highestAVersion = getArtifactLatestVersion(aBase);
+                               if (highestAVersion == null)
+                                       continue aBases;
+                               else {
+                                       // retrieve relevant child node
+                                       // Information is stored on the NT_FILE child node.
+                                       for (NodeIterator files = highestAVersion.getNodes(); files
+                                                       .hasNext();) {
+                                               Node file = files.nextNode();
+                                               if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
+                                                       if (log.isDebugEnabled())
+                                                               log.debug("Pre-Processing " + file.getName());
+                                                       preProcessBundleArtifact(file);
+                                               }
+                                       }
+                               }
+                       }
+               }
+               // if (log.isDebugEnabled()) {
+               // int bundleCount = symbolicNamesToNodes.size();
+               // log.debug("" + bundleCount + " bundles have been indexed for "
+               // + groupId);
+               // }
+       }
+
+       /** Does the real job : writes JCR META-DATA and generates binaries */
+       protected void internalProcessing(Node groupNode, ArgeoMonitor monitor)
+                       throws RepositoryException {
+               if (monitor != null)
+                       monitor.subTask("Processing group " + groupId);
+
+               Session session = groupNode.getSession();
+
+               // if version not set or empty, use the highest version
+               // useful when indexing a product maven repository where
+               // all artifacts have the same version for a given release
+               // => the version can then be left empty
+               if (version == null || version.trim().equals(""))
+                       if (allArtifactsHighestVersion != null)
+                               version = allArtifactsHighestVersion.getProperty(
+                                               SLC_ARTIFACT_VERSION).getString();
+                       else
+                               throw new SlcException("Group version " + version
+                                               + " is empty.");
+
+               // int bundleCount = symbolicNamesToNodes.size();
+               // int count = 1;
+               // for (Node bundleNode : symbolicNamesToNodes.values()) {
+               // if (log.isDebugEnabled())
+               // log.debug("Processing " + bundleNode.getName() + " ( " + count
+               // + "/" + bundleCount + " )");
+               //
+               // // processBundleArtifact(bundleNode);
+               // // bundleNode.getSession().save();
+               // count++;
+               // }
+
+               // indexes
+               Set<Artifact> indexes = new TreeSet<Artifact>(
+                               new ArtifactIdComparator());
+
+               Artifact indexArtifact;
+               indexArtifact = writeIndex(session, RepoConstants.BINARIES_ARTIFACT_ID,
+                               binaries);
+               indexes.add(indexArtifact);
+
+               indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID,
+                               sources);
+               indexes.add(indexArtifact);
+
+               // sdk
+               writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
+
+               if (monitor != null)
+                       monitor.worked(1);
+       }
+
+       protected void preProcessBundleArtifact(Node bundleNode)
+                       throws RepositoryException {
+
+               String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
+               // Sanity check.
+               if (symbolicName == null)
+                       log.warn("Symbolic name is null for bundle " + bundleNode);
+
+               // Manage source bundles
+               if (symbolicName.endsWith(".source")) {
+                       // TODO make a shared node with classifier 'sources'?
+                       String bundleName = RepoUtils
+                                       .extractBundleNameFromSourceName(symbolicName);
+                       for (String excludedSuffix : excludedSuffixes) {
+                               if (bundleName.endsWith(excludedSuffix))
+                                       return;// skip adding to sources
+                       }
+                       sources.add(RepoUtils.asArtifact(bundleNode));
+                       return;
+               }
+
+               // // Build indexes
+               // NodeIterator exportPackages = bundleNode.getNodes(SLC_
+               // + Constants.EXPORT_PACKAGE);
+               // while (exportPackages.hasNext()) {
+               // Node exportPackage = exportPackages.nextNode();
+               // String pkg = JcrUtils.get(exportPackage, SLC_NAME);
+               // packagesToSymbolicNames.put(pkg, symbolicName);
+               // }
+               //
+               // symbolicNamesToNodes.put(symbolicName, bundleNode);
+               // for (String excludedSuffix : excludedSuffixes) {
+               // if (symbolicName.endsWith(excludedSuffix))
+               // return;// skip adding to binaries
+               // }
+
+               binaries.add(RepoUtils.asArtifact(bundleNode));
+
+               // Extra check. to remove
+               if (bundleNode.getSession().hasPendingChanges())
+                       throw new SlcException("Pending changes in the session, "
+                                       + "this should not be true here.");
+       }
+
+       // protected void processBundleArtifact(Node bundleNode)
+       // throws RepositoryException {
+       // Node artifactFolder = bundleNode.getParent();
+       // String baseName = FilenameUtils.getBaseName(bundleNode.getName());
+       //
+       // // pom
+       // String pomName = baseName + ".pom";
+       // if (artifactFolder.hasNode(pomName) && !overridePoms)
+       // return;// skip
+       //
+       // String pom = generatePomForBundle(bundleNode);
+       // Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
+       // pom.getBytes());
+       // // checksum
+       // String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
+       // JcrUtils.copyBytesAsFile(artifactFolder,
+       // bundleNode.getName() + ".sha1", bundleSha.getBytes());
+       // String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
+       // JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
+       // pomSha.getBytes());
+       // }
+
+       // ////////////////////
+       // LOCAL WRITERS
+       //
+
+       private Artifact writeIndex(Session session, String artifactId,
+                       Set<Artifact> artifacts) throws RepositoryException {
+               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
+                               version);
+               Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
+                               parentPomCoordinates) : null;
+               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
+                               artifacts, parentArtifact);
+               Node node = RepoUtils.copyBytesAsArtifact(
+                               session.getNode(artifactBasePath), artifact, pom.getBytes());
+               artifactIndexer.index(node);
+
+               // TODO factorize
+               String pomSha = JcrUtils.checksumFile(node, "SHA-1");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
+                               pomSha.getBytes());
+               String pomMd5 = JcrUtils.checksumFile(node, "MD5");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
+                               pomMd5.getBytes());
+               session.save();
+               return artifact;
+       }
+
+       // Helpers
+       private Node getArtifactLatestVersion(Node artifactBase) {
+               try {
+                       Node highestAVersion = null;
+                       for (NodeIterator aVersions = artifactBase.getNodes(); aVersions
+                                       .hasNext();) {
+                               Node aVersion = aVersions.nextNode();
+                               if (aVersion.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
+                                       if (highestAVersion == null) {
+                                               highestAVersion = aVersion;
+                                               if (allArtifactsHighestVersion == null)
+                                                       allArtifactsHighestVersion = aVersion;
+                                               // Correctly handle following arrival order:
+                                               // Name1 - V1, name2 - V3
+                                               else {
+                                                       Version cachedHighestVersion = extractOsgiVersion(allArtifactsHighestVersion);
+                                                       Version currVersion = extractOsgiVersion(aVersion);
+                                                       if (currVersion.compareTo(cachedHighestVersion) > 0)
+                                                               allArtifactsHighestVersion = aVersion;
+                                               }
+                                       } else {
+                                               Version currVersion = extractOsgiVersion(aVersion);
+                                               Version currentHighestVersion = extractOsgiVersion(highestAVersion);
+                                               if (currVersion.compareTo(currentHighestVersion) > 0) {
+                                                       highestAVersion = aVersion;
+                                               }
+                                               if (currVersion
+                                                               .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
+                                                       allArtifactsHighestVersion = aVersion;
+                                               }
+                                       }
+
+                               }
+                       }
+                       return highestAVersion;
+               } catch (RepositoryException re) {
+                       throw new SlcException("Unable to get latest version for node "
+                                       + artifactBase, re);
+               }
+       }
+
+       private Version extractOsgiVersion(Node artifactVersion)
+                       throws RepositoryException {
+               String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
+                               .getString();
+               String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
+               Version osgiVersion = null;
+               // log invalid version value to enable tracking them
+               try {
+                       osgiVersion = new Version(cleanVersion);
+               } catch (IllegalArgumentException e) {
+                       log.error("Version string " + cleanVersion + " is invalid ");
+                       String twickedVersion = twickInvalidVersion(cleanVersion);
+                       osgiVersion = new Version(twickedVersion);
+                       log.error("Using " + twickedVersion + " instead");
+                       // throw e;
+               }
+               return osgiVersion;
+       }
+
+       private String twickInvalidVersion(String tmpVersion) {
+               String[] tokens = tmpVersion.split("\\.");
+               if (tokens.length == 3 && tokens[2].lastIndexOf("-") > 0) {
+                       String newSuffix = tokens[2].replaceFirst("-", ".");
+                       tmpVersion = tmpVersion.replaceFirst(tokens[2], newSuffix);
+               } else if (tokens.length > 4) {
+                       // FIXME manually remove other "."
+                       StringTokenizer st = new StringTokenizer(tmpVersion, ".", true);
+                       StringBuilder builder = new StringBuilder();
+                       // Major
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Minor
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Micro
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Qualifier
+                       builder.append(st.nextToken());
+                       while (st.hasMoreTokens()) {
+                               // consume delimiter
+                               st.nextToken();
+                               if (st.hasMoreTokens())
+                                       builder.append("-").append(st.nextToken());
+                       }
+                       tmpVersion = builder.toString();
+               }
+               return tmpVersion;
+       }
+
+       // private String generatePomForBundle(Node n) throws RepositoryException {
+       // String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
+       //
+       // StringBuffer p = new StringBuffer();
+       //
+       // // XML header
+       // p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+       // p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
+       // p.append("<modelVersion>4.0.0</modelVersion>");
+       //
+       // // Artifact
+       // p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
+       // .append("</groupId>\n");
+       // p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
+       // .append("</artifactId>\n");
+       // p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
+       // .append("</version>\n");
+       // p.append("<packaging>pom</packaging>\n");
+       // if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
+       // p.append("<name>")
+       // .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
+       // .append("</name>\n");
+       // if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
+       // p.append("<description>")
+       // .append(JcrUtils
+       // .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
+       // .append("</description>\n");
+       //
+       // // Dependencies
+       // Set<String> dependenciesSymbolicNames = new TreeSet<String>();
+       // Set<String> optionalSymbolicNames = new TreeSet<String>();
+       // NodeIterator importPackages = n.getNodes(SLC_
+       // + Constants.IMPORT_PACKAGE);
+       // while (importPackages.hasNext()) {
+       // Node importPackage = importPackages.nextNode();
+       // String pkg = JcrUtils.get(importPackage, SLC_NAME);
+       // if (packagesToSymbolicNames.containsKey(pkg)) {
+       // String dependencySymbolicName = packagesToSymbolicNames
+       // .get(pkg);
+       // if (JcrUtils.check(importPackage, SLC_OPTIONAL))
+       // optionalSymbolicNames.add(dependencySymbolicName);
+       // else
+       // dependenciesSymbolicNames.add(dependencySymbolicName);
+       // } else {
+       // if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
+       // && !systemPackages.contains(pkg))
+       // log.warn("No bundle found for pkg " + pkg);
+       // }
+       // }
+       //
+       // if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
+       // String fragmentHost = JcrUtils.get(
+       // n.getNode(SLC_ + Constants.FRAGMENT_HOST),
+       // SLC_SYMBOLIC_NAME);
+       // dependenciesSymbolicNames.add(fragmentHost);
+       // }
+       //
+       // // TODO require bundles
+       //
+       // List<Node> dependencyNodes = new ArrayList<Node>();
+       // for (String depSymbName : dependenciesSymbolicNames) {
+       // if (depSymbName.equals(ownSymbolicName))
+       // continue;// skip self
+       //
+       // if (symbolicNamesToNodes.containsKey(depSymbName))
+       // dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
+       // else
+       // log.warn("Could not find node for " + depSymbName);
+       // }
+       // List<Node> optionalDependencyNodes = new ArrayList<Node>();
+       // for (String depSymbName : optionalSymbolicNames) {
+       // if (symbolicNamesToNodes.containsKey(depSymbName))
+       // optionalDependencyNodes.add(symbolicNamesToNodes
+       // .get(depSymbName));
+       // else
+       // log.warn("Could not find node for " + depSymbName);
+       // }
+       //
+       // p.append("<dependencies>\n");
+       // for (Node dependencyNode : dependencyNodes) {
+       // p.append("<dependency>\n");
+       // p.append("\t<groupId>")
+       // .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
+       // .append("</groupId>\n");
+       // p.append("\t<artifactId>")
+       // .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
+       // .append("</artifactId>\n");
+       // p.append("</dependency>\n");
+       // }
+       //
+       // if (optionalDependencyNodes.size() > 0)
+       // p.append("<!-- OPTIONAL -->\n");
+       // for (Node dependencyNode : optionalDependencyNodes) {
+       // p.append("<dependency>\n");
+       // p.append("\t<groupId>")
+       // .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
+       // .append("</groupId>\n");
+       // p.append("\t<artifactId>")
+       // .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
+       // .append("</artifactId>\n");
+       // p.append("\t<optional>true</optional>\n");
+       // p.append("</dependency>\n");
+       // }
+       // p.append("</dependencies>\n");
+       //
+       // // Dependency management
+       // p.append("<dependencyManagement>\n");
+       // p.append("<dependencies>\n");
+       // p.append("<dependency>\n");
+       // p.append("\t<groupId>").append(groupId).append("</groupId>\n");
+       // p.append("\t<artifactId>")
+       // .append(ownSymbolicName.endsWith(".source") ?
+       // RepoConstants.SOURCES_ARTIFACT_ID
+       // : RepoConstants.BINARIES_ARTIFACT_ID)
+       // .append("</artifactId>\n");
+       // p.append("\t<version>").append(version).append("</version>\n");
+       // p.append("\t<type>pom</type>\n");
+       // p.append("\t<scope>import</scope>\n");
+       // p.append("</dependency>\n");
+       // p.append("</dependencies>\n");
+       // p.append("</dependencyManagement>\n");
+       //
+       // p.append("</project>\n");
+       // return p.toString();
+       // }
+
+       /* SETTERS */
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setCredentials(Credentials credentials) {
+               this.credentials = credentials;
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+       public void setGroupId(String groupId) {
+               this.groupId = groupId;
+       }
+
+       public void setParentPomCoordinates(String parentPomCoordinates) {
+               this.parentPomCoordinates = parentPomCoordinates;
+       }
+
+       public void setArtifactBasePath(String artifactBasePath) {
+               this.artifactBasePath = artifactBasePath;
+       }
+
+       public void setVersion(String version) {
+               this.version = version;
+       }
+
+       public void setExcludedSuffixes(List<String> excludedSuffixes) {
+               this.excludedSuffixes = excludedSuffixes;
+       }
+
+       public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
+               this.artifactIndexer = artifactIndexer;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ImportMavenDependencies.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/ImportMavenDependencies.java
new file mode 100644 (file)
index 0000000..d1245ff
--- /dev/null
@@ -0,0 +1,374 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Repository;
+import javax.jcr.Session;
+import javax.jcr.nodetype.NodeType;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherTemplate;
+import org.argeo.slc.aether.ArtifactIdComparator;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.JarFileIndexer;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.graph.DependencyNode;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Import all the dependencies listed in a POM and their dependency graphs to a
+ * workspace.
+ */
+public class ImportMavenDependencies implements Runnable {
+       private final static Log log = LogFactory
+                       .getLog(ImportMavenDependencies.class);
+
+       private AetherTemplate aetherTemplate;
+       private String rootCoordinates = "org.argeo.dep:versions-all:pom:1.2.0";
+       private String distCoordinates = "org.argeo.tp:dist:pom:1.3.0";
+       private String parentPomCoordinates = "org.argeo:parent:1.2.0";
+       private Set<String> excludedArtifacts = new HashSet<String>();
+
+       private Repository repository;
+       private String workspace;
+
+       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+
+       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
+       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
+       private Comparator<Artifact> artifactComparator = new ArtifactIdComparator();
+
+       public void run() {
+               // resolve
+               Set<Artifact> artifacts = resolveDistribution();
+
+               // sync
+               sync(artifacts);
+       }
+
+       void sync(Set<Artifact> artifacts) {
+               Session session = null;
+               try {
+                       session = JcrUtils.loginOrCreateWorkspace(repository, workspace);
+                       // clear
+                       NodeIterator nit = session.getNode(artifactBasePath).getNodes();
+                       while (nit.hasNext()) {
+                               Node node = nit.nextNode();
+                               if (node.isNodeType(NodeType.NT_FOLDER)
+                                               || node.isNodeType(NodeType.NT_UNSTRUCTURED))
+                                       node.remove();
+                       }
+                       session.save();
+
+                       // sync
+                       syncDistribution(session, artifacts);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot import distribution", e);
+               } finally {
+                       JcrUtils.logoutQuietly(session);
+               }
+       }
+
+       /**
+        * Generate a POM with all the artifacts declared in root coordinates as
+        * dependencies AND in dependency management.
+        */
+       void createDistPom() {
+               try {
+                       Artifact pomArtifact = new DefaultArtifact(rootCoordinates);
+
+                       Set<Artifact> registeredArtifacts = new TreeSet<Artifact>(
+                                       artifactComparator);
+                       MavenConventionsUtils.gatherPomDependencies(aetherTemplate,
+                                       registeredArtifacts, pomArtifact);
+                       Artifact sdkArtifact = new DefaultArtifact(distCoordinates);
+                       String sdkPom = MavenConventionsUtils.artifactsAsDependencyPom(
+                                       sdkArtifact, registeredArtifacts, new DefaultArtifact(
+                                                       parentPomCoordinates));
+                       if (log.isDebugEnabled())
+                               log.debug("Gathered " + registeredArtifacts.size()
+                                               + " artifacts:\n" + sdkPom);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot resolve distribution", e);
+               }
+       }
+
+       /** Returns all transitive dependencies of dist POM */
+       private Set<Artifact> resolveDistribution() {
+               try {
+                       Artifact distArtifact = new DefaultArtifact(distCoordinates);
+                       Set<Artifact> artifacts = new TreeSet<Artifact>(artifactComparator);
+
+                       DependencyNode node = aetherTemplate
+                                       .resolveDependencies(distArtifact);
+                       addDependencies(artifacts, node, null);
+
+                       if (log.isDebugEnabled()) {
+                               log.debug("Resolved " + artifacts.size() + " artifacts");
+
+                               // Properties distributionDescriptor =
+                               // generateDistributionDescriptor(artifacts);
+                               // ByteArrayOutputStream out = new ByteArrayOutputStream();
+                               // distributionDescriptor.store(out, "");
+                               // log.debug(new String(out.toByteArray()));
+                               // out.close();
+                       }
+
+                       /*
+                        * for (Artifact artifact : registeredArtifacts) { try { Boolean
+                        * wasAdded = addArtifact(artifacts, artifact); if (wasAdded) {
+                        * DependencyNode node = aetherTemplate
+                        * .resolveDependencies(artifact); addDependencies(artifacts, node,
+                        * null); } } catch (Exception e) {
+                        * log.error("Could not resolve dependencies of " + artifact + ": "
+                        * + e.getCause().getMessage()); }
+                        * 
+                        * }
+                        * 
+                        * if (log.isDebugEnabled()) log.debug("Resolved " +
+                        * artifacts.size() + " artifacts");
+                        * 
+                        * // distribution descriptor // Properties distributionDescriptor =
+                        * // generateDistributionDescriptor(artifacts); //
+                        * ByteArrayOutputStream out = new ByteArrayOutputStream(); //
+                        * distributionDescriptor.store(out, ""); // log.debug(new
+                        * String(out.toByteArray())); // out.close();
+                        */
+                       return artifacts;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot resolve distribution", e);
+               }
+       }
+
+       protected Properties generateDistributionDescriptor(Set<Artifact> artifacts) {
+               Properties distributionDescriptor = new Properties();
+               for (Artifact artifact : artifacts) {
+                       log.debug(artifact.getArtifactId() + " [" + artifact.getVersion()
+                                       + "]\t(" + artifact + ")");
+                       distributionDescriptor.setProperty(artifact.getArtifactId() + ":"
+                                       + artifact.getVersion(), artifact.toString());
+               }
+               return distributionDescriptor;
+       }
+
+       /** Write artifacts to the target workspace, skipping excluded ones */
+       protected void syncDistribution(Session jcrSession, Set<Artifact> artifacts) {
+               Set<Artifact> artifactsWithoutSources = new TreeSet<Artifact>(
+                               artifactComparator);
+               Long begin = System.currentTimeMillis();
+               try {
+                       JcrUtils.mkfolders(jcrSession, artifactBasePath);
+                       artifacts: for (Artifact artifact : artifacts) {
+                               // skip excluded
+                               if (excludedArtifacts.contains(artifact.getGroupId() + ":"
+                                               + artifact.getArtifactId())) {
+                                       if (log.isDebugEnabled())
+                                               log.debug("Exclude " + artifact);
+                                       continue artifacts;
+                               }
+
+                               File jarFile = MavenConventionsUtils.artifactToFile(artifact);
+                               if (!jarFile.exists()) {
+                                       log.warn("Generated file " + jarFile + " for " + artifact
+                                                       + " does not exist");
+                                       continue artifacts;
+                               }
+                               artifact.setFile(jarFile);
+
+                               try {
+                                       String parentPath = MavenConventionsUtils
+                                                       .artifactParentPath(artifactBasePath, artifact);
+                                       Node parentNode;
+                                       if (!jcrSession.itemExists(parentPath))
+                                               parentNode = JcrUtils.mkfolders(jcrSession, parentPath);
+                                       else
+                                               parentNode = jcrSession.getNode(parentPath);
+
+                                       Node fileNode;
+                                       if (!parentNode.hasNode(jarFile.getName())) {
+                                               fileNode = createFileNode(parentNode, jarFile);
+                                       } else {
+                                               fileNode = parentNode.getNode(jarFile.getName());
+                                       }
+
+                                       if (artifactIndexer.support(fileNode.getPath()))
+                                               artifactIndexer.index(fileNode);
+                                       if (jarFileIndexer.support(fileNode.getPath()))
+                                               jarFileIndexer.index(fileNode);
+                                       jcrSession.save();
+
+                                       addPdeSource(jcrSession, artifact, jarFile,
+                                                       artifactsWithoutSources);
+                                       jcrSession.save();
+
+                                       if (log.isDebugEnabled())
+                                               log.debug("Synchronized " + fileNode);
+                               } catch (Exception e) {
+                                       log.error("Could not synchronize " + artifact, e);
+                                       jcrSession.refresh(false);
+                                       throw e;
+                               }
+                       }
+
+                       Long duration = (System.currentTimeMillis() - begin) / 1000;
+                       if (log.isDebugEnabled()) {
+                               log.debug("Synchronized distribution in " + duration + "s");
+                               log.debug("The following artifacts have no sources:");
+                               for (Artifact artifact : artifactsWithoutSources) {
+                                       log.debug(artifact);
+                               }
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot synchronize distribution", e);
+               }
+       }
+
+       /** Try to add PDE sources */
+       private void addPdeSource(Session session, Artifact artifact,
+                       File artifactFile, Set<Artifact> artifactsWithoutSources) {
+               ByteArrayOutputStream out = new ByteArrayOutputStream();
+               try {
+                       File origSourceFile = null;
+                       Artifact origSourceArtifact = new DefaultArtifact(
+                                       artifact.getGroupId(), artifact.getArtifactId(), "sources",
+                                       artifact.getExtension(), artifact.getVersion());
+                       Artifact newSourceArtifact = new DefaultArtifact(
+                                       artifact.getGroupId(),
+                                       artifact.getArtifactId() + ".source",
+                                       artifact.getExtension(), artifact.getVersion());
+                       try {
+                               origSourceFile = aetherTemplate
+                                               .getResolvedFile(origSourceArtifact);
+                       } catch (Exception e) {
+                               // also try artifact following the conventions
+                               origSourceArtifact = newSourceArtifact;
+                               origSourceFile = aetherTemplate
+                                               .getResolvedFile(origSourceArtifact);
+                       }
+
+                       String newSourceParentPath = MavenConventionsUtils
+                                       .artifactParentPath(artifactBasePath, newSourceArtifact);
+                       Node newSourceParentNode = JcrUtils.mkfolders(session,
+                                       newSourceParentPath);
+                       NameVersion bundleNameVersion = RepoUtils
+                                       .readNameVersion(artifactFile);
+                       RepoUtils.packagesAsPdeSource(origSourceFile, bundleNameVersion,
+                                       out);
+                       String newSourceFileName = MavenConventionsUtils
+                                       .artifactFileName(newSourceArtifact);
+                       JcrUtils.copyBytesAsFile(newSourceParentNode, newSourceFileName,
+                                       out.toByteArray());
+               } catch (Exception e) {
+                       log.error("Cannot add PDE source for " + artifact + ": " + e);
+                       artifactsWithoutSources.add(artifact);
+               } finally {
+                       IOUtils.closeQuietly(out);
+               }
+       }
+
+       private Node createFileNode(Node parentNode, File file) {
+               return JcrUtils.copyFile(parentNode, file);
+       }
+
+       /** Recursively adds non optional dependencies */
+       private void addDependencies(Set<Artifact> artifacts, DependencyNode node,
+                       String ancestors) {
+               // if (artifacts.contains(node.getDependency().getArtifact()))
+               // return;
+               String currentArtifactId = node.getDependency().getArtifact()
+                               .getArtifactId();
+               if (log.isDebugEnabled()) {
+                       log.debug("# Add dependency for " + currentArtifactId);
+                       if (ancestors != null)
+                               log.debug(ancestors);
+               }
+               for (DependencyNode child : node.getChildren()) {
+                       if (!child.getDependency().isOptional()) {
+                               if (willAdd(child.getDependency().getArtifact())) {
+                                       addArtifact(artifacts, child.getDependency().getArtifact());
+                                       addDependencies(artifacts, child, currentArtifactId + "\n"
+                                                       + (ancestors != null ? ancestors : ""));
+                               }
+                       }
+               }
+       }
+
+       /** @return whether it was added */
+       private Boolean addArtifact(Set<Artifact> artifacts, Artifact artifact) {
+               Boolean willAdd = willAdd(artifact);
+               if (willAdd)
+                       artifacts.add(artifact);
+               else
+                       log.info("Skip " + artifact);
+               return willAdd;
+       }
+
+       private Boolean willAdd(Artifact artifact) {
+               Boolean willAdd = true;
+               if (excludedArtifacts.contains(artifact.getGroupId() + ":"
+                               + artifact.getArtifactId()))
+                       willAdd = false;
+               else if (excludedArtifacts.contains(artifact.getGroupId() + ":*"))
+                       willAdd = false;
+               return willAdd;
+       }
+
+       public void setAetherTemplate(AetherTemplate aetherTemplate) {
+               this.aetherTemplate = aetherTemplate;
+       }
+
+       public void setExcludedArtifacts(Set<String> excludedArtifactIds) {
+               this.excludedArtifacts = excludedArtifactIds;
+       }
+
+       public void setRootCoordinates(String rootCoordinates) {
+               this.rootCoordinates = rootCoordinates;
+       }
+
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+       public void setDistCoordinates(String distCoordinates) {
+               this.distCoordinates = distCoordinates;
+       }
+
+       public void setArtifactBasePath(String artifactBasePath) {
+               this.artifactBasePath = artifactBasePath;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/IndexDistribution.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/IndexDistribution.java
new file mode 100644 (file)
index 0000000..758316d
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.io.File;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.jcr.Node;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.RepoConstants;
+import org.sonatype.aether.artifact.Artifact;
+
+/** Create a distribution node from a set of artifacts */
+public class IndexDistribution implements Runnable {
+       private final static Log log = LogFactory.getLog(IndexDistribution.class);
+       private Repository repository;
+       private String workspace;
+
+       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
+       private String distributionsBasePath = RepoConstants.DISTRIBUTIONS_BASE_PATH;
+       private String distributionName;
+
+       public void run() {
+               // TODO populate
+               Set<Artifact> artifacts = new HashSet<Artifact>();
+
+               // sync
+               Session session = null;
+               try {
+                       session = repository.login(workspace);
+                       syncDistribution(session, artifacts);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot import distribution", e);
+               } finally {
+                       JcrUtils.logoutQuietly(session);
+               }
+       }
+
+       protected void syncDistribution(Session jcrSession, Set<Artifact> artifacts) {
+               Long begin = System.currentTimeMillis();
+               try {
+                       JcrUtils.mkdirs(jcrSession, distributionsBasePath + '/'
+                                       + distributionName);
+                       artifacts: for (Artifact artifact : artifacts) {
+                               File file = artifact.getFile();
+                               if (file == null) {
+                                       file = MavenConventionsUtils.artifactToFile(artifact);
+                                       if (!file.exists()) {
+                                               log.warn("Generated file " + file + " for " + artifact
+                                                               + " does not exist");
+                                               continue artifacts;
+                                       }
+                               }
+
+                               try {
+                                       String parentPath = artifactBasePath
+                                                       + (artifactBasePath.endsWith("/") ? "" : "/")
+                                                       + artifactParentPath(artifact);
+                                       Node parentNode = jcrSession.getNode(parentPath);
+                                       Node fileNode = parentNode.getNode(file.getName());
+
+                                       if (fileNode.hasProperty(SlcNames.SLC_SYMBOLIC_NAME)) {
+                                               String distPath = bundleDistributionPath(fileNode);
+                                               if (!jcrSession.itemExists(distPath)
+                                                               && fileNode
+                                                                               .isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT))
+                                                       jcrSession.getWorkspace().clone(
+                                                                       jcrSession.getWorkspace().getName(),
+                                                                       fileNode.getPath(), distPath, false);
+                                               if (log.isDebugEnabled())
+                                                       log.debug("Indexed " + fileNode);
+                                       }
+                               } catch (Exception e) {
+                                       log.error("Could not index " + artifact, e);
+                                       jcrSession.refresh(false);
+                                       throw e;
+                               }
+                       }
+
+                       Long duration = (System.currentTimeMillis() - begin) / 1000;
+                       if (log.isDebugEnabled())
+                               log.debug("Indexed distribution in " + duration + "s");
+               } catch (Exception e) {
+                       throw new SlcException("Cannot synchronize distribution", e);
+               }
+       }
+
+       private String artifactParentPath(Artifact artifact) {
+               return artifact.getGroupId().replace('.', '/') + '/'
+                               + artifact.getArtifactId() + '/' + artifact.getVersion();
+       }
+
+       private String bundleDistributionPath(Node fileNode) {
+               try {
+                       return distributionsBasePath
+                                       + '/'
+                                       + distributionName
+                                       + '/'
+                                       + fileNode.getProperty(SlcNames.SLC_SYMBOLIC_NAME)
+                                                       .getString()
+                                       + '_'
+                                       + fileNode.getProperty(SlcNames.SLC_BUNDLE_VERSION)
+                                                       .getString();
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot create distribution path for "
+                                       + fileNode, e);
+               }
+       }
+
+       public void setDistributionName(String distributionName) {
+               this.distributionName = distributionName;
+       }
+
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenConventionsUtils.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenConventionsUtils.java
new file mode 100644 (file)
index 0000000..4e8d3fb
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.io.File;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherTemplate;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+/**
+ * Static utilities around Maven which are NOT using the Maven APIs (conventions
+ * based).
+ */
+public class MavenConventionsUtils {
+       private final static Log log = LogFactory
+                       .getLog(MavenConventionsUtils.class);
+
+       /**
+        * Path to the file identified by this artifact <b>without</b> using Maven
+        * APIs (convention based). Default location of repository
+        * (~/.m2/repository) is used here.
+        * 
+        * @see MavenConventionsUtils#artifactToFile(String, Artifact)
+        */
+       public static File artifactToFile(Artifact artifact) {
+               return artifactToFile(System.getProperty("user.home") + File.separator
+                               + ".m2" + File.separator + "repository", artifact);
+       }
+
+       /**
+        * Path to the file identified by this artifact <b>without</b> using Maven
+        * APIs (convention based).
+        * 
+        * @param repositoryPath
+        *            path to the related local repository location
+        * @param artifact
+        *            the artifact
+        */
+       public static File artifactToFile(String repositoryPath, Artifact artifact) {
+               return new File(repositoryPath + File.separator
+                               + artifact.getGroupId().replace('.', File.separatorChar)
+                               + File.separator + artifact.getArtifactId() + File.separator
+                               + artifact.getVersion() + File.separator
+                               + artifactFileName(artifact)).getAbsoluteFile();
+       }
+
+       /** The file name of this artifact when stored */
+       public static String artifactFileName(Artifact artifact) {
+               return artifact.getArtifactId()
+                               + '-'
+                               + artifact.getVersion()
+                               + (artifact.getClassifier().equals("") ? "" : '-' + artifact
+                                               .getClassifier()) + '.' + artifact.getExtension();
+       }
+
+       /** Absolute path to the file */
+       public static String artifactPath(String artifactBasePath, Artifact artifact) {
+               return artifactParentPath(artifactBasePath, artifact) + '/'
+                               + artifactFileName(artifact);
+       }
+
+       /** Absolute path to the directories where the files will be stored */
+       public static String artifactParentPath(String artifactBasePath,
+                       Artifact artifact) {
+               return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/")
+                               + artifactParentPath(artifact);
+       }
+
+       /** Absolute path to the directory of this group */
+       public static String groupPath(String artifactBasePath, String groupId) {
+               return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/")
+                               + groupId.replace('.', '/');
+       }
+
+       /** Relative path to the directories where the files will be stored */
+       public static String artifactParentPath(Artifact artifact) {
+               return artifact.getGroupId().replace('.', '/') + '/'
+                               + artifact.getArtifactId() + '/' + artifact.getBaseVersion();
+       }
+
+       public static String artifactsAsDependencyPom(Artifact pomArtifact,
+                       Set<Artifact> artifacts, Artifact parent) {
+               StringBuffer p = new StringBuffer();
+
+               // XML header
+               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
+               p.append("<modelVersion>4.0.0</modelVersion>\n");
+
+               // Artifact
+               if (parent != null) {
+                       p.append("<parent>\n");
+                       p.append("<groupId>").append(parent.getGroupId())
+                                       .append("</groupId>\n");
+                       p.append("<artifactId>").append(parent.getArtifactId())
+                                       .append("</artifactId>\n");
+                       p.append("<version>").append(parent.getVersion())
+                                       .append("</version>\n");
+                       p.append("</parent>\n");
+               }
+               p.append("<groupId>").append(pomArtifact.getGroupId())
+                               .append("</groupId>\n");
+               p.append("<artifactId>").append(pomArtifact.getArtifactId())
+                               .append("</artifactId>\n");
+               p.append("<version>").append(pomArtifact.getVersion())
+                               .append("</version>\n");
+               p.append("<packaging>pom</packaging>\n");
+
+               // Dependencies
+               p.append("<dependencies>\n");
+               for (Artifact a : artifacts) {
+                       p.append("\t<dependency>");
+                       p.append("<artifactId>").append(a.getArtifactId())
+                                       .append("</artifactId>");
+                       p.append("<groupId>").append(a.getGroupId()).append("</groupId>");
+                       if (!a.getExtension().equals("jar"))
+                               p.append("<type>").append(a.getExtension()).append("</type>");
+                       p.append("</dependency>\n");
+               }
+               p.append("</dependencies>\n");
+
+               // Dependency management
+               p.append("<dependencyManagement>\n");
+               p.append("<dependencies>\n");
+               for (Artifact a : artifacts) {
+                       p.append("\t<dependency>");
+                       p.append("<artifactId>").append(a.getArtifactId())
+                                       .append("</artifactId>");
+                       p.append("<version>").append(a.getVersion()).append("</version>");
+                       p.append("<groupId>").append(a.getGroupId()).append("</groupId>");
+                       if (a.getExtension().equals("pom")) {
+                               p.append("<type>").append(a.getExtension()).append("</type>");
+                               p.append("<scope>import</scope>");
+                       }
+                       p.append("</dependency>\n");
+               }
+               p.append("</dependencies>\n");
+               p.append("</dependencyManagement>\n");
+
+               // Repositories
+               // p.append("<repositories>\n");
+               // p.append("<repository><id>argeo</id><url>http://maven.argeo.org/argeo</url></repository>\n");
+               // p.append("</repositories>\n");
+
+               p.append("</project>\n");
+               return p.toString();
+       }
+
+       /**
+        * Directly parses Maven POM XML format in order to find all artifacts
+        * references under the dependency and dependencyManagement tags. This is
+        * meant to migrate existing pom registering a lot of artifacts, not to
+        * replace Maven resolving.
+        */
+       public static void gatherPomDependencies(AetherTemplate aetherTemplate,
+                       Set<Artifact> artifacts, Artifact pomArtifact) {
+               if (log.isDebugEnabled())
+                       log.debug("Gather dependencies for " + pomArtifact);
+
+               try {
+                       File file = aetherTemplate.getResolvedFile(pomArtifact);
+                       DocumentBuilder documentBuilder = DocumentBuilderFactory
+                                       .newInstance().newDocumentBuilder();
+                       Document doc = documentBuilder.parse(file);
+
+                       // properties
+                       Properties props = new Properties();
+                       props.setProperty("project.version", pomArtifact.getBaseVersion());
+                       NodeList properties = doc.getElementsByTagName("properties");
+                       if (properties.getLength() > 0) {
+                               NodeList propertiesElems = properties.item(0).getChildNodes();
+                               for (int i = 0; i < propertiesElems.getLength(); i++) {
+                                       if (propertiesElems.item(i) instanceof Element) {
+                                               Element property = (Element) propertiesElems.item(i);
+                                               props.put(property.getNodeName(),
+                                                               property.getTextContent());
+                                       }
+                               }
+                       }
+
+                       // dependencies (direct and dependencyManagement)
+                       NodeList dependencies = doc.getElementsByTagName("dependency");
+                       for (int i = 0; i < dependencies.getLength(); i++) {
+                               Element dependency = (Element) dependencies.item(i);
+                               String groupId = dependency.getElementsByTagName("groupId")
+                                               .item(0).getTextContent().trim();
+                               String artifactId = dependency
+                                               .getElementsByTagName("artifactId").item(0)
+                                               .getTextContent().trim();
+                               String version = dependency.getElementsByTagName("version")
+                                               .item(0).getTextContent().trim();
+                               if (version.startsWith("${")) {
+                                       String versionKey = version.substring(0,
+                                                       version.length() - 1).substring(2);
+                                       if (!props.containsKey(versionKey))
+                                               throw new SlcException("Cannot interpret version "
+                                                               + version);
+                                       version = props.getProperty(versionKey);
+                               }
+                               NodeList scopes = dependency.getElementsByTagName("scope");
+                               if (scopes.getLength() > 0
+                                               && scopes.item(0).getTextContent().equals("import")) {
+                                       // recurse
+                                       gatherPomDependencies(aetherTemplate, artifacts,
+                                                       new DefaultArtifact(groupId, artifactId, "pom",
+                                                                       version));
+                               } else {
+                                       // TODO: deal with scope?
+                                       // TODO: deal with type
+                                       String type = "jar";
+                                       Artifact artifact = new DefaultArtifact(groupId,
+                                                       artifactId, type, version);
+                                       artifacts.add(artifact);
+                               }
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot process " + pomArtifact, e);
+               }
+       }
+
+       /** Prevent instantiation */
+       private MavenConventionsUtils() {
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java
new file mode 100644 (file)
index 0000000..fcd65d9
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.nodetype.NodeType;
+import javax.jcr.security.AccessControlException;
+import javax.jcr.security.Privilege;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.jcr.proxy.AbstractUrlProxy;
+import org.argeo.slc.SlcConstants;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.MavenProxyService;
+import org.argeo.slc.repo.RepoConstants;
+import org.sonatype.aether.repository.RemoteRepository;
+
+/** Synchronises the node repository with remote Maven repositories */
+public class MavenProxyServiceImpl extends AbstractUrlProxy implements
+               MavenProxyService, ArgeoNames, SlcNames {
+       private final static Log log = LogFactory
+                       .getLog(MavenProxyServiceImpl.class);
+
+       private List<RemoteRepository> defaultRepositories = new ArrayList<RemoteRepository>();
+
+       /** Initialises the artifacts area. */
+       @Override
+       protected void beforeInitSessionSave(Session session)
+                       throws RepositoryException {
+               JcrUtils.addPrivilege(session, "/", SlcConstants.USER_ANONYMOUS, Privilege.JCR_READ);
+               try {
+                       JcrUtils.addPrivilege(session, "/", SlcConstants.ROLE_SLC,
+                                       Privilege.JCR_ALL);
+               } catch (AccessControlException e) {
+                       if (log.isTraceEnabled())
+                               log.trace("Cannot give jcr:all privileges to "
+                                               + SlcConstants.ROLE_SLC);
+               }
+
+               JcrUtils.mkdirsSafe(session, RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH);
+               Node proxiedRepositories = JcrUtils.mkdirsSafe(session,
+                               RepoConstants.PROXIED_REPOSITORIES);
+               for (RemoteRepository repository : defaultRepositories) {
+                       if (!proxiedRepositories.hasNode(repository.getId())) {
+                               Node proxiedRepository = proxiedRepositories.addNode(repository
+                                               .getId());
+                               proxiedRepository.addMixin(NodeType.MIX_REFERENCEABLE);
+                               JcrUtils.urlToAddressProperties(proxiedRepository,
+                                               repository.getUrl());
+                               // proxiedRepository.setProperty(SLC_URL, repository.getUrl());
+                               proxiedRepository.setProperty(SLC_TYPE,
+                                               repository.getContentType());
+                       }
+               }
+       }
+
+       /**
+        * Retrieve and add this file to the repository
+        */
+       @Override
+       protected Node retrieve(Session session, String path) {
+               try {
+                       if (session.hasPendingChanges())
+                               throw new SlcException("Session has pending changed");
+                       Node node = null;
+                       for (Node proxiedRepository : getBaseUrls(session)) {
+                               String baseUrl = JcrUtils
+                                               .urlFromAddressProperties(proxiedRepository);
+                               node = proxyUrl(session, baseUrl, path);
+                               if (node != null) {
+                                       node.addMixin(SlcTypes.SLC_KNOWN_ORIGIN);
+                                       Node origin = node
+                                                       .addNode(SLC_ORIGIN, SlcTypes.SLC_PROXIED);
+                                       origin.setProperty(SLC_PROXY, proxiedRepository);
+                                       JcrUtils.urlToAddressProperties(origin, baseUrl + path);
+                                       if (log.isDebugEnabled())
+                                               log.debug("Imported " + baseUrl + path + " to " + node);
+                                       return node;
+                               }
+                       }
+                       if (log.isDebugEnabled())
+                               log.warn("No proxy found for " + path);
+                       return null;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot proxy " + path, e);
+               }
+       }
+
+       protected synchronized List<Node> getBaseUrls(Session session)
+                       throws RepositoryException {
+               List<Node> baseUrls = new ArrayList<Node>();
+               for (NodeIterator nit = session.getNode(
+                               RepoConstants.PROXIED_REPOSITORIES).getNodes(); nit.hasNext();) {
+                       Node proxiedRepository = nit.nextNode();
+                       baseUrls.add(proxiedRepository);
+               }
+               return baseUrls;
+       }
+
+       public void setDefaultRepositories(
+                       List<RemoteRepository> defaultRepositories) {
+               this.defaultRepositories = defaultRepositories;
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/Migration_01_03.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/maven/Migration_01_03.java
new file mode 100644 (file)
index 0000000..baf6ec7
--- /dev/null
@@ -0,0 +1,424 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.maven;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes.Name;
+import java.util.jar.Manifest;
+
+import javax.jcr.Binary;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.nodetype.NodeType;
+import javax.jcr.query.QueryManager;
+import javax.jcr.query.QueryResult;
+import javax.jcr.query.qom.Ordering;
+import javax.jcr.query.qom.QueryObjectModel;
+import javax.jcr.query.qom.QueryObjectModelFactory;
+import javax.jcr.query.qom.Selector;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.JarFileIndexer;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.osgi.OsgiProfile;
+import org.osgi.framework.Constants;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Migrate the distribution from 1.2 to 1.4 by cleaning naming and dependencies.
+ * The dependency to the SpringSource Enterprise Bundle repository is removed as
+ * well as their naming conventions. All third party are move to org.argeo.tp
+ * group IDs. Maven dependency for Eclipse artifacts don't use version ranges
+ * anymore. Verison constraints on javax.* packages are removed (since they lead
+ * to "use package conflicts" when Eclipse and Spring Security are used
+ * together).
+ */
+public class Migration_01_03 implements Runnable, SlcNames {
+       final String SPRING_SOURCE_PREFIX = "com.springsource";
+       private final static Log log = LogFactory.getLog(Migration_01_03.class);
+
+       private Repository repository;
+       private String sourceWorkspace;
+       private String targetWorkspace;
+
+       private List<String> excludedBundles = new ArrayList<String>();
+       private Map<String, String> symbolicNamesMapping = new HashMap<String, String>();
+
+       private Session origSession;
+       private Session targetSession;
+
+       private List<String> systemPackages = OsgiProfile.PROFILE_JAVA_SE_1_6
+                       .getSystemPackages();
+
+       private String artifactBasePath = "/";
+
+       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
+       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
+
+       public void init() throws RepositoryException {
+               origSession = JcrUtils.loginOrCreateWorkspace(repository,
+                               sourceWorkspace);
+               targetSession = JcrUtils.loginOrCreateWorkspace(repository,
+                               targetWorkspace);
+
+               // works only in OSGi!!
+               // systemPackages = Arrays.asList(System.getProperty(
+               // "org.osgi.framework.system.packages").split(","));
+       }
+
+       public void destroy() {
+               JcrUtils.logoutQuietly(origSession);
+               JcrUtils.logoutQuietly(targetSession);
+       }
+
+       public void run() {
+
+               try {
+                       // clear target
+                       NodeIterator nit = targetSession.getNode(artifactBasePath)
+                                       .getNodes();
+                       while (nit.hasNext()) {
+                               Node node = nit.nextNode();
+                               if (node.isNodeType(NodeType.NT_FOLDER)
+                                               || node.isNodeType(NodeType.NT_UNSTRUCTURED)) {
+                                       node.remove();
+                                       node.getSession().save();
+                                       if (log.isDebugEnabled())
+                                               log.debug("Cleared " + node);
+                               }
+                       }
+
+                       NodeIterator origArtifacts = listArtifactVersions(origSession);
+                       // process
+                       while (origArtifacts.hasNext()) {
+                               Node origArtifactNode = origArtifacts.nextNode();
+                               if (log.isTraceEnabled())
+                                       log.trace(origArtifactNode);
+
+                               processOrigArtifactVersion(origArtifactNode);
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot perform v1.3 migration from "
+                                       + sourceWorkspace + " to " + targetWorkspace, e);
+               } finally {
+                       JcrUtils.discardQuietly(targetSession);
+               }
+       }
+
+       protected void processOrigArtifactVersion(Node origArtifactNode)
+                       throws RepositoryException, IOException {
+               Artifact origArtifact = RepoUtils.asArtifact(origArtifactNode);
+
+               // skip eclipse artifacts
+               if ((origArtifact.getGroupId().startsWith("org.eclipse") && !(origArtifact
+                               .getArtifactId().equals("org.eclipse.osgi")
+                               || origArtifact.getArtifactId().equals(
+                                               "org.eclipse.osgi.source") || origArtifact
+                               .getArtifactId().startsWith("org.eclipse.rwt.widgets.upload")))
+                               || origArtifact.getArtifactId().startsWith("com.ibm.icu")) {
+                       if (log.isDebugEnabled())
+                               log.debug("Skip " + origArtifact);
+                       return;
+               }
+
+               // skip SpringSource ActiveMQ
+               if (origArtifact.getArtifactId().startsWith(
+                               "com.springsource.org.apache.activemq"))
+                       return;
+
+               String origJarNodeName = MavenConventionsUtils
+                               .artifactFileName(origArtifact);
+               if (!origArtifactNode.hasNode(origJarNodeName))
+                       throw new SlcException("Cannot find jar node for "
+                                       + origArtifactNode);
+               Node origJarNode = origArtifactNode.getNode(origJarNodeName);
+
+               // read MANIFEST
+               Binary manifestBinary = origJarNode.getProperty(SLC_MANIFEST)
+                               .getBinary();
+               Manifest origManifest = new Manifest(manifestBinary.getStream());
+               JcrUtils.closeQuietly(manifestBinary);
+
+               Boolean manifestModified = false;
+               Manifest targetManifest = new Manifest(origManifest);
+
+               // transform symbolic name
+               String origSymbolicName = origManifest.getMainAttributes().getValue(
+                               Constants.BUNDLE_SYMBOLICNAME);
+               final String targetSymbolicName;
+               if (symbolicNamesMapping.containsKey(origSymbolicName)) {
+                       targetSymbolicName = symbolicNamesMapping.get(origSymbolicName);
+               } else if (origSymbolicName.startsWith(SPRING_SOURCE_PREFIX)
+                               && !origSymbolicName.equals(SPRING_SOURCE_PREFIX + ".json")) {
+                       targetSymbolicName = origSymbolicName
+                                       .substring(SPRING_SOURCE_PREFIX.length() + 1);
+               } else {
+                       targetSymbolicName = origSymbolicName;
+               }
+
+               if (!targetSymbolicName.equals(origSymbolicName)) {
+                       targetManifest.getMainAttributes().putValue(
+                                       Constants.BUNDLE_SYMBOLICNAME, targetSymbolicName);
+                       manifestModified = true;
+                       if (log.isDebugEnabled())
+                               log.debug(Constants.BUNDLE_SYMBOLICNAME + " to "
+                                               + targetSymbolicName + " \t\tfrom " + origSymbolicName);
+               }
+
+               // skip excluded bundles
+               if (excludedBundles.contains(targetSymbolicName))
+                       return;
+
+               // check fragment host
+               if (origManifest.getMainAttributes().containsKey(
+                               new Name(Constants.FRAGMENT_HOST))) {
+                       String origFragmentHost = origManifest.getMainAttributes()
+                                       .getValue(Constants.FRAGMENT_HOST);
+                       String targetFragmentHost;
+                       if (symbolicNamesMapping.containsKey(origFragmentHost)) {
+                               targetFragmentHost = symbolicNamesMapping.get(origFragmentHost);
+                       } else if (origFragmentHost.startsWith(SPRING_SOURCE_PREFIX)
+                                       && !origFragmentHost.equals(SPRING_SOURCE_PREFIX + ".json")) {
+                               targetFragmentHost = origFragmentHost
+                                               .substring(SPRING_SOURCE_PREFIX.length() + 1);
+                       } else if (origFragmentHost
+                                       .equals("org.argeo.dep.jacob;bundle-version=\"[1.14.3,1.14.4)\"")) {
+                               // this one for those who think I cannot be pragmatic - mbaudier
+                               targetFragmentHost = "com.jacob;bundle-version=\"[1.14.3,1.14.4)\"";
+                       } else {
+                               targetFragmentHost = origFragmentHost;
+                       }
+
+                       if (!targetFragmentHost.equals(origFragmentHost)) {
+                               targetManifest.getMainAttributes().putValue(
+                                               Constants.FRAGMENT_HOST, targetFragmentHost);
+                               manifestModified = true;
+                               if (log.isDebugEnabled())
+                                       log.debug(Constants.FRAGMENT_HOST + " to "
+                                                       + targetFragmentHost + " from " + origFragmentHost);
+                       }
+               }
+
+               // we assume there is no Require-Bundle in com.springsource.* bundles
+
+               // javax with versions
+               StringBuffer targetImportPackages = new StringBuffer("");
+               NodeIterator origImportPackages = origJarNode.getNodes(SLC_
+                               + Constants.IMPORT_PACKAGE);
+               Boolean importPackagesModified = false;
+               while (origImportPackages.hasNext()) {
+                       Node importPackage = origImportPackages.nextNode();
+                       String pkg = importPackage.getProperty(SLC_NAME).getString();
+                       targetImportPackages.append(pkg);
+                       if (importPackage.hasProperty(SLC_VERSION)) {
+                               String sourceVersion = importPackage.getProperty(SLC_VERSION)
+                                               .getString();
+                               String targetVersion = sourceVersion;
+                               if (systemPackages.contains(pkg)) {
+                                       if (!(sourceVersion.trim().equals("0") || sourceVersion
+                                                       .trim().equals("0.0.0"))) {
+                                               targetVersion = null;
+                                               importPackagesModified = true;
+                                               if (log.isDebugEnabled())
+                                                       log.debug(origSymbolicName
+                                                                       + ": Nullify version of " + pkg + " from "
+                                                                       + sourceVersion);
+                                       }
+                               }
+                               if (targetVersion != null)
+                                       targetImportPackages.append(";version=\"")
+                                                       .append(targetVersion).append("\"");
+                       }
+                       if (importPackage.hasProperty(SLC_OPTIONAL)) {
+                               Boolean optional = importPackage.getProperty(SLC_OPTIONAL)
+                                               .getBoolean();
+                               if (optional)
+                                       targetImportPackages.append(";resolution:=\"optional\"");
+
+                       }
+                       if (origImportPackages.hasNext())
+                               targetImportPackages.append(",");
+               }
+
+               if (importPackagesModified) {
+                       targetManifest.getMainAttributes().putValue(
+                                       Constants.IMPORT_PACKAGE, targetImportPackages.toString());
+                       manifestModified = true;
+               }
+
+               if (!manifestModified && log.isTraceEnabled()) {
+                       log.trace("MANIFEST of " + origSymbolicName + " was not modified");
+               }
+
+               // target coordinates
+               final String targetGroupId;
+               if (origArtifact.getArtifactId().startsWith(
+                               "org.eclipse.rwt.widgets.upload"))
+                       targetGroupId = "org.argeo.tp.rap";
+               else if (origArtifact.getArtifactId().startsWith("org.polymap"))
+                       targetGroupId = "org.argeo.tp.rap";
+               else if (origArtifact.getGroupId().startsWith("org.eclipse")
+                               && !origArtifact.getArtifactId().equals("org.eclipse.osgi"))
+                       throw new SlcException(origArtifact + " should have been excluded");// targetGroupId
+                                                                                                                                                               // =
+                                                                                                                                                               // "org.argeo.tp.eclipse";
+               else
+                       targetGroupId = "org.argeo.tp";
+
+               String targetArtifactId = targetSymbolicName.split(";")[0];
+               Artifact targetArtifact = new DefaultArtifact(targetGroupId,
+                               targetArtifactId, "jar", origArtifact.getVersion());
+               String targetParentPath = MavenConventionsUtils.artifactParentPath(
+                               artifactBasePath, targetArtifact);
+               String targetFileName = MavenConventionsUtils
+                               .artifactFileName(targetArtifact);
+               String targetJarPath = targetParentPath + '/' + targetFileName;
+
+               // copy
+               Node targetParentNode = JcrUtils.mkfolders(targetSession,
+                               targetParentPath);
+               targetSession.save();
+               if (manifestModified) {
+                       Binary origBinary = origJarNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary();
+                       byte[] targetJarBytes = RepoUtils.modifyManifest(
+                                       origBinary.getStream(), targetManifest);
+                       JcrUtils.copyBytesAsFile(targetParentNode, targetFileName,
+                                       targetJarBytes);
+                       JcrUtils.closeQuietly(origBinary);
+               } else {// just copy
+                       targetSession.getWorkspace().copy(sourceWorkspace,
+                                       origJarNode.getPath(), targetJarPath);
+               }
+               targetSession.save();
+
+               // reindex
+               Node targetJarNode = targetSession.getNode(targetJarPath);
+               artifactIndexer.index(targetJarNode);
+               jarFileIndexer.index(targetJarNode);
+
+               targetSession.save();
+
+               // sources
+               Artifact origSourceArtifact = new DefaultArtifact(
+                               origArtifact.getGroupId(), origArtifact.getArtifactId()
+                                               + ".source", "jar", origArtifact.getVersion());
+               String origSourcePath = MavenConventionsUtils.artifactPath(
+                               artifactBasePath, origSourceArtifact);
+               if (origSession.itemExists(origSourcePath)) {
+                       Node origSourceJarNode = origSession.getNode(origSourcePath);
+
+                       Artifact targetSourceArtifact = new DefaultArtifact(targetGroupId,
+                                       targetArtifactId + ".source", "jar",
+                                       origArtifact.getVersion());
+                       String targetSourceParentPath = MavenConventionsUtils
+                                       .artifactParentPath(artifactBasePath, targetSourceArtifact);
+                       String targetSourceFileName = MavenConventionsUtils
+                                       .artifactFileName(targetSourceArtifact);
+                       String targetSourceJarPath = targetSourceParentPath + '/'
+                                       + targetSourceFileName;
+
+                       Node targetSourceParentNode = JcrUtils.mkfolders(targetSession,
+                                       targetSourceParentPath);
+                       targetSession.save();
+
+                       if (!targetSymbolicName.equals(origSymbolicName)) {
+                               Binary origBinary = origSourceJarNode.getNode(Node.JCR_CONTENT)
+                                               .getProperty(Property.JCR_DATA).getBinary();
+                               NameVersion targetNameVersion = RepoUtils
+                                               .readNameVersion(targetManifest);
+                               byte[] targetJarBytes = RepoUtils.packageAsPdeSource(
+                                               origBinary.getStream(), targetNameVersion);
+                               JcrUtils.copyBytesAsFile(targetSourceParentNode,
+                                               targetSourceFileName, targetJarBytes);
+                               JcrUtils.closeQuietly(origBinary);
+                       } else {// just copy
+                               targetSession.getWorkspace().copy(sourceWorkspace,
+                                               origSourceJarNode.getPath(), targetSourceJarPath);
+                       }
+                       targetSession.save();
+
+                       // reindex
+                       Node targetSourceJarNode = targetSession
+                                       .getNode(targetSourceJarPath);
+                       artifactIndexer.index(targetSourceJarNode);
+                       jarFileIndexer.index(targetSourceJarNode);
+
+                       targetSession.save();
+               }
+       }
+
+       /*
+        * UTILITIES
+        */
+
+       static NodeIterator listArtifactVersions(Session session)
+                       throws RepositoryException {
+               QueryManager queryManager = session.getWorkspace().getQueryManager();
+               QueryObjectModelFactory factory = queryManager.getQOMFactory();
+
+               final String artifactVersionsSelector = "artifactVersions";
+               Selector source = factory.selector(SlcTypes.SLC_ARTIFACT_VERSION_BASE,
+                               artifactVersionsSelector);
+
+               Ordering orderByArtifactId = factory.ascending(factory.propertyValue(
+                               artifactVersionsSelector, SlcNames.SLC_ARTIFACT_ID));
+               Ordering[] orderings = { orderByArtifactId };
+
+               QueryObjectModel query = factory.createQuery(source, null, orderings,
+                               null);
+
+               QueryResult result = query.execute();
+               return result.getNodes();
+       }
+
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setSourceWorkspace(String sourceWorkspace) {
+               this.sourceWorkspace = sourceWorkspace;
+       }
+
+       public void setTargetWorkspace(String targetWorkspace) {
+               this.targetWorkspace = targetWorkspace;
+       }
+
+       public void setExcludedBundles(List<String> excludedBundles) {
+               this.excludedBundles = excludedBundles;
+       }
+
+       public void setSymbolicNamesMapping(Map<String, String> symbolicNamesMapping) {
+               this.symbolicNamesMapping = symbolicNamesMapping;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java
new file mode 100644 (file)
index 0000000..ab52c70
--- /dev/null
@@ -0,0 +1,91 @@
+package org.argeo.slc.repo.osgi;
+
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.jar.JarEntry;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.Session;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.OsgiFactory;
+
+public class ArchiveSourcesProvider implements SourcesProvider {
+       private final static Log log = LogFactory
+                       .getLog(ArchiveSourcesProvider.class);
+
+       private OsgiFactory osgiFactory;
+       private String uri;
+       private String base = "";
+
+       @Override
+       public void writeSources(List<String> packages, ZipOutputStream zout) {
+               Session distSession = null;
+               ZipInputStream zin = null;
+               try {
+                       distSession = osgiFactory.openDistSession();
+
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapping " + uri);
+
+                       Node distNode = osgiFactory.getDist(distSession, uri);
+                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
+
+                       // prepare
+                       Set<String> directories = new TreeSet<String>();
+                       for (String pkg : packages)
+                               if (!pkg.equals("META-INF"))
+                                       directories.add(base + pkg.replace('.', '/') + '/');
+
+                       ZipEntry zentry = null;
+                       entries: while ((zentry = zin.getNextEntry()) != null) {
+                               String name = zentry.getName();
+                               if (!name.startsWith(base))
+                                       continue entries;
+
+                               String dirPath = FilenameUtils.getPath(name);
+                               if (name.equals(dirPath))// directory
+                                       continue entries;
+
+                               if (directories.contains(dirPath)) {
+                                       String path = name.substring(base.length());
+                                       zout.putNextEntry(new JarEntry(path));
+                                       IOUtils.copy(zin, zout);
+                                       zin.closeEntry();
+                                       zout.closeEntry();
+                                       continue entries;
+                               }
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot retrieve sources from " + uri, e);
+               } finally {
+                       IOUtils.closeQuietly(zin);
+                       JcrUtils.logoutQuietly(distSession);
+               }
+
+       }
+
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+
+       public void setUri(String uri) {
+               this.uri = uri;
+       }
+
+       public void setBase(String base) {
+               this.base = base;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveWrapper.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArchiveWrapper.java
new file mode 100644 (file)
index 0000000..29fa8f1
--- /dev/null
@@ -0,0 +1,439 @@
+package org.argeo.slc.repo.osgi;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.jar.JarInputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.ModuleSet;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.ArtifactIdComparator;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.build.License;
+import org.argeo.slc.repo.OsgiFactory;
+import org.argeo.slc.repo.RepoUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.util.PathMatcher;
+
+import aQute.lib.osgi.Jar;
+
+/**
+ * Download a software distribution and generates the related OSGi bundles from
+ * the jars, or import them directly if they are already OSGi bundles and don't
+ * need further modification.
+ */
+public class ArchiveWrapper implements Runnable, ModuleSet, Distribution {
+       private final static Log log = LogFactory.getLog(ArchiveWrapper.class);
+
+       private OsgiFactory osgiFactory;
+       private String version;
+       private License license;
+
+       private String uri;
+
+       /** Jars to wrap as OSGi bundles */
+       private Map<String, BndWrapper> wrappers = new HashMap<String, BndWrapper>();
+
+       private SourcesProvider sourcesProvider;
+
+       // pattern of OSGi bundles to import
+       private PathMatcher pathMatcher = new AntPathMatcher();
+       private Map<String, String> includes = new HashMap<String, String>();
+       private List<String> excludes = new ArrayList<String>();
+
+       private Boolean mavenGroupIndexes = false;
+
+       public void init() {
+               for (BndWrapper wrapper : wrappers.values()) {
+                       wrapper.setFactory(this);
+                       if (version != null && wrapper.getVersion() == null)
+                               wrapper.setVersion(version);
+                       if (license != null && wrapper.getLicense() == null)
+                               wrapper.setLicense(license);
+               }
+       }
+
+       public void destroy() {
+
+       }
+
+       public String getDistributionId() {
+               return uri;
+       }
+
+       public Iterator<? extends NameVersion> nameVersions() {
+               if (wrappers.size() > 0)
+                       return wrappers.values().iterator();
+               else
+                       return osgiNameVersions();
+       }
+
+       @SuppressWarnings("resource")
+       protected Iterator<? extends NameVersion> osgiNameVersions() {
+               List<CategorizedNameVersion> nvs = new ArrayList<CategorizedNameVersion>();
+
+               Session distSession = null;
+               ZipInputStream zin = null;
+               try {
+                       distSession = osgiFactory.openDistSession();
+
+                       Node distNode = osgiFactory.getDist(distSession, uri);
+                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
+
+                       ZipEntry zentry = null;
+                       entries: while ((zentry = zin.getNextEntry()) != null) {
+                               String name = zentry.getName();
+                               if (log.isTraceEnabled())
+                                       log.trace("Zip entry " + name);
+                               for (String exclude : excludes)
+                                       if (pathMatcher.match(exclude, name))
+                                               continue entries;
+
+                               for (String include : includes.keySet()) {
+                                       if (pathMatcher.match(include, name)) {
+                                               String groupId = includes.get(include);
+                                               JarInputStream jis = new JarInputStream(zin);
+                                               if (jis.getManifest() == null) {
+                                                       log.warn("No MANIFEST in entry " + name
+                                                                       + ", skipping...");
+                                                       continue entries;
+                                               }
+                                               NameVersion nv = RepoUtils.readNameVersion(jis
+                                                               .getManifest());
+                                               if (nv != null) {
+                                                       if (nv.getName().endsWith(".source"))
+                                                               continue entries;
+                                                       CategorizedNameVersion cnv = new OsgiCategorizedNV(
+                                                                       groupId, nv.getName(), nv.getVersion(),
+                                                                       this);
+                                                       nvs.add(cnv);
+                                                       // no need to process further includes
+                                                       continue entries;
+                                               }
+                                       }
+                               }
+                       }
+                       return nvs.iterator();
+               } catch (Exception e) {
+                       throw new SlcException("Cannot wrap distribution " + uri, e);
+               } finally {
+                       IOUtils.closeQuietly(zin);
+                       JcrUtils.logoutQuietly(distSession);
+               }
+       }
+
+       public void run() {
+               if (mavenGroupIndexes && (version == null))
+                       throw new SlcException(
+                                       "'mavenGroupIndexes' requires 'version' to be set");
+
+               Map<String, Set<Artifact>> binaries = new HashMap<String, Set<Artifact>>();
+               Map<String, Set<Artifact>> sources = new HashMap<String, Set<Artifact>>();
+
+               Session distSession = null;
+               Session javaSession = null;
+               ZipInputStream zin = null;
+               try {
+                       javaSession = osgiFactory.openJavaSession();
+                       distSession = osgiFactory.openDistSession();
+
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapping " + uri);
+                       boolean nothingWasDone = true;
+
+                       Node distNode = osgiFactory.getDist(distSession, uri);
+                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
+
+                       ZipEntry zentry = null;
+                       entries: while ((zentry = zin.getNextEntry()) != null) {
+                               String name = zentry.getName();
+
+                               // sources autodetect
+                               String baseName = FilenameUtils.getBaseName(name);
+                               if (baseName.endsWith("-sources")) {
+                                       String bundle = baseName.substring(0, baseName.length()
+                                                       - "-sources".length());
+                                       // log.debug(name + "," + baseName + ", " + bundle);
+                                       String bundlePath = FilenameUtils.getPath(name) + bundle
+                                                       + ".jar";
+                                       if (wrappers.containsKey(bundlePath)) {
+                                               BndWrapper wrapper = wrappers.get(bundlePath);
+                                               NameVersion bundleNv = new DefaultNameVersion(
+                                                               wrapper.getName(), wrapper.getVersion());
+                                               byte[] pdeSource = RepoUtils.packageAsPdeSource(zin,
+                                                               bundleNv);
+                                               Artifact sourcesArtifact = new DefaultArtifact(
+                                                               wrapper.getCategory(), wrapper.getName()
+                                                                               + ".source", "jar",
+                                                               wrapper.getVersion());
+                                               Node pdeSourceNode = RepoUtils.copyBytesAsArtifact(
+                                                               javaSession.getRootNode(), sourcesArtifact,
+                                                               pdeSource);
+                                               osgiFactory.indexNode(pdeSourceNode);
+                                               pdeSourceNode.getSession().save();
+                                               if (log.isDebugEnabled())
+                                                       log.debug("Added sources " + sourcesArtifact
+                                                                       + " for bundle " + wrapper.getArtifact()
+                                                                       + "from " + name + " in binary archive.");
+                                       }
+
+                               }
+                               // else if (baseName.endsWith(".source")) {
+                               // }
+
+                               // binaries
+                               if (wrappers.containsKey(name)) {
+                                       BndWrapper wrapper = (BndWrapper) wrappers.get(name);
+                                       // we must copy since the stream is closed by BND
+                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
+                                       Artifact artifact = wrapZipEntry(javaSession, zentry,
+                                                       origJarBytes, wrapper);
+                                       nothingWasDone = false;
+                                       addArtifactToIndex(binaries, wrapper.getGroupId(), artifact);
+                               } else {
+                                       for (String wrapperKey : wrappers.keySet())
+                                               if (pathMatcher.match(wrapperKey, name)) {
+                                                       // first matched is taken
+                                                       BndWrapper wrapper = (BndWrapper) wrappers
+                                                                       .get(wrapperKey);
+                                                       // we must copy since the stream is closed by BND
+                                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
+                                                       Artifact artifact = wrapZipEntry(javaSession,
+                                                                       zentry, origJarBytes, wrapper);
+                                                       nothingWasDone = false;
+                                                       addArtifactToIndex(binaries, wrapper.getGroupId(),
+                                                                       artifact);
+                                                       continue entries;
+                                               } else {
+                                                       if (log.isTraceEnabled())
+                                                               log.trace(name + " not matched by "
+                                                                               + wrapperKey);
+                                               }
+
+                                       for (String exclude : excludes)
+                                               if (pathMatcher.match(exclude, name))
+                                                       continue entries;
+
+                                       for (String include : includes.keySet()) {
+                                               if (pathMatcher.match(include, name)) {
+                                                       String groupId = includes.get(include);
+                                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
+                                                       Artifact artifact = importZipEntry(javaSession,
+                                                                       zentry, origJarBytes, groupId);
+                                                       if (artifact == null) {
+                                                               log.warn("Skipped non identified " + zentry);
+                                                               continue entries;
+                                                       }
+                                                       nothingWasDone = false;
+                                                       if (artifact.getArtifactId().endsWith(".source"))
+                                                               addArtifactToIndex(sources, groupId, artifact);
+                                                       else
+                                                               addArtifactToIndex(binaries, groupId, artifact);
+                                                       // no need to process this entry further
+                                                       continue entries;
+                                               }
+                                       }
+                               }
+                       }
+
+                       // indexes
+                       if (mavenGroupIndexes && version != null) {
+                               for (String groupId : binaries.keySet()) {
+                                       RepoUtils.writeGroupIndexes(javaSession, "/", groupId,
+                                                       version, binaries.get(groupId),
+                                                       sources.containsKey(groupId) ? sources.get(groupId)
+                                                                       : null);
+                               }
+                       }
+
+                       if (nothingWasDone)
+                               throw new SlcException("Nothing was done");
+
+                       // FIXME Fail if not all wrappers matched
+               } catch (Exception e) {
+                       throw new SlcException("Cannot wrap distribution " + uri, e);
+               } finally {
+                       IOUtils.closeQuietly(zin);
+                       JcrUtils.logoutQuietly(distSession);
+                       JcrUtils.logoutQuietly(javaSession);
+               }
+       }
+
+       protected Artifact wrapZipEntry(Session javaSession, ZipEntry zentry,
+                       byte[] origJarBytes, BndWrapper wrapper) throws RepositoryException {
+               ByteArrayOutputStream out = null;
+               ByteArrayInputStream in = null;
+               Node newJarNode;
+               Jar jar = null;
+               try {
+                       out = new ByteArrayOutputStream((int) zentry.getSize());
+                       in = new ByteArrayInputStream(origJarBytes);
+                       wrapper.wrapJar(in, out);
+
+                       Artifact artifact = wrapper.getArtifact();
+                       newJarNode = RepoUtils.copyBytesAsArtifact(
+                                       javaSession.getRootNode(), artifact, out.toByteArray());
+                       osgiFactory.indexNode(newJarNode);
+                       newJarNode.getSession().save();
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapped jar " + zentry.getName() + " to "
+                                               + newJarNode.getPath());
+
+                       if (sourcesProvider != null)
+                               addSource(javaSession, artifact, out.toByteArray());
+
+                       return artifact;
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+                       if (jar != null)
+                               jar.close();
+               }
+       }
+
+       protected void addSource(Session javaSession, Artifact artifact,
+                       byte[] binaryJarBytes) {
+               InputStream in = null;
+               ByteArrayOutputStream out = null;
+               Jar jar = null;
+               try {
+                       in = new ByteArrayInputStream(binaryJarBytes);
+                       jar = new Jar(null, in);
+                       List<String> packages = jar.getPackages();
+
+                       out = new ByteArrayOutputStream();
+                       sourcesProvider.writeSources(packages, new ZipOutputStream(out));
+
+                       IOUtils.closeQuietly(in);
+                       in = new ByteArrayInputStream(out.toByteArray());
+                       byte[] sourcesJar = RepoUtils.packageAsPdeSource(
+                                       in,
+                                       new DefaultNameVersion(artifact.getArtifactId(), artifact
+                                                       .getVersion()));
+                       Artifact sourcesArtifact = new DefaultArtifact(
+                                       artifact.getGroupId(),
+                                       artifact.getArtifactId() + ".source", "jar",
+                                       artifact.getVersion());
+                       Node sourcesJarNode = RepoUtils.copyBytesAsArtifact(
+                                       javaSession.getRootNode(), sourcesArtifact, sourcesJar);
+                       sourcesJarNode.getSession().save();
+
+                       if (log.isDebugEnabled())
+                               log.debug("Added sources " + sourcesArtifact + " for bundle "
+                                               + artifact + "from source provider " + sourcesProvider);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot get sources for " + artifact, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+                       if (jar != null)
+                               jar.close();
+               }
+       }
+
+       protected Artifact importZipEntry(Session javaSession, ZipEntry zentry,
+                       byte[] binaryJarBytes, String groupId) throws RepositoryException {
+               ByteArrayInputStream in = null;
+               Node newJarNode;
+               try {
+                       in = new ByteArrayInputStream(binaryJarBytes);
+                       NameVersion nameVersion = RepoUtils.readNameVersion(in);
+                       if (nameVersion == null) {
+                               log.warn("Cannot identify " + zentry.getName());
+                               return null;
+                       }
+                       Artifact artifact = new DefaultArtifact(groupId,
+                                       nameVersion.getName(), "jar", nameVersion.getVersion());
+                       newJarNode = RepoUtils.copyBytesAsArtifact(
+                                       javaSession.getRootNode(), artifact, binaryJarBytes);
+                       osgiFactory.indexNode(newJarNode);
+                       newJarNode.getSession().save();
+                       if (log.isDebugEnabled())
+                               log.debug("Imported OSGi bundle " + zentry.getName() + " to "
+                                               + newJarNode.getPath());
+
+                       if (sourcesProvider != null)
+                               addSource(javaSession, artifact, binaryJarBytes);
+
+                       return artifact;
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+       }
+
+       private void addArtifactToIndex(Map<String, Set<Artifact>> index,
+                       String groupId, Artifact artifact) {
+               if (!index.containsKey(groupId))
+                       index.put(groupId,
+                                       new TreeSet<Artifact>(new ArtifactIdComparator()));
+               index.get(groupId).add(artifact);
+       }
+
+       public void setUri(String uri) {
+               this.uri = uri;
+       }
+
+       public void setWrappers(Map<String, BndWrapper> wrappers) {
+               this.wrappers = wrappers;
+       }
+
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+
+       public void setVersion(String version) {
+               this.version = version;
+       }
+
+       public void setLicense(License license) {
+               this.license = license;
+       }
+
+       public void setPathMatcher(PathMatcher pathMatcher) {
+               this.pathMatcher = pathMatcher;
+       }
+
+       public void setIncludes(Map<String, String> includes) {
+               this.includes = includes;
+       }
+
+       public void setExcludes(List<String> excludes) {
+               this.excludes = excludes;
+       }
+
+       public void setMavenGroupIndexes(Boolean mavenGroupIndexes) {
+               this.mavenGroupIndexes = mavenGroupIndexes;
+       }
+
+       public void setSourcesProvider(SourcesProvider sourcesProvider) {
+               this.sourcesProvider = sourcesProvider;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java
new file mode 100644 (file)
index 0000000..b47da8b
--- /dev/null
@@ -0,0 +1,140 @@
+package org.argeo.slc.repo.osgi;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.ModuleSet;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.execution.ExecutionFlow;
+import org.argeo.slc.repo.ArgeoOsgiDistribution;
+import org.argeo.slc.repo.ArtifactDistribution;
+
+/** A consistent and versioned OSGi distribution, which can be built and tested. */
+public class ArgeoOsgiDistributionImpl extends ArtifactDistribution implements
+               ArgeoOsgiDistribution {
+       private final static Log log = LogFactory
+                       .getLog(ArgeoOsgiDistributionImpl.class);
+
+       private List<Object> modules = new ArrayList<Object>();
+
+       public ArgeoOsgiDistributionImpl(String coords) {
+               super(coords);
+       }
+
+       public void init() {
+               if (log.isDebugEnabled()) {
+                       SortedSet<String> sort = new TreeSet<String>();
+                       Iterator<? extends NameVersion> nvIt = nameVersions();
+                       while (nvIt.hasNext()) {
+                               NameVersion nv = nvIt.next();
+                               sort.add(nv.getName() + ":" + nv.getVersion());
+                       }
+
+                       StringBuffer buf = new StringBuffer(
+                                       "## OSGi FACTORY MANAGED MODULES : \n");
+                       for (String str : sort) {
+                               buf.append(str).append('\n');
+                       }
+
+                       log.debug(buf);
+               }
+       }
+
+       // private static void print(ModuleSet moduleSet, Integer depth) {
+       // StringBuilder prefix = new StringBuilder();
+       // for (int i = 0; i < depth; i++) {
+       // prefix.append(' ');
+       // }
+       // String p = prefix.toString();
+       // prefix.setLength(0);
+       // log.debug(p + "## " + moduleSet.toString());
+       // Iterator<? extends NameVersion> nvIt = moduleSet.nameVersions();
+       // while (nvIt.hasNext()) {
+       // NameVersion nv = nvIt.next();
+       // if (nv instanceof ModuleSet)
+       // print((ModuleSet) nv, depth + 1);
+       // else
+       // log.debug(p + nv);
+       //
+       // }
+       // }
+
+       public void destroy() {
+
+       }
+
+       public Iterator<NameVersion> nameVersions() {
+               List<NameVersion> nameVersions = new ArrayList<NameVersion>();
+               for (Object module : modules) {
+                       // extract runnable from execution flow
+                       if (module instanceof ExecutionFlow) {
+                               for (Iterator<Runnable> it = ((ExecutionFlow) module)
+                                               .runnables(); it.hasNext();) {
+                                       processModule(nameVersions, it.next());
+                               }
+                       }
+                       // module = ((ExecutionFlow) module).getRunnable();
+                       else {
+                               processModule(nameVersions, module);
+                       }
+                       // if (module instanceof ModuleSet)
+                       // addNameVersions(nameVersions, (ModuleSet) module);
+                       // else if (module instanceof NameVersion) {
+                       // NameVersion nv = (NameVersion) module;
+                       // if (!nameVersions.contains(nv))
+                       // nameVersions.add(nv);
+                       // } else
+                       // log.warn("Ignored " + module);
+               }
+               return nameVersions.iterator();
+       }
+
+       private void processModule(List<NameVersion> nameVersions, Object module) {
+               if (module instanceof ModuleSet)
+                       addNameVersions(nameVersions, (ModuleSet) module);
+               else if (module instanceof NameVersion) {
+                       NameVersion nv = (NameVersion) module;
+                       if (!nameVersions.contains(nv))
+                               nameVersions.add(nv);
+               } else
+                       log.warn("Ignored " + module);
+       }
+
+       private void addNameVersions(List<NameVersion> nameVersions,
+                       ModuleSet moduleSet) {
+               Iterator<? extends NameVersion> it = moduleSet.nameVersions();
+               while (it.hasNext()) {
+                       NameVersion nv = it.next();
+                       if (!nameVersions.contains(nv))
+                               nameVersions.add(nv);
+               }
+       }
+
+       // Modular distribution interface methods. Not yet used.
+       public Distribution getModuleDistribution(String moduleName,
+                       String moduleVersion) {
+               // NameVersion searched = new DefaultNameVersion(moduleName,
+               // moduleVersion);
+               // for (Distribution ad : modules) {
+               // if (ad.equals(searched))
+               // return ad;
+               // }
+               return null;
+       }
+
+       public Object getModulesDescriptor(String descriptorType) {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       /* DEPENDENCY INJECTION */
+       public void setModules(List<Object> modules) {
+               this.modules = modules;
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/BndWrapper.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/BndWrapper.java
new file mode 100644 (file)
index 0000000..fce5211
--- /dev/null
@@ -0,0 +1,235 @@
+package org.argeo.slc.repo.osgi;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Properties;
+import java.util.jar.Manifest;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.build.License;
+import org.osgi.framework.Version;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+import org.springframework.beans.factory.BeanNameAware;
+
+import aQute.lib.osgi.Builder;
+import aQute.lib.osgi.Constants;
+import aQute.lib.osgi.Jar;
+
+/** Utilities around the BND library, which manipulates OSGi metadata. */
+public class BndWrapper implements Constants, CategorizedNameVersion,
+               Distribution, BeanNameAware {
+       private final static Log log = LogFactory.getLog(BndWrapper.class);
+
+       private String groupId;
+       private String name;
+       private Properties bndProperties = new Properties();
+
+       private String version;
+       private License license;
+
+       private Boolean doNotModify = false;
+
+       private Runnable factory = null;
+
+       public void wrapJar(InputStream in, OutputStream out) {
+               Builder b = new Builder();
+               Jar jar = null;
+               try {
+                       byte[] jarBytes = IOUtils.toByteArray(in);
+
+                       jar = new Jar(null, new ByteArrayInputStream(jarBytes));
+                       Manifest sourceManifest = jar.getManifest();
+
+                       Version versionToUse;
+                       if (sourceManifest != null) {
+                               // Symbolic name
+                               String sourceSymbolicName = sourceManifest.getMainAttributes()
+                                               .getValue(BUNDLE_SYMBOLICNAME);
+                               if (sourceSymbolicName != null
+                                               && !sourceSymbolicName.equals(name))
+                                       log.info("The new symbolic name ("
+                                                       + name
+                                                       + ") is not consistant with the wrapped bundle symbolic name ("
+                                                       + sourceSymbolicName + ")");
+
+                               // Version
+                               String sourceVersion = sourceManifest.getMainAttributes()
+                                               .getValue(BUNDLE_VERSION);
+                               if (getVersion() == null && sourceVersion == null) {
+                                       throw new SlcException("A bundle version must be defined.");
+                               } else if (getVersion() == null && sourceVersion != null) {
+                                       versionToUse = new Version(sourceVersion);
+                                       version = sourceVersion; // set wrapper version
+                               } else if (getVersion() != null && sourceVersion == null) {
+                                       versionToUse = new Version(getVersion());
+                               } else {// both set
+                                       versionToUse = new Version(getVersion());
+                                       Version sv = new Version(sourceVersion);
+                                       if (versionToUse.getMajor() != sv.getMajor()
+                                                       || versionToUse.getMinor() != sv.getMinor()
+                                                       || versionToUse.getMicro() != sv.getMicro()) {
+                                               log.warn("The new version ("
+                                                               + versionToUse
+                                                               + ") is not consistant with the wrapped bundle version ("
+                                                               + sv + ")");
+                                       }
+                               }
+                       } else {
+                               versionToUse = new Version(getVersion());
+                       }
+
+                       if (doNotModify) {
+                               IOUtils.write(jarBytes, out);
+                               // jar.write(out);
+                       } else {
+
+                               Properties properties = new Properties();
+                               properties.putAll(bndProperties);
+                               properties.setProperty(BUNDLE_SYMBOLICNAME, name);
+                               properties.setProperty(BUNDLE_VERSION, versionToUse.toString());
+
+                               // License
+                               if (license != null) {
+                                       StringBuilder sb = new StringBuilder(license.getUri());
+                                       if (license.getName() != null)
+                                               sb.append(';').append("description=")
+                                                               .append(license.getName());
+                                       if (license.getLink() != null)
+                                               sb.append(';').append("link=")
+                                                               .append(license.getLink());
+                                       properties.setProperty(BUNDLE_LICENSE, sb.toString());
+                                       // TODO add LICENSE.TXT
+                               } else {
+                                       log.warn("No license set for " + toString());
+                               }
+
+                               // b.addIncluded(jarFile);
+                               b.addClasspath(jar);
+
+                               if (log.isDebugEnabled())
+                                       log.debug(properties);
+                               b.setProperties(properties);
+
+                               Jar newJar = b.build();
+                               newJar.write(out);
+                               newJar.close();
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot wrap jar", e);
+               } finally {
+                       b.close();
+                       if (jar != null)
+                               jar.close();
+               }
+
+       }
+
+       public Runnable getFactory() {
+               return factory;
+       }
+
+       public void setFactory(Runnable factory) {
+               if (this.factory != null)
+                       throw new SlcException("Factory already set on " + name);
+               this.factory = factory;
+       }
+
+       public void setName(String bsn) {
+               this.name = bsn;
+       }
+
+       public String getName() {
+               return name;
+       }
+
+       public void setVersion(String version) {
+               if (this.version != null)
+                       throw new SlcException("Version already set on " + name + " ("
+                                       + this.version + ")");
+               this.version = version;
+       }
+
+       public String getVersion() {
+               return version;
+       }
+
+       public License getLicense() {
+               return license;
+       }
+
+       public void setLicense(License license) {
+               if (this.license != null)
+                       throw new SlcException("License already set on " + name);
+               this.license = license;
+       }
+
+       public Properties getBndProperties() {
+               return bndProperties;
+       }
+
+       public void setBndProperties(Properties bndProperties) {
+               this.bndProperties = bndProperties;
+       }
+
+       public void setBeanName(String name) {
+               if (this.name == null) {
+                       this.name = name;
+               } else {
+                       log.warn("Using explicitely set name " + this.name
+                                       + " and not bean name " + name);
+               }
+       }
+
+       public String getGroupId() {
+               return groupId;
+       }
+
+       public String getCategory() {
+               return getGroupId();
+       }
+
+       public void setGroupId(String groupId) {
+               this.groupId = groupId;
+       }
+
+       public String getDistributionId() {
+               return getArtifact().toString();
+       }
+
+       public Artifact getArtifact() {
+               return new DefaultArtifact(groupId, name, "jar", getVersion());
+       }
+
+       @Override
+       public String toString() {
+               return getArtifact().toString();
+       }
+
+       @Override
+       public int hashCode() {
+               return getArtifact().hashCode();
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               if (obj instanceof CategorizedNameVersion) {
+                       CategorizedNameVersion cnv = (CategorizedNameVersion) obj;
+                       return getCategory().equals(cnv.getCategory())
+                                       && getName().equals(cnv.getName())
+                                       && getVersion().equals(cnv.getVersion());
+               } else
+                       return false;
+       }
+
+       public void setDoNotModify(Boolean doNotModify) {
+               this.doNotModify = doNotModify;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ImportBundlesZip.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ImportBundlesZip.java
new file mode 100644 (file)
index 0000000..80574f8
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.osgi;
+
+import java.io.ByteArrayInputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import javax.jcr.Node;
+import javax.jcr.Repository;
+import javax.jcr.Session;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.JarFileIndexer;
+import org.argeo.slc.repo.RepoUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Import all bundles in a zip file (typically an Eclipse distribution) into the
+ * workspace.
+ * 
+ * @deprecated Use {@link ArchiveWrapper} instead.
+ */
+@Deprecated
+public class ImportBundlesZip implements Runnable {
+       private final static Log log = LogFactory.getLog(ImportBundlesZip.class);
+       private Repository repository;
+       private String workspace;
+       private String groupId;
+       private String artifactBasePath = "/";
+
+       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
+       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
+
+       private String zipFile;
+
+       private List<String> excludedBundles = new ArrayList<String>();
+
+       public void run() {
+               ZipInputStream zipIn = null;
+               JarInputStream jarIn = null;
+               Session session = null;
+               try {
+                       URL url = new URL(zipFile);
+                       session = repository.login(workspace);
+
+                       // clear
+                       // String groupPath = MavenConventionsUtils.groupPath(
+                       // artifactBasePath, groupId);
+                       // if (session.itemExists(groupPath)) {
+                       // session.getNode(groupPath).remove();
+                       // session.save();
+                       // if (log.isDebugEnabled())
+                       // log.debug("Cleared " + groupPath);
+                       // }
+
+                       zipIn = new ZipInputStream(url.openStream());
+                       ZipEntry zipEntry = null;
+                       entries: while ((zipEntry = zipIn.getNextEntry()) != null) {
+                               String entryName = zipEntry.getName();
+                               if (!entryName.endsWith(".jar")
+                                               || entryName.contains("feature"))
+                                       continue entries;// skip
+                               byte[] jarBytes = IOUtils.toByteArray(zipIn);
+                               zipIn.closeEntry();
+                               jarIn = new JarInputStream(new ByteArrayInputStream(jarBytes));
+                               Manifest manifest = jarIn.getManifest();
+                               IOUtils.closeQuietly(jarIn);
+                               if (manifest == null) {
+                                       log.warn(entryName + " has no MANIFEST");
+                                       continue entries;
+                               }
+                               NameVersion nv;
+                               try {
+                                       nv = RepoUtils.readNameVersion(manifest);
+                               } catch (Exception e) {
+                                       log.warn("Cannot read name version from " + entryName, e);
+                                       continue entries;
+                               }
+
+                               String bundleName = RepoUtils
+                                               .extractBundleNameFromSourceName(nv.getName());
+                               // skip excluded bundles and their sources
+                               if (excludedBundles.contains(bundleName))
+                                       continue entries;
+                               // for(String excludedBundle:excludedBundles){
+                               // if(bundleName.contains(excludedBundle))
+                               // continue entries;
+                               // }
+
+                               Artifact artifact = new DefaultArtifact(groupId, nv.getName(),
+                                               "jar", nv.getVersion());
+                               Node artifactNode = RepoUtils.copyBytesAsArtifact(
+                                               session.getNode(artifactBasePath), artifact, jarBytes);
+                               jarBytes = null;// superstition, in order to free memory
+
+                               // indexes
+                               artifactIndexer.index(artifactNode);
+                               jarFileIndexer.index(artifactNode);
+                               session.save();
+                               if (log.isDebugEnabled())
+                                       log.debug("Imported " + entryName + " to " + artifactNode);
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot import zip " + zipFile + " to "
+                                       + workspace, e);
+               } finally {
+                       IOUtils.closeQuietly(zipIn);
+                       IOUtils.closeQuietly(jarIn);
+                       JcrUtils.logoutQuietly(session);
+               }
+
+       }
+
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+       public void setGroupId(String groupId) {
+               this.groupId = groupId;
+       }
+
+       public void setArtifactBasePath(String artifactBasePath) {
+               this.artifactBasePath = artifactBasePath;
+       }
+
+       public void setZipFile(String zipFile) {
+               this.zipFile = zipFile;
+       }
+
+       public void setExcludedBundles(List<String> excludedBundles) {
+               this.excludedBundles = excludedBundles;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.6.profile b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.6.profile
new file mode 100644 (file)
index 0000000..68e811f
--- /dev/null
@@ -0,0 +1,194 @@
+###############################################################################
+# Copyright (c) 2003, 2008 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+# 
+# Contributors:
+#     IBM Corporation - initial API and implementation
+###############################################################################
+org.osgi.framework.system.packages = \
+ javax.accessibility,\
+ javax.activation,\
+ javax.activity,\
+ javax.annotation,\
+ javax.annotation.processing,\
+ javax.crypto,\
+ javax.crypto.interfaces,\
+ javax.crypto.spec,\
+ javax.imageio,\
+ javax.imageio.event,\
+ javax.imageio.metadata,\
+ javax.imageio.plugins.bmp,\
+ javax.imageio.plugins.jpeg,\
+ javax.imageio.spi,\
+ javax.imageio.stream,\
+ javax.jws,\
+ javax.jws.soap,\
+ javax.lang.model,\
+ javax.lang.model.element,\
+ javax.lang.model.type,\
+ javax.lang.model.util,\
+ javax.management,\
+ javax.management.loading,\
+ javax.management.modelmbean,\
+ javax.management.monitor,\
+ javax.management.openmbean,\
+ javax.management.relation,\
+ javax.management.remote,\
+ javax.management.remote.rmi,\
+ javax.management.timer,\
+ javax.naming,\
+ javax.naming.directory,\
+ javax.naming.event,\
+ javax.naming.ldap,\
+ javax.naming.spi,\
+ javax.net,\
+ javax.net.ssl,\
+ javax.print,\
+ javax.print.attribute,\
+ javax.print.attribute.standard,\
+ javax.print.event,\
+ javax.rmi,\
+ javax.rmi.CORBA,\
+ javax.rmi.ssl,\
+ javax.script,\
+ javax.security.auth,\
+ javax.security.auth.callback,\
+ javax.security.auth.kerberos,\
+ javax.security.auth.login,\
+ javax.security.auth.spi,\
+ javax.security.auth.x500,\
+ javax.security.cert,\
+ javax.security.sasl,\
+ javax.sound.midi,\
+ javax.sound.midi.spi,\
+ javax.sound.sampled,\
+ javax.sound.sampled.spi,\
+ javax.sql,\
+ javax.sql.rowset,\
+ javax.sql.rowset.serial,\
+ javax.sql.rowset.spi,\
+ javax.swing,\
+ javax.swing.border,\
+ javax.swing.colorchooser,\
+ javax.swing.event,\
+ javax.swing.filechooser,\
+ javax.swing.plaf,\
+ javax.swing.plaf.basic,\
+ javax.swing.plaf.metal,\
+ javax.swing.plaf.multi,\
+ javax.swing.plaf.synth,\
+ javax.swing.table,\
+ javax.swing.text,\
+ javax.swing.text.html,\
+ javax.swing.text.html.parser,\
+ javax.swing.text.rtf,\
+ javax.swing.tree,\
+ javax.swing.undo,\
+ javax.tools,\
+ javax.transaction,\
+ javax.transaction.xa,\
+ javax.xml,\
+ javax.xml.bind,\
+ javax.xml.bind.annotation,\
+ javax.xml.bind.annotation.adapters,\
+ javax.xml.bind.attachment,\
+ javax.xml.bind.helpers,\
+ javax.xml.bind.util,\
+ javax.xml.crypto,\
+ javax.xml.crypto.dom,\
+ javax.xml.crypto.dsig,\
+ javax.xml.crypto.dsig.dom,\
+ javax.xml.crypto.dsig.keyinfo,\
+ javax.xml.crypto.dsig.spec,\
+ javax.xml.datatype,\
+ javax.xml.namespace,\
+ javax.xml.parsers,\
+ javax.xml.soap,\
+ javax.xml.stream,\
+ javax.xml.stream.events,\
+ javax.xml.stream.util,\
+ javax.xml.transform,\
+ javax.xml.transform.dom,\
+ javax.xml.transform.sax,\
+ javax.xml.transform.stax,\
+ javax.xml.transform.stream,\
+ javax.xml.validation,\
+ javax.xml.ws,\
+ javax.xml.ws.handler,\
+ javax.xml.ws.handler.soap,\
+ javax.xml.ws.http,\
+ javax.xml.ws.soap,\
+ javax.xml.ws.spi,\
+ javax.xml.ws.wsaddressing,\
+ javax.xml.xpath,\
+ org.ietf.jgss,\
+ org.omg.CORBA,\
+ org.omg.CORBA_2_3,\
+ org.omg.CORBA_2_3.portable,\
+ org.omg.CORBA.DynAnyPackage,\
+ org.omg.CORBA.ORBPackage,\
+ org.omg.CORBA.portable,\
+ org.omg.CORBA.TypeCodePackage,\
+ org.omg.CosNaming,\
+ org.omg.CosNaming.NamingContextExtPackage,\
+ org.omg.CosNaming.NamingContextPackage,\
+ org.omg.Dynamic,\
+ org.omg.DynamicAny,\
+ org.omg.DynamicAny.DynAnyFactoryPackage,\
+ org.omg.DynamicAny.DynAnyPackage,\
+ org.omg.IOP,\
+ org.omg.IOP.CodecFactoryPackage,\
+ org.omg.IOP.CodecPackage,\
+ org.omg.Messaging,\
+ org.omg.PortableInterceptor,\
+ org.omg.PortableInterceptor.ORBInitInfoPackage,\
+ org.omg.PortableServer,\
+ org.omg.PortableServer.CurrentPackage,\
+ org.omg.PortableServer.POAManagerPackage,\
+ org.omg.PortableServer.POAPackage,\
+ org.omg.PortableServer.portable,\
+ org.omg.PortableServer.ServantLocatorPackage,\
+ org.omg.SendingContext,\
+ org.omg.stub.java.rmi,\
+ org.w3c.dom,\
+ org.w3c.dom.bootstrap,\
+ org.w3c.dom.css,\
+ org.w3c.dom.events,\
+ org.w3c.dom.html,\
+ org.w3c.dom.ls,\
+ org.w3c.dom.ranges,\
+ org.w3c.dom.stylesheets,\
+ org.w3c.dom.traversal,\
+ org.w3c.dom.views,\
+ org.w3c.dom.xpath,\
+ org.xml.sax,\
+ org.xml.sax.ext,\
+ org.xml.sax.helpers
+org.osgi.framework.bootdelegation = \
+ javax.*,\
+ org.ietf.jgss,\
+ org.omg.*,\
+ org.w3c.*,\
+ org.xml.*,\
+ sun.*,\
+ com.sun.*
+org.osgi.framework.executionenvironment = \
+ OSGi/Minimum-1.0,\
+ OSGi/Minimum-1.1,\
+ OSGi/Minimum-1.2,\
+ JRE-1.1,\
+ J2SE-1.2,\
+ J2SE-1.3,\
+ J2SE-1.4,\
+ J2SE-1.5,\
+ JavaSE-1.6
+osgi.java.profile.name = JavaSE-1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.source=1.6
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.7.profile b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/JavaSE-1.7.profile
new file mode 100644 (file)
index 0000000..192b46e
--- /dev/null
@@ -0,0 +1,198 @@
+###############################################################################
+# Copyright (c) 2009, 2010 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+# 
+# Contributors:
+#     IBM Corporation - initial API and implementation
+###############################################################################
+org.osgi.framework.system.packages = \
+ javax.accessibility,\
+ javax.activation,\
+ javax.activity,\
+ javax.annotation,\
+ javax.annotation.processing,\
+ javax.crypto,\
+ javax.crypto.interfaces,\
+ javax.crypto.spec,\
+ javax.imageio,\
+ javax.imageio.event,\
+ javax.imageio.metadata,\
+ javax.imageio.plugins.bmp,\
+ javax.imageio.plugins.jpeg,\
+ javax.imageio.spi,\
+ javax.imageio.stream,\
+ javax.jws,\
+ javax.jws.soap,\
+ javax.lang.model,\
+ javax.lang.model.element,\
+ javax.lang.model.type,\
+ javax.lang.model.util,\
+ javax.management,\
+ javax.management.event,\
+ javax.management.loading,\
+ javax.management.modelmbean,\
+ javax.management.monitor,\
+ javax.management.namespace,\
+ javax.management.openmbean,\
+ javax.management.relation,\
+ javax.management.remote,\
+ javax.management.remote.rmi,\
+ javax.management.timer,\
+ javax.naming,\
+ javax.naming.directory,\
+ javax.naming.event,\
+ javax.naming.ldap,\
+ javax.naming.spi,\
+ javax.net,\
+ javax.net.ssl,\
+ javax.print,\
+ javax.print.attribute,\
+ javax.print.attribute.standard,\
+ javax.print.event,\
+ javax.rmi,\
+ javax.rmi.CORBA,\
+ javax.rmi.ssl,\
+ javax.script,\
+ javax.security.auth,\
+ javax.security.auth.callback,\
+ javax.security.auth.kerberos,\
+ javax.security.auth.login,\
+ javax.security.auth.spi,\
+ javax.security.auth.x500,\
+ javax.security.cert,\
+ javax.security.sasl,\
+ javax.sound.midi,\
+ javax.sound.midi.spi,\
+ javax.sound.sampled,\
+ javax.sound.sampled.spi,\
+ javax.sql,\
+ javax.sql.rowset,\
+ javax.sql.rowset.serial,\
+ javax.sql.rowset.spi,\
+ javax.swing,\
+ javax.swing.border,\
+ javax.swing.colorchooser,\
+ javax.swing.event,\
+ javax.swing.filechooser,\
+ javax.swing.plaf,\
+ javax.swing.plaf.basic,\
+ javax.swing.plaf.metal,\
+ javax.swing.plaf.multi,\
+ javax.swing.plaf.nimbus,\
+ javax.swing.plaf.synth,\
+ javax.swing.table,\
+ javax.swing.text,\
+ javax.swing.text.html,\
+ javax.swing.text.html.parser,\
+ javax.swing.text.rtf,\
+ javax.swing.tree,\
+ javax.swing.undo,\
+ javax.tools,\
+ javax.transaction,\
+ javax.transaction.xa,\
+ javax.xml,\
+ javax.xml.bind,\
+ javax.xml.bind.annotation,\
+ javax.xml.bind.annotation.adapters,\
+ javax.xml.bind.attachment,\
+ javax.xml.bind.helpers,\
+ javax.xml.bind.util,\
+ javax.xml.crypto,\
+ javax.xml.crypto.dom,\
+ javax.xml.crypto.dsig,\
+ javax.xml.crypto.dsig.dom,\
+ javax.xml.crypto.dsig.keyinfo,\
+ javax.xml.crypto.dsig.spec,\
+ javax.xml.datatype,\
+ javax.xml.namespace,\
+ javax.xml.parsers,\
+ javax.xml.soap,\
+ javax.xml.stream,\
+ javax.xml.stream.events,\
+ javax.xml.stream.util,\
+ javax.xml.transform,\
+ javax.xml.transform.dom,\
+ javax.xml.transform.sax,\
+ javax.xml.transform.stax,\
+ javax.xml.transform.stream,\
+ javax.xml.validation,\
+ javax.xml.ws,\
+ javax.xml.ws.handler,\
+ javax.xml.ws.handler.soap,\
+ javax.xml.ws.http,\
+ javax.xml.ws.soap,\
+ javax.xml.ws.spi,\
+ javax.xml.ws.wsaddressing,\
+ javax.xml.xpath,\
+ org.ietf.jgss,\
+ org.omg.CORBA,\
+ org.omg.CORBA_2_3,\
+ org.omg.CORBA_2_3.portable,\
+ org.omg.CORBA.DynAnyPackage,\
+ org.omg.CORBA.ORBPackage,\
+ org.omg.CORBA.portable,\
+ org.omg.CORBA.TypeCodePackage,\
+ org.omg.CosNaming,\
+ org.omg.CosNaming.NamingContextExtPackage,\
+ org.omg.CosNaming.NamingContextPackage,\
+ org.omg.Dynamic,\
+ org.omg.DynamicAny,\
+ org.omg.DynamicAny.DynAnyFactoryPackage,\
+ org.omg.DynamicAny.DynAnyPackage,\
+ org.omg.IOP,\
+ org.omg.IOP.CodecFactoryPackage,\
+ org.omg.IOP.CodecPackage,\
+ org.omg.Messaging,\
+ org.omg.PortableInterceptor,\
+ org.omg.PortableInterceptor.ORBInitInfoPackage,\
+ org.omg.PortableServer,\
+ org.omg.PortableServer.CurrentPackage,\
+ org.omg.PortableServer.POAManagerPackage,\
+ org.omg.PortableServer.POAPackage,\
+ org.omg.PortableServer.portable,\
+ org.omg.PortableServer.ServantLocatorPackage,\
+ org.omg.SendingContext,\
+ org.omg.stub.java.rmi,\
+ org.w3c.dom,\
+ org.w3c.dom.bootstrap,\
+ org.w3c.dom.css,\
+ org.w3c.dom.events,\
+ org.w3c.dom.html,\
+ org.w3c.dom.ls,\
+ org.w3c.dom.ranges,\
+ org.w3c.dom.stylesheets,\
+ org.w3c.dom.traversal,\
+ org.w3c.dom.views,\
+ org.w3c.dom.xpath,\
+ org.xml.sax,\
+ org.xml.sax.ext,\
+ org.xml.sax.helpers
+org.osgi.framework.bootdelegation = \
+ javax.*,\
+ org.ietf.jgss,\
+ org.omg.*,\
+ org.w3c.*,\
+ org.xml.*,\
+ sun.*,\
+ com.sun.*
+org.osgi.framework.executionenvironment = \
+ OSGi/Minimum-1.0,\
+ OSGi/Minimum-1.1,\
+ OSGi/Minimum-1.2,\
+ JRE-1.1,\
+ J2SE-1.2,\
+ J2SE-1.3,\
+ J2SE-1.4,\
+ J2SE-1.5,\
+ JavaSE-1.6,\
+ JavaSE-1.7
+osgi.java.profile.name = JavaSE-1.7
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.source=1.6
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/MavenWrapper.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/MavenWrapper.java
new file mode 100644 (file)
index 0000000..ab7daeb
--- /dev/null
@@ -0,0 +1,131 @@
+package org.argeo.slc.repo.osgi;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.OsgiFactory;
+import org.argeo.slc.repo.RepoUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+import org.sonatype.aether.util.artifact.SubArtifact;
+
+/**
+ * BND wrapper based on a Maven artifact available from one of the configured
+ * repositories.
+ */
+public class MavenWrapper extends BndWrapper implements Runnable {
+       private final static Log log = LogFactory.getLog(MavenWrapper.class);
+
+       private String sourceCoords;
+
+       private OsgiFactory osgiFactory;
+
+       private Boolean doNotModifySources = false;
+
+       public MavenWrapper() {
+               setFactory(this);
+       }
+
+       @Override
+       public String getVersion() {
+               String version = super.getVersion();
+               if (version != null)
+                       return version;
+               return new DefaultArtifact(sourceCoords).getVersion();
+       }
+
+       public void run() {
+               Session distSession = null;
+               Session javaSession = null;
+               InputStream in = null;
+               ByteArrayOutputStream out = null;
+               try {
+                       distSession = osgiFactory.openDistSession();
+                       javaSession = osgiFactory.openJavaSession();
+                       Node origArtifact;
+                       try {
+                               origArtifact = osgiFactory.getMaven(distSession, sourceCoords);
+                       } catch (Exception e1) {
+                               origArtifact = osgiFactory.getMaven(distSession, sourceCoords
+                                               + ":" + getVersion());
+                       }
+
+                       in = origArtifact.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
+                       out = new ByteArrayOutputStream();
+                       wrapJar(in, out);
+                       Node newJarNode = RepoUtils
+                                       .copyBytesAsArtifact(javaSession.getRootNode(),
+                                                       getArtifact(), out.toByteArray());
+                       osgiFactory.indexNode(newJarNode);
+                       newJarNode.getSession().save();
+
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapped Maven " + sourceCoords + " to "
+                                               + newJarNode.getPath());
+
+                       // sources
+                       Artifact sourcesArtifact = new SubArtifact(new DefaultArtifact(
+                                       sourceCoords), "sources", null);
+                       Node sourcesArtifactNode;
+                       try {
+
+                               sourcesArtifactNode = osgiFactory.getMaven(distSession,
+                                               sourcesArtifact.toString());
+                       } catch (SlcException e) {
+                               // no sources available
+                               return;
+                       }
+
+                       IOUtils.closeQuietly(in);
+                       in = sourcesArtifactNode.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
+                       byte[] pdeSource;
+                       if (doNotModifySources)
+                               pdeSource = IOUtils.toByteArray(in);
+                       else
+                               pdeSource = RepoUtils.packageAsPdeSource(in,
+                                               new DefaultNameVersion(getName(), getVersion()));
+                       Node pdeSourceNode = RepoUtils.copyBytesAsArtifact(javaSession
+                                       .getRootNode(), new DefaultArtifact(getCategory(),
+                                       getName() + ".source", "jar", getVersion()), pdeSource);
+                       osgiFactory.indexNode(pdeSourceNode);
+                       pdeSourceNode.getSession().save();
+
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapped Maven " + sourcesArtifact
+                                               + " to PDE sources " + pdeSourceNode.getPath());
+               } catch (Exception e) {
+                       throw new SlcException("Cannot wrap Maven " + sourceCoords, e);
+               } finally {
+                       JcrUtils.logoutQuietly(distSession);
+                       JcrUtils.logoutQuietly(javaSession);
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+               }
+       }
+
+       public void setSourceCoords(String sourceCoords) {
+               this.sourceCoords = sourceCoords;
+       }
+
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+
+       public void setDoNotModifySources(Boolean doNotModifySources) {
+               this.doNotModifySources = doNotModifySources;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/NormalizeGroup.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/NormalizeGroup.java
new file mode 100644 (file)
index 0000000..99f31bb
--- /dev/null
@@ -0,0 +1,507 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.osgi;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.ArtifactIdComparator;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Version;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Make sure that all JCR metadata and Maven metadata are consistent for this
+ * group of OSGi bundles.
+ * 
+ * The job is now done via the various {@code NodeIndexer} of the
+ * WorkspaceManager. TODO import dependencies in the workspace.
+ */
+@Deprecated
+public class NormalizeGroup implements Runnable, SlcNames {
+       private final static Log log = LogFactory.getLog(NormalizeGroup.class);
+
+       private Repository repository;
+       private String workspace;
+       private String groupId;
+       private Boolean overridePoms = false;
+       private String artifactBasePath = "/";
+       private String version = null;
+       private String parentPomCoordinates;
+
+       private List<String> excludedSuffixes = new ArrayList<String>();
+
+       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
+       // private JarFileIndexer jarFileIndexer = new JarFileIndexer();
+
+       /** TODO make it more generic */
+       private List<String> systemPackages = OsgiProfile.PROFILE_JAVA_SE_1_6
+                       .getSystemPackages();
+
+       // indexes
+       private Map<String, String> packagesToSymbolicNames = new HashMap<String, String>();
+       private Map<String, Node> symbolicNamesToNodes = new HashMap<String, Node>();
+
+       private Set<Artifact> binaries = new TreeSet<Artifact>(
+                       new ArtifactIdComparator());
+       private Set<Artifact> sources = new TreeSet<Artifact>(
+                       new ArtifactIdComparator());
+
+       public void run() {
+               Session session = null;
+               try {
+                       session = repository.login(workspace);
+                       Node groupNode = session.getNode(MavenConventionsUtils.groupPath(
+                                       artifactBasePath, groupId));
+                       processGroupNode(groupNode, null);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot normalize group " + groupId + " in "
+                                       + workspace, e);
+               } finally {
+                       JcrUtils.logoutQuietly(session);
+               }
+       }
+
+       public static void processGroupNode(Node groupNode, String version,
+                       Boolean overridePoms, ArgeoMonitor monitor)
+                       throws RepositoryException {
+               // TODO set artifactsBase based on group node
+               NormalizeGroup ng = new NormalizeGroup();
+               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
+                               .getString();
+               ng.setGroupId(groupId);
+               ng.setVersion(version);
+               ng.setOverridePoms(overridePoms);
+               ng.processGroupNode(groupNode, monitor);
+       }
+
+       protected void processGroupNode(Node groupNode, ArgeoMonitor monitor)
+                       throws RepositoryException {
+               if (monitor != null)
+                       monitor.subTask("Group " + groupId);
+               Node allArtifactsHighestVersion = null;
+               Session session = groupNode.getSession();
+               aBases: for (NodeIterator aBases = groupNode.getNodes(); aBases
+                               .hasNext();) {
+                       Node aBase = aBases.nextNode();
+                       if (aBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
+                               Node highestAVersion = null;
+                               for (NodeIterator aVersions = aBase.getNodes(); aVersions
+                                               .hasNext();) {
+                                       Node aVersion = aVersions.nextNode();
+                                       if (aVersion.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
+                                               if (highestAVersion == null) {
+                                                       highestAVersion = aVersion;
+                                                       if (allArtifactsHighestVersion == null)
+                                                               allArtifactsHighestVersion = aVersion;
+
+                                                       // BS will fail if artifacts arrive in this order
+                                                       // Name1 - V1, name2 - V3, V1 will remain the
+                                                       // allArtifactsHighestVersion
+                                                       // Fixed below
+                                                       else {
+                                                               Version currVersion = extractOsgiVersion(aVersion);
+                                                               Version highestVersion = extractOsgiVersion(allArtifactsHighestVersion);
+                                                               if (currVersion.compareTo(highestVersion) > 0)
+                                                                       allArtifactsHighestVersion = aVersion;
+                                                       }
+
+                                               } else {
+                                                       Version currVersion = extractOsgiVersion(aVersion);
+                                                       Version currentHighestVersion = extractOsgiVersion(highestAVersion);
+                                                       if (currVersion.compareTo(currentHighestVersion) > 0) {
+                                                               highestAVersion = aVersion;
+                                                       }
+                                                       if (currVersion
+                                                                       .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
+                                                               allArtifactsHighestVersion = aVersion;
+                                                       }
+                                               }
+
+                                       }
+
+                               }
+                               if (highestAVersion == null)
+                                       continue aBases;
+                               for (NodeIterator files = highestAVersion.getNodes(); files
+                                               .hasNext();) {
+                                       Node file = files.nextNode();
+                                       if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
+                                               preProcessBundleArtifact(file);
+                                               file.getSession().save();
+                                               if (log.isDebugEnabled())
+                                                       log.debug("Pre-processed " + file.getName());
+                                       }
+
+                               }
+                       }
+               }
+
+               // if version not set or empty, use the highest version
+               // useful when indexing a product maven repository where
+               // all artifacts have the same version for a given release
+               // => the version can then be left empty
+               if (version == null || version.trim().equals(""))
+                       if (allArtifactsHighestVersion != null)
+                               version = allArtifactsHighestVersion.getProperty(
+                                               SLC_ARTIFACT_VERSION).getString();
+                       else
+                               version = "0.0";
+               // throw new SlcException("Group version " + version
+               // + " is empty.");
+
+               int bundleCount = symbolicNamesToNodes.size();
+               if (log.isDebugEnabled())
+                       log.debug("Indexed " + bundleCount + " bundles");
+
+               int count = 1;
+               for (Node bundleNode : symbolicNamesToNodes.values()) {
+                       processBundleArtifact(bundleNode);
+                       bundleNode.getSession().save();
+                       if (log.isDebugEnabled())
+                               log.debug(count + "/" + bundleCount + " Processed "
+                                               + bundleNode.getName());
+                       count++;
+               }
+
+               // indexes
+               Set<Artifact> indexes = new TreeSet<Artifact>(
+                               new ArtifactIdComparator());
+               Artifact indexArtifact = writeIndex(session,
+                               RepoConstants.BINARIES_ARTIFACT_ID, binaries);
+               indexes.add(indexArtifact);
+               indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID,
+                               sources);
+               indexes.add(indexArtifact);
+               // sdk
+               writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
+               if (monitor != null)
+                       monitor.worked(1);
+       }
+
+       private Version extractOsgiVersion(Node artifactVersion)
+                       throws RepositoryException {
+               String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
+                               .getString();
+               String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
+               Version osgiVersion = null;
+               // log invalid version value to enable tracking them
+               try {
+                       osgiVersion = new Version(cleanVersion);
+               } catch (IllegalArgumentException e) {
+                       log.error("Version string " + cleanVersion + " is invalid ");
+                       String twickedVersion = twickInvalidVersion(cleanVersion);
+                       osgiVersion = new Version(twickedVersion);
+                       log.error("Using " + twickedVersion + " instead");
+                       // throw e;
+               }
+               return osgiVersion;
+       }
+
+       private String twickInvalidVersion(String tmpVersion) {
+               String[] tokens = tmpVersion.split("\\.");
+               if (tokens.length == 3 && tokens[2].lastIndexOf("-") > 0) {
+                       String newSuffix = tokens[2].replaceFirst("-", ".");
+                       tmpVersion = tmpVersion.replaceFirst(tokens[2], newSuffix);
+               } else if (tokens.length > 4) {
+                       // FIXME manually remove other "."
+                       StringTokenizer st = new StringTokenizer(tmpVersion, ".", true);
+                       StringBuilder builder = new StringBuilder();
+                       // Major
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Minor
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Micro
+                       builder.append(st.nextToken()).append(st.nextToken());
+                       // Qualifier
+                       builder.append(st.nextToken());
+                       while (st.hasMoreTokens()) {
+                               // consume delimiter
+                               st.nextToken();
+                               if (st.hasMoreTokens())
+                                       builder.append("-").append(st.nextToken());
+                       }
+                       tmpVersion = builder.toString();
+               }
+               return tmpVersion;
+       }
+
+       private Artifact writeIndex(Session session, String artifactId,
+                       Set<Artifact> artifacts) throws RepositoryException {
+               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
+                               version);
+               Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
+                               parentPomCoordinates) : null;
+               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
+                               artifacts, parentArtifact);
+               Node node = RepoUtils.copyBytesAsArtifact(
+                               session.getNode(artifactBasePath), artifact, pom.getBytes());
+               artifactIndexer.index(node);
+
+               // TODO factorize
+               String pomSha = JcrUtils.checksumFile(node, "SHA-1");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
+                               pomSha.getBytes());
+               String pomMd5 = JcrUtils.checksumFile(node, "MD5");
+               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
+                               pomMd5.getBytes());
+               session.save();
+               return artifact;
+       }
+
+       protected void preProcessBundleArtifact(Node bundleNode)
+                       throws RepositoryException {
+
+               String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
+               if (symbolicName.endsWith(".source")) {
+                       // TODO make a shared node with classifier 'sources'?
+                       String bundleName = RepoUtils
+                                       .extractBundleNameFromSourceName(symbolicName);
+                       for (String excludedSuffix : excludedSuffixes) {
+                               if (bundleName.endsWith(excludedSuffix))
+                                       return;// skip adding to sources
+                       }
+                       sources.add(RepoUtils.asArtifact(bundleNode));
+                       return;
+               }
+
+               NodeIterator exportPackages = bundleNode.getNodes(SLC_
+                               + Constants.EXPORT_PACKAGE);
+               while (exportPackages.hasNext()) {
+                       Node exportPackage = exportPackages.nextNode();
+                       String pkg = JcrUtils.get(exportPackage, SLC_NAME);
+                       packagesToSymbolicNames.put(pkg, symbolicName);
+               }
+
+               symbolicNamesToNodes.put(symbolicName, bundleNode);
+               for (String excludedSuffix : excludedSuffixes) {
+                       if (symbolicName.endsWith(excludedSuffix))
+                               return;// skip adding to binaries
+               }
+               binaries.add(RepoUtils.asArtifact(bundleNode));
+
+               if (bundleNode.getSession().hasPendingChanges())
+                       bundleNode.getSession().save();
+       }
+
+       protected void processBundleArtifact(Node bundleNode)
+                       throws RepositoryException {
+               Node artifactFolder = bundleNode.getParent();
+               String baseName = FilenameUtils.getBaseName(bundleNode.getName());
+
+               // pom
+               String pomName = baseName + ".pom";
+               if (artifactFolder.hasNode(pomName) && !overridePoms)
+                       return;// skip
+
+               String pom = generatePomForBundle(bundleNode);
+               Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
+                               pom.getBytes());
+               // checksum
+               String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
+               JcrUtils.copyBytesAsFile(artifactFolder,
+                               bundleNode.getName() + ".sha1", bundleSha.getBytes());
+               String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
+               JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
+                               pomSha.getBytes());
+       }
+
+       private String generatePomForBundle(Node n) throws RepositoryException {
+               String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
+
+               StringBuffer p = new StringBuffer();
+
+               // XML header
+               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
+               p.append("<modelVersion>4.0.0</modelVersion>");
+
+               // Artifact
+               p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
+                               .append("</groupId>\n");
+               p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
+                               .append("</artifactId>\n");
+               p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
+                               .append("</version>\n");
+               p.append("<packaging>pom</packaging>\n");
+               if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
+                       p.append("<name>")
+                                       .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
+                                       .append("</name>\n");
+               if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
+                       p.append("<description>")
+                                       .append(JcrUtils
+                                                       .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
+                                       .append("</description>\n");
+
+               // Dependencies
+               Set<String> dependenciesSymbolicNames = new TreeSet<String>();
+               Set<String> optionalSymbolicNames = new TreeSet<String>();
+               NodeIterator importPackages = n.getNodes(SLC_
+                               + Constants.IMPORT_PACKAGE);
+               while (importPackages.hasNext()) {
+                       Node importPackage = importPackages.nextNode();
+                       String pkg = JcrUtils.get(importPackage, SLC_NAME);
+                       if (packagesToSymbolicNames.containsKey(pkg)) {
+                               String dependencySymbolicName = packagesToSymbolicNames
+                                               .get(pkg);
+                               if (JcrUtils.check(importPackage, SLC_OPTIONAL))
+                                       optionalSymbolicNames.add(dependencySymbolicName);
+                               else
+                                       dependenciesSymbolicNames.add(dependencySymbolicName);
+                       } else {
+                               if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
+                                               && !systemPackages.contains(pkg))
+                                       log.warn("No bundle found for pkg " + pkg);
+                       }
+               }
+
+               if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
+                       String fragmentHost = JcrUtils.get(
+                                       n.getNode(SLC_ + Constants.FRAGMENT_HOST),
+                                       SLC_SYMBOLIC_NAME);
+                       dependenciesSymbolicNames.add(fragmentHost);
+               }
+
+               // TODO require bundles
+
+               List<Node> dependencyNodes = new ArrayList<Node>();
+               for (String depSymbName : dependenciesSymbolicNames) {
+                       if (depSymbName.equals(ownSymbolicName))
+                               continue;// skip self
+
+                       if (symbolicNamesToNodes.containsKey(depSymbName))
+                               dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
+                       else
+                               log.warn("Could not find node for " + depSymbName);
+               }
+               List<Node> optionalDependencyNodes = new ArrayList<Node>();
+               for (String depSymbName : optionalSymbolicNames) {
+                       if (symbolicNamesToNodes.containsKey(depSymbName))
+                               optionalDependencyNodes.add(symbolicNamesToNodes
+                                               .get(depSymbName));
+                       else
+                               log.warn("Could not find node for " + depSymbName);
+               }
+
+               p.append("<dependencies>\n");
+               for (Node dependencyNode : dependencyNodes) {
+                       p.append("<dependency>\n");
+                       p.append("\t<groupId>")
+                                       .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
+                                       .append("</groupId>\n");
+                       p.append("\t<artifactId>")
+                                       .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
+                                       .append("</artifactId>\n");
+                       p.append("</dependency>\n");
+               }
+
+               if (optionalDependencyNodes.size() > 0)
+                       p.append("<!-- OPTIONAL -->\n");
+               for (Node dependencyNode : optionalDependencyNodes) {
+                       p.append("<dependency>\n");
+                       p.append("\t<groupId>")
+                                       .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
+                                       .append("</groupId>\n");
+                       p.append("\t<artifactId>")
+                                       .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
+                                       .append("</artifactId>\n");
+                       p.append("\t<optional>true</optional>\n");
+                       p.append("</dependency>\n");
+               }
+               p.append("</dependencies>\n");
+
+               // Dependency management
+               p.append("<dependencyManagement>\n");
+               p.append("<dependencies>\n");
+               p.append("<dependency>\n");
+               p.append("\t<groupId>").append(groupId).append("</groupId>\n");
+               p.append("\t<artifactId>")
+                               .append(ownSymbolicName.endsWith(".source") ? RepoConstants.SOURCES_ARTIFACT_ID
+                                               : RepoConstants.BINARIES_ARTIFACT_ID)
+                               .append("</artifactId>\n");
+               p.append("\t<version>").append(version).append("</version>\n");
+               p.append("\t<type>pom</type>\n");
+               p.append("\t<scope>import</scope>\n");
+               p.append("</dependency>\n");
+               p.append("</dependencies>\n");
+               p.append("</dependencyManagement>\n");
+
+               p.append("</project>\n");
+               return p.toString();
+       }
+
+       /* DEPENDENCY INJECTION */
+       public void setRepository(Repository repository) {
+               this.repository = repository;
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+       public void setGroupId(String groupId) {
+               this.groupId = groupId;
+       }
+
+       public void setParentPomCoordinates(String parentPomCoordinates) {
+               this.parentPomCoordinates = parentPomCoordinates;
+       }
+
+       public void setArtifactBasePath(String artifactBasePath) {
+               this.artifactBasePath = artifactBasePath;
+       }
+
+       public void setVersion(String version) {
+               this.version = version;
+       }
+
+       public void setExcludedSuffixes(List<String> excludedSuffixes) {
+               this.excludedSuffixes = excludedSuffixes;
+       }
+
+       public void setOverridePoms(Boolean overridePoms) {
+               this.overridePoms = overridePoms;
+       }
+
+       public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
+               this.artifactIndexer = artifactIndexer;
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ObrWrapper.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ObrWrapper.java
new file mode 100644 (file)
index 0000000..d44593b
--- /dev/null
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.osgi;
+
+public class ObrWrapper {
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java
new file mode 100644 (file)
index 0000000..0d75d25
--- /dev/null
@@ -0,0 +1,29 @@
+package org.argeo.slc.repo.osgi;
+
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.DefaultNameVersion;
+
+class OsgiCategorizedNV extends DefaultNameVersion implements
+               CategorizedNameVersion, Runnable {
+       private String category;
+       /** Build runnable */
+       private Runnable build;
+
+       public OsgiCategorizedNV(String category, String name, String version,
+                       Runnable build) {
+               super(name, version);
+               this.category = category;
+               this.build = build;
+       }
+
+       public String getCategory() {
+               return category;
+       }
+
+       @Override
+       public void run() {
+               if (build != null)
+                       build.run();
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java
new file mode 100644 (file)
index 0000000..bd4f431
--- /dev/null
@@ -0,0 +1,250 @@
+package org.argeo.slc.repo.osgi;
+
+import java.io.BufferedInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.jcr.Node;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcConstants;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.NodeIndexer;
+import org.argeo.slc.repo.OsgiFactory;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/** Default implementation of {@link OsgiFactory}. */
+public class OsgiFactoryImpl implements OsgiFactory, SlcNames {
+       private final static Log log = LogFactory.getLog(OsgiFactoryImpl.class);
+
+       private String workspace;
+       private Repository distRepository;
+       private Repository javaRepository;
+
+       private List<NodeIndexer> nodeIndexers = new ArrayList<NodeIndexer>();
+
+       /** key is URI prefix, value list of base URLs */
+       private Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
+
+       private List<String> mavenRepositories = new ArrayList<String>();
+       private String mavenProxyBase = "/mavenProxy";
+
+       public void init() {
+               if (workspace == null)
+                       throw new SlcException("A workspace must be specified");
+
+               // default Maven repo
+               if (mavenRepositories.size() == 0) {
+                       // mavenRepositories
+                       // .add("http://search.maven.org/remotecontent?filepath=");
+                       mavenRepositories.add("http://repo1.maven.org/maven2");
+               }
+
+               Session javaSession = null;
+               Session distSession = null;
+               try {
+                       // TODO rather user a JavaRepoManager that will also implicitely
+                       // manage the indexing of newly created nodes.
+                       javaSession = JcrUtils.loginOrCreateWorkspace(javaRepository,
+                                       workspace);
+                       distSession = JcrUtils.loginOrCreateWorkspace(distRepository,
+                                       workspace);
+
+                       // Privileges
+                       JcrUtils.addPrivilege(javaSession, "/", SlcConstants.ROLE_SLC,
+                                       "jcr:all");
+                       JcrUtils.addPrivilege(distSession, "/", SlcConstants.ROLE_SLC,
+                                       "jcr:all");
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot initialize OSGi Factory "
+                                       + workspace, e);
+               } finally {
+                       JcrUtils.logoutQuietly(javaSession);
+                       JcrUtils.logoutQuietly(distSession);
+               }
+       }
+
+       public void destroy() {
+
+       }
+
+       public Session openJavaSession() throws RepositoryException {
+               return javaRepository.login(workspace);
+       }
+
+       public Session openDistSession() throws RepositoryException {
+               return distRepository.login(workspace);
+       }
+
+       public void indexNode(Node node) {
+               for (NodeIndexer nodeIndexer : nodeIndexers) {
+                       nodeIndexer.index(node);
+               }
+       }
+
+       public Node getMaven(Session distSession, String coords)
+                       throws RepositoryException {
+               Artifact artifact = new DefaultArtifact(coords);
+               String path = MavenConventionsUtils.artifactPath(mavenProxyBase,
+                               artifact);
+
+               // exists
+               if (distSession.itemExists(path))
+                       return distSession.getNode(path);
+
+               for (String mavenRepo : mavenRepositories) {
+                       String url = mavenRepo
+                                       + MavenConventionsUtils.artifactPath("/", artifact);
+                       try {
+                               Node node = loadUrlToPath(url, distSession, path);
+                               if (node != null) {
+                                       // checksums
+                                       try {
+                                               loadUrlToPath(url + ".md5", distSession, path + ".md5");
+                                       } catch (FileNotFoundException e) {
+                                               // silent
+                                       }
+                                       try {
+                                               loadUrlToPath(url + ".sha1", distSession, path
+                                                               + ".sha1");
+                                       } catch (FileNotFoundException e) {
+                                               // silent
+                                       }
+                                       return node;
+                               }
+                       } catch (FileNotFoundException e) {
+                               if (log.isDebugEnabled())
+                                       log.debug("Maven " + coords
+                                                       + " could not be downloaded from " + url);
+                       }
+               }
+               throw new SlcException("Could not download Maven " + coords);
+       }
+
+       public Node getDist(Session distSession, String uri)
+                       throws RepositoryException {
+               String distPath = '/' + JcrUtils.urlAsPath(uri);
+
+               // already retrieved
+               if (distSession.itemExists(distPath))
+                       return distSession.getNode(distPath);
+
+               // find mirror
+               List<String> urlBases = null;
+               String uriPrefix = null;
+               uriPrefixes: for (String uriPref : mirrors.keySet()) {
+                       if (uri.startsWith(uriPref)) {
+                               if (mirrors.get(uriPref).size() > 0) {
+                                       urlBases = mirrors.get(uriPref);
+                                       uriPrefix = uriPref;
+                                       break uriPrefixes;
+                               }
+                       }
+               }
+               if (urlBases == null)
+                       try {
+                               return loadUrlToPath(uri, distSession, distPath);
+                       } catch (FileNotFoundException e) {
+                               throw new SlcException("Cannot download " + uri, e);
+                       }
+
+               // try to download
+               for (String urlBase : urlBases) {
+                       String relativePath = uri.substring(uriPrefix.length());
+                       String url = urlBase + relativePath;
+                       try {
+                               return loadUrlToPath(url, distSession, distPath);
+                       } catch (FileNotFoundException e) {
+                               if (log.isDebugEnabled())
+                                       log.debug("Cannot download " + url
+                                                       + ", trying another mirror");
+                       }
+               }
+
+               throw new SlcException("Could not download " + uri);
+       }
+
+       /** Actually downloads a file to an internal location */
+       protected Node loadUrlToPath(String url, Session distSession, String path)
+                       throws RepositoryException, FileNotFoundException {
+               if (log.isDebugEnabled())
+                       log.debug("Downloading " + url + "...");
+
+               InputStream in = null;
+               URLConnection conn = null;
+               Node folderNode = JcrUtils.mkfolders(distSession,
+                               JcrUtils.parentPath(path));
+               try {
+                       URL u = new URL(url);
+                       conn = u.openConnection();
+                       conn.connect();
+                       in = new BufferedInputStream(conn.getInputStream());
+                       // byte[] arr = IOUtils.toByteArray(in);
+                       // Node fileNode = JcrUtils.copyBytesAsFile(folderNode,
+                       // JcrUtils.nodeNameFromPath(path), arr);
+                       Node fileNode = JcrUtils.copyStreamAsFile(folderNode,
+                                       JcrUtils.nodeNameFromPath(path), in);
+                       fileNode.addMixin(SlcTypes.SLC_KNOWN_ORIGIN);
+                       Node origin = fileNode.addNode(SLC_ORIGIN, SlcTypes.SLC_PROXIED);
+                       JcrUtils.urlToAddressProperties(origin, url);
+                       distSession.save();
+                       return fileNode;
+               } catch (MalformedURLException e) {
+                       throw new SlcException("URL " + url + " not valid.", e);
+               } catch (FileNotFoundException e) {
+                       throw e;
+               } catch (IOException e) {
+                       throw new SlcException("Cannot load " + url + " to " + path, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+
+       }
+
+       public void setWorkspace(String workspace) {
+               this.workspace = workspace;
+       }
+
+       public void setDistRepository(Repository distRepository) {
+               this.distRepository = distRepository;
+       }
+
+       public void setJavaRepository(Repository javaRepository) {
+               this.javaRepository = javaRepository;
+       }
+
+       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
+               this.nodeIndexers = nodeIndexers;
+       }
+
+       public void setMirrors(Map<String, List<String>> mirrors) {
+               this.mirrors = mirrors;
+       }
+
+       public void setMavenRepositories(List<String> mavenRepositories) {
+               this.mavenRepositories = mavenRepositories;
+       }
+
+       public void setMavenProxyBase(String mavenProxyBase) {
+               this.mavenProxyBase = mavenProxyBase;
+       }
+
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiProfile.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/OsgiProfile.java
new file mode 100644 (file)
index 0000000..50f87be
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.repo.osgi;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.commons.io.IOUtils;
+import org.argeo.slc.SlcException;
+
+/**
+ * Wraps an OSGi profile, simplifying access to its values such as system
+ * packages, etc.
+ */
+public class OsgiProfile {
+       public final static String PROP_SYSTEM_PACKAGES = "org.osgi.framework.system.packages";
+
+       public final static OsgiProfile PROFILE_JAVA_SE_1_6 = new OsgiProfile(
+                       "JavaSE-1.6.profile");
+
+       private final URL url;
+       private final Properties properties;
+
+       public OsgiProfile(URL url) {
+               this.url = url;
+               properties = new Properties();
+               InputStream in = null;
+               try {
+                       properties.load(this.url.openStream());
+               } catch (Exception e) {
+                       throw new SlcException("Cannot initalize OSGi profile " + url, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+       }
+
+       public OsgiProfile(String name) {
+               this(OsgiProfile.class.getClassLoader().getResource(
+                               '/'
+                                               + OsgiProfile.class.getPackage().getName()
+                                                               .replace('.', '/') + '/' + name));
+       }
+
+       public List<String> getSystemPackages() {
+               String[] splitted = properties.getProperty(PROP_SYSTEM_PACKAGES).split(
+                               ",");
+               List<String> res = new ArrayList<String>();
+               for (String pkg : splitted) {
+                       res.add(pkg.trim());
+               }
+               return Collections.unmodifiableList(res);
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ProcessDistribution.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/ProcessDistribution.java
new file mode 100644 (file)
index 0000000..d16a797
--- /dev/null
@@ -0,0 +1,96 @@
+package org.argeo.slc.repo.osgi;
+
+import java.util.Iterator;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.CategorizedNameVersion;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.ArgeoOsgiDistribution;
+import org.argeo.slc.repo.ModularDistributionFactory;
+import org.argeo.slc.repo.OsgiFactory;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/** Executes the processes required so that all managed bundles are available. */
+public class ProcessDistribution implements Runnable {
+       private final static Log log = LogFactory.getLog(ProcessDistribution.class);
+
+       private ArgeoOsgiDistribution osgiDistribution;
+       private OsgiFactory osgiFactory;
+
+       public void run() {
+               Session javaSession = null;
+               try {
+                       javaSession = osgiFactory.openJavaSession();
+                       for (Iterator<? extends NameVersion> it = osgiDistribution
+                                       .nameVersions(); it.hasNext();)
+                               processNameVersion(javaSession, it.next());
+
+                       // Check sources
+                       for (Iterator<? extends NameVersion> it = osgiDistribution
+                                       .nameVersions(); it.hasNext();) {
+                               CategorizedNameVersion nv = (CategorizedNameVersion) it.next();
+                               Artifact artifact = new DefaultArtifact(nv.getCategory(),
+                                               nv.getName() + ".source", "jar", nv.getVersion());
+                               String path = MavenConventionsUtils.artifactPath("/", artifact);
+                               if (!javaSession.itemExists(path))
+                                       log.warn("No source available for " + nv);
+                       }
+
+                       // explicitly create the corresponding modular distribution as we
+                       // have here all necessary info.
+                       ModularDistributionFactory mdf = new ModularDistributionFactory(
+                                       osgiFactory, osgiDistribution);
+                       mdf.run();
+
+               } catch (RepositoryException e) {
+                       throw new SlcException("Cannot process distribution "
+                                       + osgiDistribution, e);
+               } finally {
+                       JcrUtils.logoutQuietly(javaSession);
+               }
+       }
+
+       protected void processNameVersion(Session javaSession,
+                       NameVersion nameVersion) throws RepositoryException {
+               if (log.isTraceEnabled())
+                       log.trace("Check " + nameVersion + "...");
+               if (!(nameVersion instanceof CategorizedNameVersion))
+                       throw new SlcException("Unsupported type " + nameVersion.getClass());
+               CategorizedNameVersion nv = (CategorizedNameVersion) nameVersion;
+               Artifact artifact = new DefaultArtifact(nv.getCategory(), nv.getName(),
+                               "jar", nv.getVersion());
+               String path = MavenConventionsUtils.artifactPath("/", artifact);
+               if (!javaSession.itemExists(path)) {
+                       if (nv instanceof BndWrapper) {
+                               if (log.isDebugEnabled())
+                                       log.debug("Run factory for   : " + nv + "...");
+                               ((BndWrapper) nv).getFactory().run();
+                       } else if (nv instanceof Runnable) {
+                               ((Runnable) nv).run();
+                       } else {
+                               log.warn("Skip unsupported   : " + nv);
+                       }
+               } else {
+                       if (log.isTraceEnabled())
+                               log.trace("Already available : " + nv);
+               }
+       }
+
+       /* DEPENDENCY INJECTION */
+       public void setOsgiDistribution(ArgeoOsgiDistribution osgiDistribution) {
+               this.osgiDistribution = osgiDistribution;
+       }
+
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+}
\ No newline at end of file
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/SourcesProvider.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/SourcesProvider.java
new file mode 100644 (file)
index 0000000..a0a20f6
--- /dev/null
@@ -0,0 +1,17 @@
+package org.argeo.slc.repo.osgi;
+
+import java.util.List;
+import java.util.zip.ZipOutputStream;
+
+/** Provides access to Java sources */
+public interface SourcesProvider {
+       /**
+        * Writes sources into a ZIP (or a JAR), under the same sirectory structure.
+        * 
+        * @param packages
+        *            the packages to import
+        * @param out
+        *            the ZIP or JAR to write to
+        */
+       public void writeSources(List<String> packages, ZipOutputStream zout);
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/UriWrapper.java b/org.argeo.slc.repo/src/org/argeo/slc/repo/osgi/UriWrapper.java
new file mode 100644 (file)
index 0000000..cf0422e
--- /dev/null
@@ -0,0 +1,128 @@
+package org.argeo.slc.repo.osgi;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.List;
+import java.util.zip.ZipOutputStream;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.Session;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.DefaultNameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.OsgiFactory;
+import org.argeo.slc.repo.RepoUtils;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+import aQute.lib.osgi.Jar;
+
+public class UriWrapper extends BndWrapper implements Runnable {
+       private final static Log log = LogFactory.getLog(UriWrapper.class);
+
+       private String uri;
+       private String baseUri;
+       private String versionSeparator = "-";
+       private String extension = "jar";
+
+       private OsgiFactory osgiFactory;
+
+       private SourcesProvider sourcesProvider;
+
+       public UriWrapper() {
+               setFactory(this);
+       }
+
+       public void run() {
+               Session distSession = null;
+               Session javaSession = null;
+               InputStream in = null;
+               ByteArrayOutputStream out = null;
+               Jar jar = null;
+               try {
+                       distSession = osgiFactory.openDistSession();
+                       javaSession = osgiFactory.openJavaSession();
+                       if (uri == null) {
+                               uri = baseUri + '/' + getName() + versionSeparator
+                                               + getVersion() + "." + extension;
+                       }
+                       Node sourceArtifact = osgiFactory.getDist(distSession, uri);
+
+                       // TODO factorize with Maven
+                       in = sourceArtifact.getNode(Node.JCR_CONTENT)
+                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
+                       out = new ByteArrayOutputStream();
+                       wrapJar(in, out);
+                       Node newJarNode = RepoUtils
+                                       .copyBytesAsArtifact(javaSession.getRootNode(),
+                                                       getArtifact(), out.toByteArray());
+                       osgiFactory.indexNode(newJarNode);
+                       newJarNode.getSession().save();
+                       if (log.isDebugEnabled())
+                               log.debug("Wrapped " + uri + " to " + newJarNode.getPath());
+
+                       // sources
+                       if (sourcesProvider != null) {
+                               IOUtils.closeQuietly(in);
+                               in = new ByteArrayInputStream(out.toByteArray());
+                               jar = new Jar(null, in);
+                               List<String> packages = jar.getPackages();
+
+                               IOUtils.closeQuietly(out);
+                               out = new ByteArrayOutputStream();
+                               sourcesProvider
+                                               .writeSources(packages, new ZipOutputStream(out));
+
+                               IOUtils.closeQuietly(in);
+                               in = new ByteArrayInputStream(out.toByteArray());
+                               byte[] sourcesJar = RepoUtils.packageAsPdeSource(in,
+                                               new DefaultNameVersion(this));
+                               Artifact sourcesArtifact = new DefaultArtifact(getArtifact()
+                                               .getGroupId(), getArtifact().getArtifactId()
+                                               + ".source", "jar", getArtifact().getVersion());
+                               Node sourcesJarNode = RepoUtils.copyBytesAsArtifact(
+                                               javaSession.getRootNode(), sourcesArtifact, sourcesJar);
+                               sourcesJarNode.getSession().save();
+
+                               if (log.isDebugEnabled())
+                                       log.debug("Added sources " + sourcesArtifact
+                                                       + " for bundle " + getArtifact());
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot wrap URI " + uri, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+                       JcrUtils.logoutQuietly(distSession);
+                       JcrUtils.logoutQuietly(javaSession);
+                       if (jar != null)
+                               jar.close();
+               }
+       }
+
+       public void setUri(String sourceCoords) {
+               this.uri = sourceCoords;
+       }
+
+       public void setOsgiFactory(OsgiFactory osgiFactory) {
+               this.osgiFactory = osgiFactory;
+       }
+
+       public void setBaseUri(String baseUri) {
+               this.baseUri = baseUri;
+       }
+
+       public void setVersionSeparator(String versionSeparator) {
+               this.versionSeparator = versionSeparator;
+       }
+
+       public void setSourcesProvider(SourcesProvider sourcesProvider) {
+               this.sourcesProvider = sourcesProvider;
+       }
+}
diff --git a/org.argeo.slc.repo/src/org/argeo/slc/repo/repo.cnd b/org.argeo.slc.repo/src/org/argeo/slc/repo/repo.cnd
new file mode 100644 (file)
index 0000000..271e85e
--- /dev/null
@@ -0,0 +1,160 @@
+<slc = 'http://www.argeo.org/ns/slc'>
+
+// AETHER
+[slc:artifact] > mix:referenceable, mix:created, mix:lastModified
+mixin
+- slc:artifactId (STRING) m
+- slc:groupId (STRING) m
+- slc:artifactVersion (STRING) m
+- slc:artifactExtension (STRING) m
+- slc:artifactClassifier (STRING) ='' m a
+
+[slc:artifactVersion] > mix:referenceable, mix:created, mix:lastModified, mix:title
+mixin
+- slc:artifactId (STRING) m
+- slc:groupId (STRING) m
+- slc:artifactVersion (STRING) m
+
+[slc:artifactBase] > mix:referenceable, mix:created, mix:lastModified
+mixin
+- slc:artifactId (STRING) m
+- slc:groupId (STRING) m
+
+[slc:groupBase] > mix:referenceable, mix:created, mix:lastModified
+mixin
+// it is possible to have groupBase being artifact base (e.g. org.argeo.commons.basic)
+// so using groupId would conflict 
+- slc:groupBaseId (STRING) m
+
+// Mark a given group base as relevant to create modular distribution in the current workspace  
+// [slc:category]
+// mixin
+
+[slc:distribution] > slc:artifactVersion
+mixin
++ slc:artifactVersions (argeo:references) m
+
+
+[slc:modularDistributionBase]
+mixin
+
+// Question: Extend slc:categorizedNameVersion ? (not possible without migration)
+[slc:modularDistribution] 
+mixin
++ slc:modules (nt:unstructured) m
+
+[slc:moduleCoordinates] > nt:unstructured
+- slc:category (STRING)
+- slc:name (STRING)
+- slc:version (STRING)
+
+
+// ORIGINS
+[slc:knownOrigin] > nt:base
+mixin
++ slc:origin (nt:address)
+
+[slc:proxied] > nt:address
+- slc:proxy (REFERENCE)
+
+// JAVA
+[slc:jarFile] > mix:referenceable
+mixin
+- 'slc:manifest' (BINARY) m
+- 'slc:Manifest-Version' (STRING)
+- 'slc:Signature-Version' (STRING)
+- 'slc:Class-Path'  (STRING)
+- 'slc:Main-Class' (STRING)
+- 'slc:Extension-Name' (STRING)
+- 'slc:Implementation-Version' (STRING)
+- 'slc:Implementation-Vendor' (STRING)
+- 'slc:Implementation-Vendor-Id' (STRING)
+- 'slc:Implementation-URL' (STRING)
+- 'slc:Specification-Title' (STRING)
+- 'slc:Specification-Version' (STRING)
+- 'slc:Specification-Vendor' (STRING)
+- 'slc:Sealed' (STRING)
+
+// OSGi
+// see http://www.osgi.org/Specifications/Reference
+
+[slc:javaPackage] > mix:referenceable
+- slc:name (STRING) primary m
+
+[slc:osgiBaseVersion] > mix:referenceable
+- slc:asString (STRING) primary m
+- slc:major (LONG) m
+- slc:minor (LONG) m
+- slc:micro (LONG) m
+
+[slc:osgiVersion] > slc:osgiBaseVersion
+- slc:qualifier (STRING)
+
+[slc:exportedPackage] > slc:javaPackage
++ slc:uses (slc:javaPackage) multiple
++ slc:version (slc:osgiVersion)
+
+[slc:importedPackage] > slc:javaPackage
+- slc:version (STRING) ='0.0.0' m a
+- slc:optional (BOOLEAN) ='false' m a
+
+[slc:dynamicImportedPackage] > slc:javaPackage
+- slc:version (STRING) ='0.0.0' m a
+- slc:optional (BOOLEAN) ='false' m a
+
+[slc:requiredBundle] > mix:referenceable
+- 'slc:symbolic-name' (STRING) primary m
+- 'slc:bundle-version' (STRING) ='0.0.0' m a
+- slc:optional (BOOLEAN) ='false' m a
+
+[slc:fragmentHost] > mix:referenceable
+- 'slc:symbolic-name' (STRING) m
+- 'slc:bundle-version' (STRING) ='0.0.0' m a
+
+[slc:bundleNativeCode] > mix:referenceable
+- slc:path (STRING) primary m
+- slc:osname (STRING)
+- slc:processor (STRING)
+
+// see http://www.osgi.org/Specifications/ReferenceHeaders
+[slc:bundle] > mix:referenceable
+mixin
+- 'slc:symbolic-name' (STRING) primary m
+- 'slc:bundle-version' (STRING) m
+- 'slc:Bundle-SymbolicName' (STRING) m
+- 'slc:Bundle-Name' (STRING)
+- 'slc:Bundle-Description' (STRING)
+- 'slc:Bundle-ManifestVersion' (STRING)
+- 'slc:Bundle-Category' (STRING)
+- 'slc:Bundle-ActivationPolicy' (STRING)
+- 'slc:Bundle-Copyright' (STRING)
+- 'slc:Bundle-Vendor' (STRING)
+- 'slc:Bundle-License' (STRING)
+- 'slc:Bundle-DocURL' (STRING)
+- 'slc:Bundle-ContactAddress' (STRING)
+- 'slc:Bundle-Activator' (STRING)
+- 'slc:Bundle-UpdateLocation' (STRING)
+- 'slc:Bundle-Localization' (STRING)
+- 'slc:Bundle-ClassPath' (STRING) *
+// see http://wiki.eclipse.org/EE  < 'OSGi/Minimum-1.0','OSGi/Minimum-1.1','CDC-1.0/Foundation-1.0','CDC-1.1/Foundation-1.1','JRE-1.1','J2SE-1.2','J2SE-1.3','J2SE-1.4','J2SE-1.5','JavaSE-1.6','JavaSE-1.7'
+- 'slc:Bundle-RequiredExecutionEnvironment' (STRING) *
++ 'slc:Bundle-Version' (slc:osgiVersion) m
++ 'slc:Fragment-Host' (slc:fragmentHost)
++ 'slc:Import-Package' (slc:importedPackage) multiple
++ 'slc:Export-Package' (slc:exportedPackage) multiple
++ 'slc:Require-Bundle' (slc:requiredBundle) multiple
++ 'slc:Bundle-NativeCode' (slc:bundleNativeCode) multiple
++ 'slc:DynamicImport-Package' (slc:dynamicImportedPackage) multiple
+
+[slc:bundleArtifact] > slc:artifact,slc:jarFile,slc:bundle
+mixin
+
+// RPM
+[slc:rpm] > mix:referenceable, mix:created, mix:lastModified, mix:title
+mixin
+- slc:name (STRING)
+- slc:version (STRING)
+- slc:rpmVersion (STRING)
+- slc:rpmRelease (STRING)
+- slc:rpmArch (STRING)
+- slc:rpmArchivaeSize (STRING)
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..acf329fc8631a88e40d70b1b1311a807b2f5612a 100644 (file)
@@ -0,0 +1,6 @@
+Import-Package: org.apache.commons.logging,\
+org.dbunit.*;resolution:="optional",\
+junit.framework;resolution:="optional",\
+org.apache.commons.vfs.*,\
+javax.swing.plaf.metal,\
+*
\ No newline at end of file
diff --git a/org.argeo.slc.support/ext/test/log4j.properties b/org.argeo.slc.support/ext/test/log4j.properties
new file mode 100644 (file)
index 0000000..0133bab
--- /dev/null
@@ -0,0 +1,22 @@
+# Set root logger level to DEBUG and its only appender to A1.\r
+log4j.rootLogger=WARN, console\r
+\r
+## Levels\r
+# Slc\r
+log4j.logger.org.argeo=DEBUG\r
+\r
+# Castor\r
+log4j.logger.org.exolab.castor=WARN\r
+\r
+# Spring\r
+log4j.logger.org.springframework=WARN\r
+\r
+\r
+## Appenders\r
+# A1 is set to be a ConsoleAppender.\r
+log4j.appender.console=org.apache.log4j.ConsoleAppender\r
+\r
+# A1 uses PatternLayout.\r
+log4j.appender.console.layout=org.apache.log4j.PatternLayout\r
+log4j.appender.console.layout.ConversionPattern= %-5p %d{ISO8601} %m - %c%n\r
+\r
diff --git a/org.argeo.slc.support/ext/test/org/argeo/slc/diff/LineTokenizerTest.java b/org.argeo.slc.support/ext/test/org/argeo/slc/diff/LineTokenizerTest.java
new file mode 100644 (file)
index 0000000..4c7c858
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.diff;
+
+import java.util.List;
+
+import junit.framework.TestCase;
+
+public class LineTokenizerTest extends TestCase {
+       public void testSimple() throws Exception {
+               testAndAssert("a,b,c", new String[] { "a", "b", "c" });
+               testAndAssert("hello,bonjour,hallo,priviet", new String[] { "hello",
+                               "bonjour", "hallo", "priviet" });
+       }
+
+       public void testTricky() throws Exception {
+               testAndAssert("alone", new String[] { "alone" });
+               testAndAssert("", new String[] { "" });
+
+               testAndAssert(",hello,bonjour,hallo,priviet", new String[] { "",
+                               "hello", "bonjour", "hallo", "priviet" });
+               testAndAssert("hello,bonjour,,hallo,priviet", new String[] { "hello",
+                               "bonjour", "", "hallo", "priviet" });
+               testAndAssert("hello,bonjour,hallo,priviet,", new String[] { "hello",
+                               "bonjour", "hallo", "priviet", "" });
+               testAndAssert(",hello,,bonjour,hallo,,,,priviet,", new String[] { "",
+                               "hello", "", "bonjour", "hallo", "", "", "", "priviet", "" });
+
+               testAndAssert(",,,", new String[] { "", "", "", "" });
+       }
+
+       public void testComplex() throws Exception {
+               testAndAssert("a#b#c", '#', "", new String[] { "a", "b", "c" });
+               testAndAssert("hello!bonjour!hallo!priviet", '!', "", new String[] {
+                               "hello", "bonjour", "hallo", "priviet" });
+
+               testAndAssert("hello,,bonjour,,hallo,priviet", ',', "<EMPTY>",
+                               new String[] { "hello", "<EMPTY>", "bonjour", "<EMPTY>",
+                                               "hallo", "priviet" });
+       }
+
+       private void testAndAssert(String str, String[] expected) {
+               testAndAssert(str, ',', "", expected);
+       }
+
+       private void testAndAssert(String str, Character sep, String noValueStr,
+                       String[] expected) {
+               List<String> res = LineTokenizer.tokenize(str, sep, noValueStr);
+               assertEquals("Size", expected.length, res.size());
+               for (int i = 0; i < res.size(); i++) {
+                       String token = res.get(i);
+                       assertEquals("Value@" + i, expected[i], token);
+               }
+       }
+}
index ae6582536b350f8075593ee072c4500e48655914..f00bc0dd3a2af0f9c37da3e1a3d1f78bfa11f107 100644 (file)
@@ -8,4 +8,12 @@
        </parent>
        <artifactId>org.argeo.slc.support</artifactId>
        <name>SLC Third Party Support</name>
+       <dependencies>
+               <!-- SLC Runtime -->
+               <dependency>
+                       <groupId>org.argeo.slc</groupId>
+                       <artifactId>org.argeo.slc.core</artifactId>
+                       <version>2.1.1-SNAPSHOT</version>
+               </dependency>
+       </dependencies>
 </project>
\ No newline at end of file
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DataInterpreter.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DataInterpreter.java
new file mode 100644 (file)
index 0000000..9255c76
--- /dev/null
@@ -0,0 +1,35 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/**\r
+ * Converts data into a format better adapted for comparison. It is typically\r
+ * used to convert <code>String</code> into typed format such as\r
+ * <code>BigDecimal</code>\r
+ */\r
+public interface DataInterpreter {\r
+       /**\r
+        * Converts data\r
+        * \r
+        * @param key\r
+        *            any object used to differentiate the type of data (e.g.\r
+        *            column, path)\r
+        * @param value\r
+        *            the data to convert\r
+        * @return the converted object\r
+        */\r
+       public Object convert(Object key, Object value);\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/Diff.java b/org.argeo.slc.support/src/org/argeo/slc/diff/Diff.java
new file mode 100644 (file)
index 0000000..79dd7c4
--- /dev/null
@@ -0,0 +1,25 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+import org.springframework.core.io.Resource;\r
+\r
+/** A comparator providing structured information about the differences found. */\r
+public interface Diff {\r
+       /** Performs the comparison. */\r
+       public void compare(Resource expected, Resource reached,\r
+                       DiffResult diffResult);\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssue.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssue.java
new file mode 100644 (file)
index 0000000..eda08e5
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/** The root class for issues which happened during a diff. */\r
+public abstract class DiffIssue implements Comparable<DiffIssue> {\r
+       /** The position of this issue. */\r
+       // Was final and is not anymore in order to persist in hibernate\r
+       protected DiffPosition position;\r
+\r
+       // hibernate\r
+       private long id;\r
+\r
+       /** Constructor */\r
+       public DiffIssue(DiffPosition position) {\r
+               super();\r
+               this.position = position;\r
+       }\r
+\r
+       public int compareTo(DiffIssue o) {\r
+               return position.compareTo(o.position);\r
+       }\r
+\r
+       /** The position of this issue within the test file */\r
+       public DiffPosition getPosition() {\r
+               return position;\r
+       }\r
+\r
+       // Hibernate\r
+       @SuppressWarnings("unused")\r
+       private void setId(long id) {\r
+               this.id = id;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private long getId() {\r
+               return id;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setPosition(DiffPosition position) {\r
+               this.position = position;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssueKey.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffIssueKey.java
new file mode 100644 (file)
index 0000000..0be73a5
--- /dev/null
@@ -0,0 +1,52 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/** Intermediate class that can hold the key to be displayed. */\r
+public abstract class DiffIssueKey extends DiffIssue {\r
+       /** The position of this issue. */\r
+       protected DiffKey key;\r
+\r
+       /** Constructor without key */\r
+       public DiffIssueKey(DiffPosition position) {\r
+               super(position);\r
+       }\r
+\r
+       /** Constructor with key */\r
+       public DiffIssueKey(DiffPosition position, DiffKey key) {\r
+               super(position);\r
+               this.key = key;\r
+       }\r
+\r
+       public Object getKey() {\r
+               return key;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               if (key != null) {\r
+                       return key.toString();\r
+               } else {\r
+                       return "";\r
+               }\r
+       }\r
+\r
+       // Hibernate\r
+       @SuppressWarnings("unused")\r
+       private void setKey(DiffKey key) {\r
+               this.key = key;\r
+       }\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffKey.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffKey.java
new file mode 100644 (file)
index 0000000..8c2e60d
--- /dev/null
@@ -0,0 +1,24 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/**\r
+ * Object able to uniquely identify an atomic diff part. Used to identify\r
+ * missings and left-overs.\r
+ */\r
+public interface DiffKey {\r
+       public String toString();\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissing.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissing.java
new file mode 100644 (file)
index 0000000..7e7ba24
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/**\r
+ * A value missing in one of the file. If its position is related to expected,\r
+ * this means it is a left over in the reached, if its position is related to\r
+ * the reached it means that it is missing from the reached. If the value is\r
+ * null it means that the entire line is missing.\r
+ */\r
+public class DiffMissing extends DiffIssueKey {\r
+\r
+       public DiffMissing(DiffPosition position, DiffKey key) {\r
+               super(position);\r
+               super.key = key;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               if (position.relatedFile == RelatedFile.EXPECTED) {\r
+                       return position + ": left over " + super.toString();\r
+               } else if (position.relatedFile == RelatedFile.REACHED) {\r
+                       return position + ": missing " + super.toString();\r
+               }\r
+               return super.toString();\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissingXml.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffMissingXml.java
new file mode 100644 (file)
index 0000000..50fc7cd
--- /dev/null
@@ -0,0 +1,58 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/**\r
+ * <code>DiffMissing</code> using the XPath of the position as\r
+ * <code>DiffKey</code>\r
+ */\r
+public class DiffMissingXml extends DiffMissing {\r
+\r
+       public DiffMissingXml(XPathDiffPosition position) {\r
+               super(position, new DiffKeyXml(position.getXPath()));\r
+       }\r
+\r
+       /** Implementation of <code>DiffKey</code> based on an XPath string. */\r
+       protected static class DiffKeyXml implements DiffKey {\r
+               private final String xPath;\r
+\r
+               public DiffKeyXml(String xPath) {\r
+                       this.xPath = xPath;\r
+               }\r
+\r
+               public String getXPath() {\r
+                       return xPath;\r
+               }\r
+\r
+               @Override\r
+               public String toString() {\r
+                       return xPath;\r
+               }\r
+\r
+               @Override\r
+               public boolean equals(Object obj) {\r
+                       if (!(obj instanceof DiffKeyXml))\r
+                               return false;\r
+                       return xPath.equals(((DiffKeyXml) obj).xPath);\r
+               }\r
+\r
+               @Override\r
+               public int hashCode() {\r
+                       return xPath.hashCode();\r
+               }\r
+\r
+       }\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffNotMatched.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffNotMatched.java
new file mode 100644 (file)
index 0000000..9483dfe
--- /dev/null
@@ -0,0 +1,90 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+import org.argeo.slc.SlcException;\r
+\r
+/** Diff issue where reached and expected values are different. */\r
+public class DiffNotMatched extends DiffIssueKey {\r
+\r
+       // To enable hibernate persistance, these object cannot be final\r
+       // private final Object expected;\r
+       // private final Object reached;\r
+\r
+       private Object expected;\r
+       private Object reached;\r
+\r
+       public DiffNotMatched(DiffPosition position, Object expected, Object reached) {\r
+               super(position);\r
+               this.expected = expected;\r
+               this.reached = reached;\r
+       }\r
+\r
+       public DiffNotMatched(DiffPosition position, Object expected,\r
+                       Object reached, DiffKey key) {\r
+               super(position, key);\r
+               this.expected = expected;\r
+               this.reached = reached;\r
+       }\r
+\r
+       public Object getExpected() {\r
+               return expected;\r
+       }\r
+\r
+       public Object getReached() {\r
+               return reached;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               String result = position + ": not matched " + expected + " <> "\r
+                               + reached;\r
+               if (super.key != null) {\r
+                       result = result + " - Key: " + super.toString();\r
+               }\r
+\r
+               return result;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private String getExpectedStr() {\r
+               if (expected instanceof String)\r
+                       return (String) expected;\r
+               else\r
+                       throw new SlcException(\r
+                                       "Object 'expected' is of wrong type. Must be a String");\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private String getReachedStr() {\r
+               if (reached instanceof String)\r
+                       return (String) reached;\r
+               else\r
+                       throw new SlcException(\r
+                                       "Object 'reached' is of wrong type. Must be a String");\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setReachedStr(String reachedStr) {\r
+               this.reached = reachedStr;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setExpectedStr(String expectedStr) {\r
+               this.expected = expectedStr;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffPosition.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffPosition.java
new file mode 100644 (file)
index 0000000..f8ff823
--- /dev/null
@@ -0,0 +1,47 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/** The position of a diff issue within the test resource. */\r
+public abstract class DiffPosition implements Comparable<DiffPosition> {\r
+       protected RelatedFile relatedFile;\r
+\r
+       public DiffPosition(RelatedFile relatedFile) {\r
+               super();\r
+               this.relatedFile = relatedFile;\r
+       }\r
+\r
+       // For Hibernate\r
+       DiffPosition() {\r
+       }\r
+\r
+       public RelatedFile getRelatedFile() {\r
+               return relatedFile;\r
+       }\r
+\r
+       // Added to enable the new data model for persisting TabularDiffTestResult\r
+       @SuppressWarnings("unused")\r
+       private Boolean getIsReached() {\r
+               return relatedFile.equals(RelatedFile.REACHED);\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setIsReached(Boolean isReached) {\r
+               this.relatedFile = (isReached ? RelatedFile.REACHED\r
+                               : RelatedFile.EXPECTED);\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/DiffResult.java b/org.argeo.slc.support/src/org/argeo/slc/diff/DiffResult.java
new file mode 100644 (file)
index 0000000..8cdcf7e
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.diff;
+
+/**
+ * The result of a diff, to be subclassed in order to provide richer information
+ */
+public interface DiffResult {
+       /** Adds a diff issue */
+       public void addDiffIssue(DiffIssue diffIssue);
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/KeyColumnsDiff.java b/org.argeo.slc.support/src/org/argeo/slc/diff/KeyColumnsDiff.java
new file mode 100644 (file)
index 0000000..8ba832d
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.diff;
+
+import java.util.List;
+
+/**
+ * Diff which is based on comparison of multiple-key atomic elements (typically
+ * columns in a tabular content)
+ */
+public interface KeyColumnsDiff extends Diff {
+       /** $The list of key columns. */
+       List<String> getKeyColumns();
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/LineTokenizer.java b/org.argeo.slc.support/src/org/argeo/slc/diff/LineTokenizer.java
new file mode 100644 (file)
index 0000000..baaa3b9
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.diff;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Parses a string as a vector of strings according to a separator, dealing
+ * properly with missing values. This is intended to be used instead of the
+ * standard StringTokenizer, which does not deal well with empty values.
+ * Contrary to the StringTokenizer the provided String is parsed in the
+ * constructor and the values stored as a property. This should therefore not be
+ * used to parse long strings. No reference to the argument passed in
+ * constructor is kept.
+ */
+public class LineTokenizer {
+       private final List<String> tokens;
+
+       /** Complete constructor. */
+       public LineTokenizer(String stringToParse, Character separator,
+                       String noValueString) {
+               this.tokens = parse(stringToParse, separator, noValueString);
+       }
+
+       /**
+        * Parse the string as a vector of strings. Can be overridden in order to
+        * provide another implementation.
+        */
+       protected List<String> parse(final String stringToParse,
+                       final char separator, final String noValueString) {
+               // Init
+               final int NULL = -1;
+               List<String> res = new ArrayList<String>();
+               final char[] array = stringToParse.toCharArray();
+               int lastSeparatorIndex = NULL;
+
+               // Loop on chars
+               for (int currIndex = 0; currIndex < array.length; currIndex++) {
+                       char c = array[currIndex];
+                       if (c == separator) {
+                               if (currIndex == 0) {
+                                       // first char is a separator
+                                       res.add(new String(noValueString));
+                                       lastSeparatorIndex = 0;
+                               } else if (lastSeparatorIndex == NULL) {
+                                       // first separator found
+                                       res.add(new String(array, 0, currIndex));
+                                       lastSeparatorIndex = currIndex;
+                               } else if (lastSeparatorIndex != NULL
+                                               && (lastSeparatorIndex == (currIndex - 1))) {
+                                       // consecutive separators
+                                       res.add(new String(noValueString));
+                                       lastSeparatorIndex = currIndex;
+                               } else {
+                                       // simple case
+                                       res.add(new String(array, lastSeparatorIndex + 1, currIndex
+                                                       - lastSeparatorIndex - 1));
+                                       lastSeparatorIndex = currIndex;
+                               }
+                       }
+               }
+
+               // Finalize
+               if (lastSeparatorIndex == NULL) {
+                       // no separator found
+                       res.add(new String(stringToParse));
+               } else if (lastSeparatorIndex == (array.length - 1)) {
+                       // last char is a separator
+                       res.add(new String(noValueString));
+               } else {
+                       // last token
+                       res.add(new String(array, lastSeparatorIndex + 1, array.length
+                                       - lastSeparatorIndex - 1));
+               }
+               return res;
+       }
+
+       /** The tokens. */
+       public List<String> getTokens() {
+               return tokens;
+       }
+
+       /** Parse */
+       public static List<String> tokenize(String stringToParse,
+                       Character separator, String noValueString) {
+               LineTokenizer lt = new LineTokenizer(stringToParse, separator,
+                               noValueString);
+               return lt.getTokens();
+       }
+
+       /** Parse, using the empty string as no value string. */
+       public static List<String> tokenize(String stringToParse,
+                       Character separator) {
+               return tokenize(stringToParse, separator, "");
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/RelatedFile.java b/org.argeo.slc.support/src/org/argeo/slc/diff/RelatedFile.java
new file mode 100644 (file)
index 0000000..e2887ba
--- /dev/null
@@ -0,0 +1,24 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/** Enumeration of the types of resource tested. */\r
+public enum RelatedFile {\r
+       /** The expected resource */\r
+       EXPECTED,\r
+       /** The reached resource */\r
+       REACHED\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/TableDiffPosition.java b/org.argeo.slc.support/src/org/argeo/slc/diff/TableDiffPosition.java
new file mode 100644 (file)
index 0000000..7d5aa3e
--- /dev/null
@@ -0,0 +1,101 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+import org.argeo.slc.UnsupportedException;\r
+\r
+/**\r
+ * A diff position within a table structure such a CSV file or an SQL result\r
+ * set.\r
+ */\r
+public class TableDiffPosition extends DiffPosition {\r
+       private Integer line;\r
+       /** Can be null */\r
+       private Integer column;\r
+       /** Can be null */\r
+       private String columnName;\r
+\r
+       public TableDiffPosition(RelatedFile relatedFile, Integer line,\r
+                       Integer column, String columnName) {\r
+               super(relatedFile);\r
+               this.line = line;\r
+               this.column = column;\r
+               this.columnName = columnName;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private TableDiffPosition() {\r
+       }\r
+\r
+       public Integer getLine() {\r
+               return line;\r
+       }\r
+\r
+       public Integer getColumn() {\r
+               return column;\r
+       }\r
+\r
+       public String getColumnName() {\r
+               return columnName;\r
+       }\r
+\r
+       public int compareTo(DiffPosition dp) {\r
+               if (!(dp instanceof TableDiffPosition))\r
+                       throw new UnsupportedException("position", dp);\r
+\r
+               TableDiffPosition o = (TableDiffPosition) dp;\r
+               if (relatedFile.equals(o.relatedFile)) {\r
+                       if (line == o.line) {\r
+                               return column.compareTo(o.column);\r
+                       } else {\r
+                               return line.compareTo(o.line);\r
+                       }\r
+               } else {\r
+                       return relatedFile.compareTo(o.relatedFile);\r
+               }\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               StringBuffer buf = new StringBuffer("");\r
+               buf.append(relatedFile).append('[').append(line);\r
+               if (column != null) {\r
+                       buf.append(',').append(column);\r
+                       if (columnName != null) {\r
+                               buf.append('-').append(columnName);\r
+                       }\r
+               }\r
+               buf.append(']');\r
+               return buf.toString();\r
+       }\r
+\r
+       // Hibernate\r
+       @SuppressWarnings("unused")\r
+       private void setLine(Integer line) {\r
+               this.line = line;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setColumn(Integer column) {\r
+               this.column = column;\r
+       }\r
+\r
+       @SuppressWarnings("unused")\r
+       private void setColumnName(String columnName) {\r
+               this.columnName = columnName;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/Tolerance.java b/org.argeo.slc.support/src/org/argeo/slc/diff/Tolerance.java
new file mode 100644 (file)
index 0000000..625699c
--- /dev/null
@@ -0,0 +1,33 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+/** Compares objects, eventually using tolerance mechanisms. */\r
+public interface Tolerance {\r
+       /**\r
+        * Compares objects\r
+        * \r
+        * @param key\r
+        *            any object used to differentiate the type of data (e.g.\r
+        *            column, path)\r
+        * @param expected\r
+        *            the expected value\r
+        * @param reached\r
+        *            the reached value\r
+        * @return the converted object\r
+        */\r
+       public Boolean compare(Object key, Object expected, Object reached);\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/ToleranceDiff.java b/org.argeo.slc.support/src/org/argeo/slc/diff/ToleranceDiff.java
new file mode 100644 (file)
index 0000000..798b658
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.diff;
+
+import java.util.Map;
+
+/** A diff which can manage tolerances. */
+public interface ToleranceDiff extends Diff {
+
+       /** Get tolerances, key is the column name. */
+       public Map<String, String> getTolerances();
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/XPathDiffPosition.java b/org.argeo.slc.support/src/org/argeo/slc/diff/XPathDiffPosition.java
new file mode 100644 (file)
index 0000000..a1ddb6e
--- /dev/null
@@ -0,0 +1,50 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.diff;\r
+\r
+import org.argeo.slc.UnsupportedException;\r
+\r
+/** A diff position within an Xml file. <b>NOT YET IMPLEMENTED</b>. */\r
+public class XPathDiffPosition extends DiffPosition {\r
+\r
+       private String xPath;\r
+\r
+       public XPathDiffPosition(RelatedFile relatedFile, String path) {\r
+               super(relatedFile);\r
+               xPath = path;\r
+       }\r
+\r
+       public int compareTo(DiffPosition dp) {\r
+               if (!(dp instanceof XPathDiffPosition))\r
+                       throw new UnsupportedException("position", dp);\r
+\r
+               XPathDiffPosition o = (XPathDiffPosition) dp;\r
+               if (relatedFile.equals(o.relatedFile)) {\r
+                       return xPath.compareTo(o.xPath);\r
+               } else {\r
+                       return relatedFile.compareTo(o.relatedFile);\r
+               }\r
+       }\r
+\r
+       public String getXPath() {\r
+               return xPath;\r
+       }\r
+\r
+       @Override\r
+       public String toString() {\r
+               return xPath;\r
+       }\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/diff/package.html b/org.argeo.slc.support/src/org/argeo/slc/diff/package.html
new file mode 100644 (file)
index 0000000..a58e685
--- /dev/null
@@ -0,0 +1,6 @@
+<html>\r
+<head></head>\r
+<body>\r
+Abstraction of diff comparison with structured results.\r
+</body>\r
+</html>
\ No newline at end of file
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/AbstractJschTask.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/AbstractJschTask.java
new file mode 100644 (file)
index 0000000..ed37069
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+
+public abstract class AbstractJschTask implements Runnable {
+       private final Log log = LogFactory.getLog(getClass());
+
+       private SshTarget sshTarget;
+
+       protected Session openSession() {
+               if (sshTarget.getSession() != null) {
+                       Session session = sshTarget.getSession();
+                       if (session.isConnected()) {
+                               if (log.isTraceEnabled())
+                                       log.debug("Using cached session to " + getSshTarget()
+                                                       + " via SSH");
+                               return session;
+                       }
+               }
+
+               try {
+                       JSch jsch = new JSch();
+                       if (sshTarget.getUsePrivateKey()
+                                       && sshTarget.getLocalPrivateKey().exists())
+                               jsch.addIdentity(sshTarget.getLocalPrivateKey()
+                                               .getAbsolutePath());
+                       Session session = jsch.getSession(getSshTarget().getUser(),
+                                       getSshTarget().getHost(), getSshTarget().getPort());
+
+                       session.setUserInfo(getSshTarget().getUserInfo());
+                       session.setServerAliveInterval(1000);
+                       session.connect();
+                       if (log.isTraceEnabled())
+                               log.trace("Connected to " + getSshTarget() + " via SSH");
+                       if (sshTarget.getSession() != null) {
+                               if (log.isTraceEnabled())
+                                       log.trace("The cached session to " + getSshTarget()
+                                                       + " was disconnected and was reset.");
+                               sshTarget.setSession(session);
+                       }
+                       return session;
+               } catch (JSchException e) {
+                       if (sshTarget.getUserInfo() instanceof SimpleUserInfo)
+                               ((SimpleUserInfo) sshTarget.getUserInfo()).reset();
+                       throw new SlcException("Could not open session to "
+                                       + getSshTarget(), e);
+               }
+       }
+
+       public void run() {
+               Session session = openSession();
+               try {
+                       run(session);
+               } finally {
+                       if (sshTarget != null && sshTarget.getSession() == null) {
+                               session.disconnect();
+                               if (log.isTraceEnabled())
+                                       log.trace("Disconnected from " + getSshTarget()
+                                                       + " via SSH");
+                       }
+               }
+       }
+
+       abstract void run(Session session);
+
+       protected int checkAck(InputStream in) throws IOException {
+               int b = in.read();
+               // b may be 0 for success,
+               // 1 for error,
+               // 2 for fatal error,
+               // -1
+               if (b == 0)
+                       return b;
+               else if (b == -1)
+                       return b;// throw new SlcException("SSH ack returned -1");
+               else if (b == 1 || b == 2) {
+                       StringBuffer sb = new StringBuffer();
+                       int c;
+                       do {
+                               c = in.read();
+                               sb.append((char) c);
+                       } while (c != '\n');
+                       if (b == 1) { // error
+                               throw new SlcException("SSH ack error: " + sb.toString());
+                       }
+                       if (b == 2) { // fatal error
+                               throw new SlcException("SSH fatal error: " + sb.toString());
+                       }
+               }
+               return b;
+       }
+
+       public SshTarget getSshTarget() {
+               if (sshTarget == null)
+                       throw new SlcException("No SSH target defined.");
+               return sshTarget;
+       }
+
+       public void setSshTarget(SshTarget sshTarget) {
+               this.sshTarget = sshTarget;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/CallbackHandlerUserInfo.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/CallbackHandlerUserInfo.java
new file mode 100644 (file)
index 0000000..ab358aa
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.PasswordCallback;
+
+import org.argeo.slc.SlcException;
+
+/** Retrieve a password or a passphrase using a standard callback handler. */
+public final class CallbackHandlerUserInfo extends SimpleUserInfo {
+       private CallbackHandler callbackHandler;
+
+       private Boolean alwaysPrompt = false;
+
+       public boolean promptPassphrase(String message) {
+               if (passphrase != null)
+                       return true;
+
+               if (!alwaysPrompt && passphraseSafe != null)
+                       return true;
+
+               reset();
+               PasswordCallback passwordCb = new PasswordCallback("SSH Passphrase",
+                               false);
+               Callback[] dialogCbs = new Callback[] { passwordCb };
+               try {
+                       callbackHandler.handle(dialogCbs);
+                       passphraseSafe = passwordCb.getPassword();
+                       return passphraseSafe != null;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot ask for a password", e);
+               }
+       }
+
+       public boolean promptPassword(String message) {
+               if (password != null)
+                       return true;
+
+               if (!alwaysPrompt && passwordSafe != null)
+                       return true;
+
+               reset();
+               PasswordCallback passwordCb = new PasswordCallback("SSH Password",
+                               false);
+               Callback[] dialogCbs = new Callback[] { passwordCb };
+               try {
+                       callbackHandler.handle(dialogCbs);
+                       passwordSafe = passwordCb.getPassword();
+                       return passwordSafe != null;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot ask for a password", e);
+               }
+       }
+
+       public void setAlwaysPrompt(Boolean alwaysPrompt) {
+               this.alwaysPrompt = alwaysPrompt;
+       }
+
+       public void setCallbackHandler(CallbackHandler defaultCallbackHandler) {
+               this.callbackHandler = defaultCallbackHandler;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/JschContextSession.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/JschContextSession.java
new file mode 100644 (file)
index 0000000..44d0bcc
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.InitializingBean;
+
+import com.jcraft.jsch.Session;
+
+/** Caches a JSCH session in the the ssh target. */
+public class JschContextSession extends AbstractJschTask implements
+               InitializingBean, DisposableBean {
+       private final static Log log = LogFactory.getLog(JschContextSession.class);
+       private Boolean autoconnect = false;
+
+       @Override
+       void run(Session session) {
+               // clear();
+               getSshTarget().setSession(session);
+               if (log.isDebugEnabled())
+                       log.debug("Cached SSH context session to " + getSshTarget());
+       }
+
+       public void afterPropertiesSet() throws Exception {
+               // if (log.isDebugEnabled())
+               // log.debug(getClass() + ".afterPropertiesSet(), " + beanName + ", "
+               // + this);
+               if (autoconnect)
+                       try {
+                               run();
+                       } catch (Exception e) {
+                               log.error("Could not automatically open session", e);
+                       }
+       }
+
+       public void destroy() throws Exception {
+               clear();
+       }
+
+       public void clear() {
+               SshTarget sshTarget = getSshTarget();
+               synchronized (sshTarget) {
+                       if (sshTarget.getSession() != null) {
+                               sshTarget.getSession().disconnect();
+                               sshTarget.setSession(null);
+                               if (log.isDebugEnabled())
+                                       log.debug("Cleared cached SSH context session to "
+                                                       + getSshTarget());
+                       }
+               }
+       }
+
+       public void setAutoconnect(Boolean autoconnect) {
+               this.autoconnect = autoconnect;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/JschExecutor.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/JschExecutor.java
new file mode 100644 (file)
index 0000000..b15694c
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.ExecuteException;
+import org.apache.commons.exec.ExecuteResultHandler;
+import org.apache.commons.exec.ExecuteStreamHandler;
+import org.apache.commons.exec.ExecuteWatchdog;
+import org.apache.commons.exec.Executor;
+import org.apache.commons.exec.ProcessDestroyer;
+
+/** A Commons Exec executor executing remotely via SSH */
+public class JschExecutor implements Executor {
+       private File workingDirectory;
+       private ExecuteStreamHandler streamHandler;
+
+       private SshTarget sshTarget;
+
+       public void setExitValue(int value) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public void setExitValues(int[] values) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public boolean isFailure(int exitValue) {
+               return Executor.INVALID_EXITVALUE == exitValue;
+       }
+
+       public ExecuteStreamHandler getStreamHandler() {
+               return streamHandler;
+       }
+
+       public void setStreamHandler(ExecuteStreamHandler streamHandler) {
+               this.streamHandler = streamHandler;
+       }
+
+       public ExecuteWatchdog getWatchdog() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public void setWatchdog(ExecuteWatchdog watchDog) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public ProcessDestroyer getProcessDestroyer() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public void setProcessDestroyer(ProcessDestroyer processDestroyer) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public File getWorkingDirectory() {
+               return workingDirectory;
+       }
+
+       public void setWorkingDirectory(File workingDirectory) {
+               this.workingDirectory = workingDirectory;
+       }
+
+       public int execute(CommandLine command) throws ExecuteException,
+                       IOException {
+               return execute(command, (Map) null);
+       }
+
+       public int execute(CommandLine command, Map environment)
+                       throws ExecuteException, IOException {
+               String cmd = command.toString();
+               if(workingDirectory!=null)
+                       cmd = "cd "+workingDirectory.getPath()+" && "+cmd;
+               RemoteExec remoteExec = new RemoteExec();
+               remoteExec.setSshTarget(sshTarget);
+               remoteExec.setStreamHandler(streamHandler);
+               remoteExec.setCommand(cmd);
+               if (environment != null)
+                       remoteExec.setEnv(environment);
+               remoteExec.run();
+               return remoteExec.getLastExitStatus() != null ? remoteExec
+                               .getLastExitStatus() : Executor.INVALID_EXITVALUE;
+       }
+
+       public void execute(CommandLine command, ExecuteResultHandler handler)
+                       throws ExecuteException, IOException {
+               // TODO Auto-generated method stub
+
+       }
+
+       public void execute(CommandLine command, Map environment,
+                       ExecuteResultHandler handler) throws ExecuteException, IOException {
+
+       }
+
+       public SshTarget getSshTarget() {
+               return sshTarget;
+       }
+
+       public void setSshTarget(SshTarget sshTarget) {
+               this.sshTarget = sshTarget;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/JschMultiTasks.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/JschMultiTasks.java
new file mode 100644 (file)
index 0000000..40d4034
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.jcraft.jsch.Session;
+
+public class JschMultiTasks extends AbstractJschTask {
+       private List<AbstractJschTask> tasks = new ArrayList<AbstractJschTask>();
+
+       @Override
+       protected void run(Session session) {
+               for (AbstractJschTask task : tasks) {
+                       task.setSshTarget(getSshTarget());
+                       task.run(session);
+               }
+       }
+
+       public void setTasks(List<AbstractJschTask> tasks) {
+               this.tasks = tasks;
+       }
+
+       public List<AbstractJschTask> getTasks() {
+               return tasks;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/RemoteExec.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/RemoteExec.java
new file mode 100644 (file)
index 0000000..691d0d6
--- /dev/null
@@ -0,0 +1,501 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import org.apache.commons.exec.ExecuteStreamHandler;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.ExecutionResources;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.springframework.core.io.Resource;
+import org.springframework.util.StringUtils;
+
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.ChannelShell;
+import com.jcraft.jsch.Session;
+
+public class RemoteExec extends AbstractJschTask {
+       private final static Log log = LogFactory.getLog(RemoteExec.class);
+
+       private Boolean failOnBadExitStatus = true;
+
+       private List<String> commands = new ArrayList<String>();
+       private String command;
+       private SystemCall systemCall;
+       private List<SystemCall> systemCalls = new ArrayList<SystemCall>();
+       private Resource script;
+       private Boolean xForwarding = false;
+       private Boolean agentForwarding = false;
+       private Boolean forceShell = false;
+       private Map<String, String> env = new HashMap<String, String>();
+       private Resource stdIn = null;
+       private Resource stdOut = null;
+       private ExecutionResources executionResources;
+
+       private String user;
+
+       private ExecuteStreamHandler streamHandler = null;
+
+       private Integer lastExitStatus = null;
+       /**
+        * If set, stdout is written to it as a list of lines. Cleared before each
+        * run.
+        */
+       private List<String> stdOutLines = null;
+       private Boolean logEvenIfStdOutLines = false;
+       private Boolean quiet = false;
+
+       public RemoteExec() {
+       }
+
+       public RemoteExec(SshTarget sshTarget, String cmd) {
+               setSshTarget(sshTarget);
+               setCommand(cmd);
+       }
+
+       public void run(Session session) {
+               List<String> commandsToUse = new ArrayList<String>(commands);
+               String commandToUse = command;
+               // convert system calls
+               if (systemCall != null) {
+                       if (command != null)
+                               throw new SlcException("Cannot specify command AND systemCall");
+                       commandToUse = convertSystemCall(systemCall);
+               }
+
+               if (systemCalls.size() != 0) {
+                       if (commandsToUse.size() != 0)
+                               throw new SlcException(
+                                               "Cannot specify commands AND systemCalls");
+                       for (SystemCall systemCall : systemCalls)
+                               commandsToUse.add(convertSystemCall(systemCall));
+               }
+
+               if (script != null) {
+                       // TODO: simply pass the script as a string command
+                       if (commandsToUse.size() != 0)
+                               throw new SlcException("Cannot specify commands and script");
+                       BufferedReader reader = null;
+                       try {
+                               reader = new BufferedReader(new InputStreamReader(
+                                               script.getInputStream()));
+                               String line = null;
+                               while ((line = reader.readLine()) != null) {
+                                       if (!StringUtils.hasText(line))
+                                               continue;
+                                       commandsToUse.add(line);
+                               }
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot read script " + script, e);
+                       } finally {
+                               IOUtils.closeQuietly(reader);
+                       }
+               }
+
+               if (forceShell) {
+                       // for the time being do not interpret both \n and ;
+                       // priority to \n
+                       // until we know how to parse ; within ""
+                       if (commandToUse.indexOf('\n') >= 0) {
+                               StringTokenizer st = new StringTokenizer(commandToUse, "\n");
+                               while (st.hasMoreTokens()) {
+                                       String cmd = st.nextToken();
+                                       commandsToUse.add(cmd);
+                               }
+                       } else if (commandToUse.indexOf(';') >= 0) {
+                               StringTokenizer st = new StringTokenizer(commandToUse, ";");
+                               while (st.hasMoreTokens()) {
+                                       String cmd = st.nextToken();
+                                       commandsToUse.add(cmd);
+                               }
+                       } else {
+                               commandsToUse.add(commandToUse);
+                       }
+                       commandToUse = null;
+               }
+
+               // run as user
+               if (user != null) {
+                       if (commandsToUse.size() > 0) {
+                               commandsToUse.add(0, "su - " + user);
+                               commandsToUse.add("exit");
+                       } else {
+                               if (command.indexOf('\"') >= 0)
+                                       throw new SlcException(
+                                                       "Don't know how to su a command with \", use shell instead.");
+                               commandToUse = "su - " + user + " -c \"" + command + "\"";
+                       }
+               }
+
+               // execute command(s)
+               if (commandToUse != null) {
+                       if (commandsToUse.size() != 0)
+                               throw new SlcException(
+                                               "Specify either a single command or a list of commands.");
+                       remoteExec(session, commandToUse);
+               } else {
+                       if (commandsToUse.size() == 0)
+                               throw new SlcException(
+                                               "Neither a single command or a list of commands has been specified.");
+
+                       remoteExec(session, commandsToUse, script != null ? "script "
+                                       + script.getFilename() : commandsToUse.size() + " commands");
+               }
+       }
+
+       protected String convertSystemCall(SystemCall systemCall) {
+               // TODO: prepend environment variables
+               // TODO: deal with exec dir
+               return systemCall.asCommand();
+       }
+
+       protected void remoteExec(Session session, final List<String> commands,
+                       String description) {
+               try {
+                       final ChannelShell channel = (ChannelShell) session
+                                       .openChannel("shell");
+                       channel.setInputStream(null);
+                       channel.setXForwarding(xForwarding);
+                       channel.setAgentForwarding(agentForwarding);
+                       channel.setEnv(new Hashtable<String, String>(env));
+
+                       /*
+                        * // Choose the pty-type "vt102".
+                        * ((ChannelShell)channel).setPtyType("vt102");
+                        */
+                       // Writer thread
+                       final BufferedWriter writer = new BufferedWriter(
+                                       new OutputStreamWriter(channel.getOutputStream()));
+
+                       if (log.isDebugEnabled())
+                               log.debug("Run " + description + " on " + getSshTarget()
+                                               + "...");
+                       channel.connect();
+
+                       // write commands to shell
+                       Thread writerThread = new Thread("Shell writer " + getSshTarget()) {
+                               @Override
+                               public void run() {
+                                       try {
+                                               for (String line : commands) {
+                                                       if (!StringUtils.hasText(line))
+                                                               continue;
+                                                       writer.write(line);
+                                                       writer.newLine();
+                                               }
+                                               writer.append("exit");
+                                               writer.newLine();
+                                               writer.flush();
+                                               // channel.disconnect();
+                                       } catch (IOException e) {
+                                               throw new SlcException("Cannot write to shell on "
+                                                               + getSshTarget(), e);
+                                       } finally {
+                                               IOUtils.closeQuietly(writer);
+                                       }
+                               }
+                       };
+                       writerThread.start();
+
+                       readStdOut(channel);
+                       checkExitStatus(channel);
+                       channel.disconnect();
+
+               } catch (Exception e) {
+                       throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
+                                       e);
+               }
+
+       }
+
+       protected void remoteExec(Session session, String command) {
+               try {
+                       final ChannelExec channel = (ChannelExec) session
+                                       .openChannel("exec");
+                       channel.setCommand(command);
+
+                       channel.setInputStream(null);
+                       channel.setXForwarding(xForwarding);
+                       channel.setAgentForwarding(agentForwarding);
+                       channel.setEnv(new Hashtable<String, String>(env));
+                       channel.setErrStream(null);
+
+                       // Standard Error
+                       readStdErr(channel);
+
+                       if (log.isTraceEnabled())
+                               log.trace("Run '" + command + "' on " + getSshTarget() + "...");
+                       channel.connect();
+
+                       readStdIn(channel);
+                       readStdOut(channel);
+
+                       if (streamHandler != null) {
+                               streamHandler.start();
+                               while (!channel.isClosed()) {
+                                       try {
+                                               Thread.sleep(100);
+                                       } catch (Exception e) {
+                                               break;
+                                       }
+                               }
+                       }
+
+                       checkExitStatus(channel);
+                       channel.disconnect();
+               } catch (Exception e) {
+                       throw new SlcException("Cannot execute remotely '" + command
+                                       + "' on " + getSshTarget(), e);
+               }
+       }
+
+       protected void readStdOut(Channel channel) {
+               try {
+                       if (stdOut != null) {
+                               OutputStream localStdOut = createOutputStream(stdOut);
+                               try {
+                                       IOUtils.copy(channel.getInputStream(), localStdOut);
+                               } finally {
+                                       IOUtils.closeQuietly(localStdOut);
+                               }
+                       } else if (streamHandler != null) {
+                               if (channel.getInputStream() != null)
+                                       streamHandler.setProcessOutputStream(channel
+                                                       .getInputStream());
+                       } else {
+                               BufferedReader stdOut = null;
+                               try {
+                                       InputStream in = channel.getInputStream();
+                                       stdOut = new BufferedReader(new InputStreamReader(in));
+                                       String line = null;
+                                       while ((line = stdOut.readLine()) != null) {
+                                               if (!line.trim().equals("")) {
+
+                                                       if (stdOutLines != null) {
+                                                               stdOutLines.add(line);
+                                                               if (logEvenIfStdOutLines && !quiet)
+                                                                       log.info(line);
+                                                       } else {
+                                                               if (!quiet)
+                                                                       log.info(line);
+                                                       }
+                                               }
+                                       }
+                               } finally {
+                                       IOUtils.closeQuietly(stdOut);
+                               }
+                       }
+               } catch (IOException e) {
+                       throw new SlcException("Cannot redirect stdout from "
+                                       + getSshTarget(), e);
+               }
+       }
+
+       protected void readStdErr(final ChannelExec channel) {
+               if (streamHandler != null) {
+                       try {
+                               streamHandler.setProcessOutputStream(channel.getErrStream());
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot read stderr from "
+                                               + getSshTarget(), e);
+                       }
+               } else {
+                       new Thread("stderr " + getSshTarget()) {
+                               public void run() {
+                                       BufferedReader stdErr = null;
+                                       try {
+                                               InputStream in = channel.getErrStream();
+                                               stdErr = new BufferedReader(new InputStreamReader(in));
+                                               String line = null;
+                                               while ((line = stdErr.readLine()) != null) {
+                                                       if (!line.trim().equals(""))
+                                                               log.error(line);
+                                               }
+                                       } catch (IOException e) {
+                                               if (log.isDebugEnabled())
+                                                       log.error("Cannot read stderr from "
+                                                                       + getSshTarget(), e);
+                                       } finally {
+                                               IOUtils.closeQuietly(stdErr);
+                                       }
+                               }
+                       }.start();
+               }
+       }
+
+       protected void readStdIn(final ChannelExec channel) {
+               if (stdIn != null) {
+                       Thread stdInThread = new Thread("Stdin " + getSshTarget()) {
+                               @Override
+                               public void run() {
+                                       OutputStream out = null;
+                                       try {
+                                               out = channel.getOutputStream();
+                                               IOUtils.copy(stdIn.getInputStream(), out);
+                                       } catch (IOException e) {
+                                               throw new SlcException("Cannot write stdin on "
+                                                               + getSshTarget(), e);
+                                       } finally {
+                                               IOUtils.closeQuietly(out);
+                                       }
+                               }
+                       };
+                       stdInThread.start();
+               } else if (streamHandler != null) {
+                       try {
+                               streamHandler.setProcessInputStream(channel.getOutputStream());
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot write stdin on "
+                                               + getSshTarget(), e);
+                       }
+               }
+       }
+
+       protected void checkExitStatus(Channel channel) {
+               if (channel.isClosed()) {
+                       lastExitStatus = channel.getExitStatus();
+                       if (lastExitStatus == 0) {
+                               if (log.isTraceEnabled())
+                                       log.trace("Remote execution exit status: " + lastExitStatus);
+                       } else {
+                               String msg = "Remote execution failed with " + " exit status: "
+                                               + lastExitStatus;
+                               if (failOnBadExitStatus)
+                                       throw new SlcException(msg);
+                               else
+                                       log.error(msg);
+                       }
+               }
+
+       }
+
+       protected OutputStream createOutputStream(Resource target) {
+               FileOutputStream out = null;
+               try {
+
+                       final File file;
+                       if (executionResources != null)
+                               file = new File(executionResources.getAsOsPath(target, true));
+                       else
+                               file = target.getFile();
+                       out = new FileOutputStream(file, false);
+               } catch (IOException e) {
+                       log.error("Cannot get file for " + target, e);
+                       IOUtils.closeQuietly(out);
+               }
+               return out;
+       }
+
+       public Integer getLastExitStatus() {
+               return lastExitStatus;
+       }
+
+       public void setStreamHandler(ExecuteStreamHandler executeStreamHandler) {
+               this.streamHandler = executeStreamHandler;
+       }
+
+       public void setCommand(String command) {
+               this.command = command;
+       }
+
+       public void setCommands(List<String> commands) {
+               this.commands = commands;
+       }
+
+       public void setFailOnBadExitStatus(Boolean failOnBadExitStatus) {
+               this.failOnBadExitStatus = failOnBadExitStatus;
+       }
+
+       public void setSystemCall(SystemCall systemCall) {
+               this.systemCall = systemCall;
+       }
+
+       public void setSystemCalls(List<SystemCall> systemCalls) {
+               this.systemCalls = systemCalls;
+       }
+
+       public void setScript(Resource script) {
+               this.script = script;
+       }
+
+       public void setxForwarding(Boolean xForwarding) {
+               this.xForwarding = xForwarding;
+       }
+
+       public void setAgentForwarding(Boolean agentForwarding) {
+               this.agentForwarding = agentForwarding;
+       }
+
+       public void setEnv(Map<String, String> env) {
+               this.env = env;
+       }
+
+       public void setForceShell(Boolean forceShell) {
+               this.forceShell = forceShell;
+       }
+
+       public List<String> getCommands() {
+               return commands;
+       }
+
+       public void setStdOutLines(List<String> stdOutLines) {
+               this.stdOutLines = stdOutLines;
+       }
+
+       public void setLogEvenIfStdOutLines(Boolean logEvenIfStdOutLines) {
+               this.logEvenIfStdOutLines = logEvenIfStdOutLines;
+       }
+
+       public void setQuiet(Boolean quiet) {
+               this.quiet = quiet;
+       }
+
+       public void setStdIn(Resource stdIn) {
+               this.stdIn = stdIn;
+       }
+
+       public void setStdOut(Resource stdOut) {
+               this.stdOut = stdOut;
+       }
+
+       public void setExecutionResources(ExecutionResources executionResources) {
+               this.executionResources = executionResources;
+       }
+
+       public void setUser(String user) {
+               this.user = user;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/ScpFrom.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/ScpFrom.java
new file mode 100644 (file)
index 0000000..3f83778
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.springframework.core.io.Resource;
+
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.Session;
+
+public class ScpFrom extends AbstractJschTask {
+       private final static Log log = LogFactory.getLog(ScpFrom.class);
+
+       private Resource localResource;
+       private String remotePath;
+       private Boolean mkdir = false;
+
+       public void run(Session session) {
+               if (localResource != null) {
+                       File lFile;
+                       try {
+                               lFile = localResource.getFile();
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot interpret resource "
+                                               + localResource + " as file.", e);
+                       }
+                       downloadFile(session, lFile, remotePath);
+               }
+       }
+
+       protected void downloadFile(Session session, File localFile,
+                       String remoteFile) {
+               OutputStream out = null;
+               OutputStream channelOut;
+               InputStream channelIn;
+               try {
+                       // exec 'scp -f rfile' remotely
+                       String command = "scp -f " + remoteFile;
+                       Channel channel = session.openChannel("exec");
+                       ((ChannelExec) channel).setCommand(command);
+
+                       // get I/O streams for remote scp
+                       channelOut = channel.getOutputStream();
+                       channelIn = channel.getInputStream();
+
+                       channel.connect();
+
+                       byte[] buf = new byte[1024];
+
+                       // send '\0'
+                       buf[0] = 0;
+                       channelOut.write(buf, 0, 1);
+                       channelOut.flush();
+
+                       while (true) {
+                               int c = checkAck(channelIn);
+                               if (c != 'C') {
+                                       break;
+                               }
+
+                               // read '0644 '
+                               channelIn.read(buf, 0, 5);
+
+                               long filesize = 0L;
+                               while (true) {
+                                       if (channelIn.read(buf, 0, 1) < 0) {
+                                               // error
+                                               break;
+                                       }
+                                       if (buf[0] == ' ')
+                                               break;
+                                       filesize = filesize * 10L + (long) (buf[0] - '0');
+                               }
+
+                               String remoteFileName = null;
+                               for (int i = 0;; i++) {
+                                       channelIn.read(buf, i, 1);
+                                       if (buf[i] == (byte) 0x0a) {
+                                               remoteFileName = new String(buf, 0, i);
+                                               break;
+                                       }
+                               }
+
+                               // System.out.println("filesize="+filesize+", file="+file);
+
+                               // send '\0'
+                               buf[0] = 0;
+                               channelOut.write(buf, 0, 1);
+                               channelOut.flush();
+
+                               // Create a s adirectory if it doesn't exists
+                               if (!localFile.exists() && mkdir)
+                                       localFile.mkdirs();
+
+                               // read a content of lfile
+                               String localPath = localFile.isDirectory() ? localFile
+                                               .getPath()
+                                               + File.separator + remoteFileName : localFile.getPath();
+
+                               out = new FileOutputStream(localPath);
+                               int foo;
+                               while (true) {
+                                       if (buf.length < filesize)
+                                               foo = buf.length;
+                                       else
+                                               foo = (int) filesize;
+                                       foo = channelIn.read(buf, 0, foo);
+                                       if (foo < 0) {
+                                               // error
+                                               break;
+                                       }
+                                       out.write(buf, 0, foo);
+                                       filesize -= foo;
+                                       if (filesize == 0L)
+                                               break;
+                               }
+
+                               checkAck(channelIn);
+
+                               // send '\0'
+                               buf[0] = 0;
+                               channelOut.write(buf, 0, 1);
+                               channelOut.flush();
+
+                               if (log.isDebugEnabled())
+                                       log.debug("Finished downloading " + remoteFile + " on "
+                                                       + getSshTarget() + " to " + localPath);
+                       }
+
+                       channel.disconnect();
+                       // session.disconnect();
+               } catch (Exception e) {
+                       throw new SlcException("Cannot download " + remoteFile + " to "
+                                       + localFile, e);
+               } finally {
+                       IOUtils.closeQuietly(out);
+               }
+       }
+
+       public void setLocalResource(Resource localFile) {
+               this.localResource = localFile;
+       }
+
+       public void setRemotePath(String remoteFile) {
+               this.remotePath = remoteFile;
+       }
+
+       public void setMkdir(Boolean mkdir) {
+               this.mkdir = mkdir;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/ScpTo.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/ScpTo.java
new file mode 100644 (file)
index 0000000..c0af991
--- /dev/null
@@ -0,0 +1,290 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.Resource;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.util.PathMatcher;
+import org.springframework.util.StringUtils;
+
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.Session;
+
+public class ScpTo extends AbstractJschTask {
+       private final static Log log = LogFactory.getLog(ScpTo.class);
+
+       private Resource localResource;
+       private String remotePath;
+
+       private String dir;
+       private String remoteDir;
+       private List<String> includes = new ArrayList<String>();
+
+       private List<String> excludes = new ArrayList<String>();
+
+       private PathMatcher pathMatcher;
+
+       public void run(Session session) {
+               if (StringUtils.hasText(dir)) {
+                       if (!StringUtils.hasText(remoteDir))
+                               throw new SlcException("Remote dir has to be specified.");
+
+                       String dirOs = dir.replace('/', File.separatorChar);
+                       if (dirOs.charAt(dir.length() - 1) != File.separatorChar) {
+                               dirOs = dirOs + File.separator;
+                       }
+
+                       if (pathMatcher == null)
+                               pathMatcher = new AntPathMatcher();
+
+                       log.info("Start multiple scp based on " + dirOs);
+                       scanDir(session, dirOs, "", includes, excludes);
+               }
+
+               if (localResource != null) {
+                       uploadResource(session, localResource);
+               }
+       }
+
+       protected void scanDir(Session session, String dir, String currentRelPath,
+                       List<String> includes, List<String> excludes) {
+               File[] files = new File(dir).listFiles();
+               for (File file : files) {
+                       if (!file.isDirectory()) {
+                               String relPath = currentRelPath.concat(file.getName());
+                               if (match(relPath, includes, excludes, false)) {
+                                       uploadFile(session, file, remoteDir + '/' + relPath);
+                               }
+                       } else {
+                               String relPath = currentRelPath.concat(file.getName()).concat(
+                                               "/");
+                               if (match(relPath, includes, excludes, true)) {
+                                       String nextDir = dir.concat(file.getName()).concat(
+                                                       File.separator);
+                                       scanDir(session, nextDir, relPath, includes, excludes);
+                               }
+                       }
+               }
+       }
+
+       protected Boolean match(String path, List<String> includes,
+                       List<String> excludes, boolean matchStart) {
+               for (String patternIn : includes) {
+                       boolean matchIn = matchStart ? pathMatcher.matchStart(patternIn,
+                                       path) : pathMatcher.match(patternIn, path);
+                       if (matchIn) {
+                               // Could be included, check excludes
+                               boolean excluded = false;
+                               ex: for (String patternEx : excludes) {
+                                       boolean matchEx = matchStart ? pathMatcher.matchStart(
+                                                       patternEx, path) : pathMatcher.match(patternEx,
+                                                       path);
+
+                                       if (matchEx) {
+                                               excluded = true;
+                                               break ex;
+                                       }
+                               }
+                               if (!excluded)
+                                       return true;
+                       }
+               }
+               return false;
+       }
+
+       protected void uploadFile(Session session, File file, String remoteFile) {
+               try {
+                       upload(session, new FileInputStream(file), file.length(), file
+                                       .getPath(), file.toString(), remoteFile);
+               } catch (FileNotFoundException e) {
+                       throw new SlcException("Cannot upload " + file, e);
+               }
+       }
+
+       protected void uploadResource(Session session, Resource resource) {
+               String targetPath = remotePath != null ? remotePath : remoteDir + '/'
+                               + resource.getFilename();
+               try {
+                       File lFile = resource.getFile();
+                       uploadFile(session, lFile, targetPath);
+               } catch (IOException e) {
+                       // no underlying file found
+                       // load the resource in memory before transferring it
+                       InputStream in = null;
+                       try {
+                               byte[] arr;
+                               String path;
+                               if (resource instanceof ByteArrayResource) {
+                                       arr = ((ByteArrayResource) resource).getByteArray();
+                                       path = "bytearray";
+                               } else {
+                                       in = resource.getInputStream();
+                                       ByteArrayOutputStream out = new ByteArrayOutputStream();
+                                       IOUtils.copy(in, out);
+                                       arr = out.toByteArray();
+                                       path = resource.getURL().getPath();
+                                       if (path.startsWith("/"))
+                                               path = path.substring(1);
+                               }
+                               ByteArrayInputStream content = new ByteArrayInputStream(arr);
+                               upload(session, content, arr.length, path, resource.toString(),
+                                               targetPath);
+                               arr = null;
+                       } catch (IOException e1) {
+                               throw new SlcException("Can not interpret resource "
+                                               + localResource, e1);
+                       } finally {
+                               IOUtils.closeQuietly(in);
+                               // no need to close byte arrays streams
+                       }
+               }
+       }
+
+       protected void upload(Session session, InputStream in, long size,
+                       String path, String sourceDesc, String remoteFile) {
+               OutputStream channelOut;
+               InputStream channelIn;
+               try {
+
+                       // exec 'scp -t rfile' remotely
+                       String command = "scp -p -t " + remoteFile;
+                       Channel channel = session.openChannel("exec");
+                       ((ChannelExec) channel).setCommand(command);
+
+                       // get I/O streams for remote scp
+                       channelOut = channel.getOutputStream();
+                       channelIn = channel.getInputStream();
+
+                       channel.connect();
+                       checkAck(channelIn);
+
+                       // send "C0644 filesize filename", where filename should not include
+                       // '/'
+                       long filesize = size;
+                       command = "C0644 " + filesize + " ";
+                       int index = path.lastIndexOf('/');
+                       if (index > 0) {
+                               command += path.substring(index + 1);
+                       } else {
+                               command += path;
+                       }
+                       command += "\n";
+
+                       channelOut.write(command.getBytes());
+                       channelOut.flush();
+                       checkAck(channelIn);
+
+                       if (log.isTraceEnabled())
+                               log.debug("Start copy of " + sourceDesc + " to " + remoteFile
+                                               + " on " + getSshTarget() + "...");
+
+                       final long oneMB = 1024l;// in KB
+                       final long tenMB = 10 * oneMB;// in KB
+
+                       // send a content of lfile
+                       byte[] buf = new byte[1024];
+                       long cycleCount = 0;
+                       long nbrOfBytes = 0;
+                       while (true) {
+                               int len = in.read(buf, 0, buf.length);
+                               if (len <= 0)
+                                       break;
+                               channelOut.write(buf, 0, len); // out.flush();
+                               nbrOfBytes = nbrOfBytes + len;
+                               if (((cycleCount % oneMB) == 0) && cycleCount != 0)// each 1 MB
+                                       System.out.print('#');
+                               if (((cycleCount % (tenMB)) == 0) && cycleCount != 0)// each 10
+                                       // MB
+                                       System.out.print(" - " + cycleCount / tenMB + "0 MB\n");
+                               cycleCount++;
+                       }
+                       // send '\0'
+                       buf[0] = 0;
+                       channelOut.write(buf, 0, 1);
+                       channelOut.flush();
+                       checkAck(channelIn);
+
+                       if (log.isDebugEnabled())
+                               log.debug("Transferred to " + remoteFile + " ("
+                                               + sizeDesc(nbrOfBytes) + ") on " + getSshTarget()
+                                               + " from " + sourceDesc);
+
+                       IOUtils.closeQuietly(channelOut);
+
+                       channel.disconnect();
+               } catch (Exception e) {
+                       throw new SlcException("Cannot copy " + path + " to " + remoteFile,
+                                       e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+               }
+       }
+
+       protected String sizeDesc(Long nbrOfBytes) {
+               if (nbrOfBytes < 1024)
+                       return nbrOfBytes + " B";
+               else if (nbrOfBytes < 1024 * 1024)
+                       return (nbrOfBytes / 1024) + " KB";
+               else
+                       return nbrOfBytes / (1024 * 1024) + " MB";
+       }
+
+       public void setLocalResource(Resource localFile) {
+               this.localResource = localFile;
+       }
+
+       public void setRemotePath(String remoteFile) {
+               this.remotePath = remoteFile;
+       }
+
+       public void setDir(String dir) {
+               this.dir = dir;
+       }
+
+       public void setRemoteDir(String remoteDir) {
+               this.remoteDir = remoteDir;
+       }
+
+       public void setIncludes(List<String> includes) {
+               this.includes = includes;
+       }
+
+       public void setExcludes(List<String> excludes) {
+               this.excludes = excludes;
+       }
+
+       public void setPathMatcher(PathMatcher pathMatcher) {
+               this.pathMatcher = pathMatcher;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/SimpleUserInfo.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/SimpleUserInfo.java
new file mode 100644 (file)
index 0000000..cabeeb2
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PushbackInputStream;
+import java.util.Arrays;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+
+import com.jcraft.jsch.UserInfo;
+
+/** Basic implementation of user info. */
+public class SimpleUserInfo implements UserInfo {
+       private Boolean permissive = true;
+       private Boolean verbose = false;
+
+       private final static Log log = LogFactory.getLog(SimpleUserInfo.class);
+
+       protected String password;
+       protected char[] passwordSafe;
+       protected String passphrase;
+       protected char[] passphraseSafe;
+
+       public void reset() {
+               if (passwordSafe != null)
+                       Arrays.fill(passwordSafe, (char) 0);
+               passwordSafe = null;
+               if (passphraseSafe != null)
+                       Arrays.fill(passphraseSafe, (char) 0);
+               passphraseSafe = null;
+       }
+
+       public void setPassword(String password) {
+               this.password = password;
+       }
+
+       public void setPassphrase(String passphrase) {
+               this.passphrase = passphrase;
+       }
+
+       public String getPassphrase() {
+               if (passphraseSafe != null)
+                       return new String(passphraseSafe);
+               return passphrase;
+       }
+
+       public String getPassword() {
+               if (passwordSafe != null)
+                       return new String(passwordSafe);
+               return password;
+       }
+
+       public boolean promptPassphrase(String message) {
+               if (permissive)
+                       return true;
+               else {
+                       log.info(message);
+                       passwordSafe = readPassword(System.in);
+                       return passwordSafe != null;
+               }
+       }
+
+       public boolean promptPassword(String message) {
+               if (permissive)
+                       return true;
+               else {
+                       log.info(message);
+                       passwordSafe = readPassword(System.in);
+                       return passwordSafe != null;
+               }
+       }
+
+       public boolean promptYesNo(String message) {
+               String msg = message + " (y/n): ";
+               if (permissive) {
+                       if (verbose)
+                               log.info(msg + "y");
+                       return true;
+               } else {
+                       log.info(msg);
+                       char c;
+                       try {
+                               c = (char) System.in.read();
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot read stdin", e);
+                       }
+                       if (c == 'y')
+                               return true;
+                       else
+                               return false;
+               }
+       }
+
+       public void showMessage(String message) {
+               log.info(message);
+       }
+
+       public void setPermissive(Boolean permissive) {
+               this.permissive = permissive;
+       }
+
+       public void setVerbose(Boolean verbose) {
+               this.verbose = verbose;
+       }
+
+       protected char[] readPassword(InputStream in) {
+
+               try {
+                       char[] lineBuffer;
+                       char[] buf;
+                       // int i;
+
+                       buf = lineBuffer = new char[128];
+
+                       int room = buf.length;
+                       int offset = 0;
+                       int c;
+
+                       loop: while (true) {
+                               switch (c = in.read()) {
+                               case -1:
+                               case '\n':
+                                       break loop;
+
+                               case '\r':
+                                       int c2 = in.read();
+                                       if ((c2 != '\n') && (c2 != -1)) {
+                                               if (!(in instanceof PushbackInputStream)) {
+                                                       in = new PushbackInputStream(in);
+                                               }
+                                               ((PushbackInputStream) in).unread(c2);
+                                       } else
+                                               break loop;
+
+                               default:
+                                       if (--room < 0) {
+                                               buf = new char[offset + 128];
+                                               room = buf.length - offset - 1;
+                                               System.arraycopy(lineBuffer, 0, buf, 0, offset);
+                                               Arrays.fill(lineBuffer, ' ');
+                                               lineBuffer = buf;
+                                       }
+                                       buf[offset++] = (char) c;
+                                       break;
+                               }
+                       }
+
+                       if (offset == 0) {
+                               return null;
+                       }
+
+                       char[] ret = new char[offset];
+                       System.arraycopy(buf, 0, ret, 0, offset);
+                       Arrays.fill(buf, ' ');
+
+                       return ret;
+               } catch (IOException e) {
+                       throw new SlcException("Cannot read password.", e);
+               }
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/SshFilesDeployment.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/SshFilesDeployment.java
new file mode 100644 (file)
index 0000000..9254d7c
--- /dev/null
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.deploy.DigestCheck;
+import org.argeo.slc.core.deploy.ResourceSet;
+import org.springframework.core.io.Resource;
+
+import com.jcraft.jsch.Session;
+
+public class SshFilesDeployment extends AbstractJschTask implements Runnable {
+       private final static Log log = LogFactory.getLog(SshFilesDeployment.class);
+       private String targetBase = "";
+       private ResourceSet resourceSet;
+       /**
+        * Activate with algorithm as per
+        * http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#AppA
+        */
+       private String checksum = "MD5";
+       private int remoteChecksumsPerCall = 20;
+
+       public SshFilesDeployment() {
+       }
+
+       public SshFilesDeployment(SshTarget sshTarget, ResourceSet resourceSet) {
+               setSshTarget(sshTarget);
+               this.resourceSet = resourceSet;
+       }
+
+       @Override
+       void run(Session session) {
+               JschMultiTasks multiTasks = new JschMultiTasks();
+
+               Map<String, Resource> resources = resourceSet.listResources();
+
+               // Analyze set
+               List<String> subDirs = new ArrayList<String>();
+               Map<String, String> targetPaths = new HashMap<String, String>();
+               for (String relPath : resources.keySet()) {
+                       String parentDir;
+                       int lastIndexSubDir = relPath.lastIndexOf('/');
+                       if (lastIndexSubDir > 0)
+                               parentDir = targetBase + '/'
+                                               + relPath.substring(0, lastIndexSubDir);
+                       else
+                               parentDir = targetBase;
+
+                       boolean skipDir = false;
+                       registerDirs: for (String registeredDir : new ArrayList<String>(
+                                       subDirs)) {
+                               if (parentDir.equals(registeredDir)) {
+                                       if (log.isTraceEnabled())
+                                               log.trace("Already registered, skip " + parentDir);
+                                       skipDir = true;
+                                       break registerDirs;
+                               }
+
+                               if (parentDir.startsWith(registeredDir))
+                                       if (subDirs.contains(registeredDir)) {
+                                               subDirs.remove(registeredDir);
+                                               if (log.isTraceEnabled())
+                                                       log.trace("Remove parent " + registeredDir + " of "
+                                                                       + parentDir);
+                                               continue registerDirs;
+                                       }
+
+                               if (registeredDir.startsWith(parentDir)) {
+                                       skipDir = true;
+                                       if (log.isTraceEnabled())
+                                               log.trace("Skip " + parentDir
+                                                               + " because child already registered.");
+                                       break registerDirs;
+                               }
+                       }
+
+                       if (!subDirs.contains(parentDir) && !skipDir) {
+                               subDirs.add(parentDir);
+                       }
+
+                       targetPaths.put(relPath, targetBase + "/" + relPath);
+               }
+
+               // checksum
+               List<String> targetPathsEqualsToLocal = new ArrayList<String>();
+               if (checksum != null) {
+                       Map<String, String> remoteChecksums = new HashMap<String, String>();
+                       List<String> csLines = new ArrayList<String>();
+                       String csExecutable;
+                       if ("MD5".equals(checksum))
+                               csExecutable = "/usr/bin/md5sum";
+                       else if ("SHA".equals(checksum))
+                               csExecutable = "/usr/bin/sha1sum";
+                       else if ("SHA-256".equals(checksum))
+                               csExecutable = "/usr/bin/sha256sum";
+                       else if ("SHA-512".equals(checksum))
+                               csExecutable = "/usr/bin/sha512sum";
+                       else
+                               throw new SlcException(
+                                               "Don't know how to remotely execute checksum "
+                                                               + checksum);
+
+                       StringBuffer csCmd = new StringBuffer(csExecutable);
+                       int numberOfPaths = targetPaths.size();
+                       int count = 0;
+                       for (String targetPath : targetPaths.values()) {
+                               csCmd.append(" ").append(targetPath);
+                               count++;
+
+                               if ((count % remoteChecksumsPerCall == 0)
+                                               || count == numberOfPaths) {
+                                       RemoteExec remoteCs = new RemoteExec();
+                                       remoteCs.setSshTarget(getSshTarget());
+                                       remoteCs.setCommand(csCmd.toString());
+                                       remoteCs.setStdOutLines(csLines);
+                                       remoteCs.setFailOnBadExitStatus(false);
+                                       remoteCs.run(session);
+                                       csCmd = new StringBuffer(csExecutable);
+                               }
+
+                       }
+
+                       remoteChecksums: for (String csLine : csLines) {
+                               StringTokenizer st = new StringTokenizer(csLine, ": ");
+                               String cs = st.nextToken();
+                               if (cs.equals(csExecutable)) {
+                                       // remote does not exist
+                                       continue remoteChecksums;
+                               } else {
+                                       String targetPath = st.nextToken();
+                                       if (log.isTraceEnabled())
+                                               log.trace("REMOTE: " + targetPath + "=" + cs);
+                                       remoteChecksums.put(targetPath, cs);
+                               }
+                       }
+
+                       // Local checksums
+                       for (String relPath : resources.keySet()) {
+                               Resource resource = resources.get(relPath);
+                               String targetPath = targetPaths.get(relPath);
+                               if (remoteChecksums.containsKey(targetPath)) {
+                                       String cs = DigestCheck.digest(checksum, resource);
+                                       if (log.isTraceEnabled())
+                                               log.trace("LOCAL : " + targetPath + "=" + cs);
+                                       if (remoteChecksums.get(targetPath).equals(cs))
+                                               targetPathsEqualsToLocal.add(targetPath);
+                               }
+                       }
+               }
+
+               // Prepare multitask
+
+               // Create dirs
+               StringBuffer mkdirCmd = new StringBuffer("mkdir -p");
+               RemoteExec remoteExec = new RemoteExec();
+               for (String dir : subDirs) {
+                       // remoteExec.getCommands().add("mkdir -p " + dir);
+                       mkdirCmd.append(' ');
+                       if (dir.indexOf(' ') >= 0)
+                               mkdirCmd.append('\"').append(dir).append('\"');
+                       else
+                               mkdirCmd.append(dir);
+               }
+               remoteExec.setCommand(mkdirCmd.toString());
+               multiTasks.getTasks().add(remoteExec);
+
+               // Perform copies
+               int copied = 0;
+               int skipped = 0;
+               copy: for (String relPath : resources.keySet()) {
+                       String targetPath = targetPaths.get(relPath);
+                       if (targetPathsEqualsToLocal.contains(targetPath)) {
+                               if (log.isTraceEnabled())
+                                       log.trace("Skip copy of " + relPath
+                                                       + " since it is equal to remote " + targetPath);
+                               skipped++;
+                               continue copy;
+                       }
+                       // Copy resource
+                       Resource resource = resources.get(relPath);
+                       ScpTo scpTo = new ScpTo();
+                       scpTo.setLocalResource(resource);
+                       scpTo.setRemotePath(targetPath);
+                       multiTasks.getTasks().add(scpTo);
+                       copied++;
+                       // TODO: set permissions
+               }
+
+               multiTasks.setSshTarget(getSshTarget());
+               multiTasks.run(session);
+
+               if (checksum != null && log.isDebugEnabled())
+                       log.debug("Copied " + copied + " files, skipped " + skipped
+                                       + " with same checksum.");
+       }
+
+       public void setTargetBase(String targetBase) {
+               this.targetBase = targetBase;
+       }
+
+       public void setResourceSet(ResourceSet resourceSet) {
+               this.resourceSet = resourceSet;
+       }
+
+       public void setChecksum(String checksum) {
+               this.checksum = checksum;
+       }
+
+       /** Number of remote checksums per remote call */
+       public void setRemoteChecksumsPerCall(int remoteChecksumsPerCall) {
+               this.remoteChecksumsPerCall = remoteChecksumsPerCall;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/SshShell.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/SshShell.java
new file mode 100644 (file)
index 0000000..cb1b724
--- /dev/null
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.springframework.core.io.Resource;
+import org.springframework.util.StringUtils;
+
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.Session;
+
+public class SshShell extends AbstractJschTask {
+       private final static Log log = LogFactory.getLog(SshShell.class);
+       private Resource input;
+
+       @Override
+       void run(Session session) {
+               try {
+                       final Channel channel = session.openChannel("shell");
+
+                       // Enable agent-forwarding.
+                       // ((ChannelShell)channel).setAgentForwarding(true);
+
+                       // channel.setInputStream(System.in);
+                       // channel.setInputStream(input.getInputStream());
+                       /*
+                        * // a hack for MS-DOS prompt on Windows.
+                        * channel.setInputStream(new FilterInputStream(System.in){ public
+                        * int read(byte[] b, int off, int len)throws IOException{ return
+                        * in.read(b, off, (len>1024?1024:len)); } });
+                        */
+
+                       // channel.setOutputStream(System.out);
+
+                       /*
+                        * // Choose the pty-type "vt102".
+                        * ((ChannelShell)channel).setPtyType("vt102");
+                        */
+
+                       /*
+                        * // Set environment variable "LANG" as "ja_JP.eucJP".
+                        * ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
+                        */
+
+                       // Writer thread
+                       final BufferedWriter writer = new BufferedWriter(
+                                       new OutputStreamWriter(channel.getOutputStream()));
+
+                       // channel.connect();
+                       channel.connect(3 * 1000);
+
+                       // while (!channel.isConnected())
+                       // try {
+                       // Thread.sleep(500);
+                       // } catch (InterruptedException e1) {
+                       // // silent
+                       // }
+
+                       Thread writerThread = new Thread("Shell writer " + getSshTarget()) {
+
+                               @Override
+                               public void run() {
+
+                                       if (log.isDebugEnabled())
+                                               log.debug("Start writing to shell");
+
+                                       BufferedReader reader = null;
+                                       try {
+                                               reader = new BufferedReader(new InputStreamReader(input
+                                                               .getInputStream()));
+                                               String line = null;
+                                               while ((line = reader.readLine()) != null) {
+                                                       if (!StringUtils.hasText(line))
+                                                               continue;
+                                                       writer.write(line);
+                                                       writer.newLine();
+                                               }
+                                               writer.append("exit");
+                                               writer.newLine();
+                                               writer.flush();
+                                               // channel.disconnect();
+                                       } catch (IOException e) {
+                                               throw new SlcException("Cannot write to shell on "
+                                                               + getSshTarget(), e);
+                                       } finally {
+                                               IOUtils.closeQuietly(reader);
+                                       }
+                               }
+                       };
+                       writerThread.start();
+
+                       BufferedReader execIn = null;
+                       try {
+                               execIn = new BufferedReader(new InputStreamReader(channel
+                                               .getInputStream()));
+                               String line = null;
+                               while ((line = execIn.readLine()) != null) {
+                                       if (!line.trim().equals(""))
+                                               log.info(line);
+                               }
+                       } catch (Exception e) {
+                               throw new SlcException("Cannot read from shell on "
+                                               + getSshTarget(), e);
+                       } finally {
+                               IOUtils.closeQuietly(execIn);
+                       }
+
+               } catch (Exception e) {
+                       throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
+                                       e);
+               }
+       }
+
+       public void setInput(Resource input) {
+               this.input = input;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/SshTarget.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/SshTarget.java
new file mode 100644 (file)
index 0000000..eeebbc6
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.io.File;
+
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.UserInfo;
+
+public class SshTarget {
+       private String host;
+       private Integer port = 22;
+       private String user;
+       private UserInfo userInfo = new SimpleUserInfo();
+
+       private Boolean usePrivateKey = true;
+       private File localPrivateKey = new File(System.getProperty("user.home")
+                       + File.separator + ".ssh" + File.separator + "id_rsa");
+
+       /** cached session */
+       private transient Session session;
+
+       public String getHost() {
+               return host;
+       }
+
+       public void setHost(String host) {
+               this.host = host;
+       }
+
+       public Integer getPort() {
+               return port;
+       }
+
+       public void setPort(Integer port) {
+               this.port = port;
+       }
+
+       public String getUser() {
+               return user;
+       }
+
+       public void setUser(String user) {
+               this.user = user;
+       }
+
+       public UserInfo getUserInfo() {
+               return userInfo;
+       }
+
+       public void setUserInfo(UserInfo userInfo) {
+               this.userInfo = userInfo;
+       }
+
+       public void setLocalPrivateKey(File localPrivateKey) {
+               this.localPrivateKey = localPrivateKey;
+       }
+
+       public File getLocalPrivateKey() {
+               return localPrivateKey;
+       }
+
+       public Boolean getUsePrivateKey() {
+               return usePrivateKey;
+       }
+
+       public void setUsePrivateKey(Boolean usePrivateKey) {
+               this.usePrivateKey = usePrivateKey;
+       }
+
+       public String toString() {
+               return getUser() + "@" + getHost() + ":" + getPort();
+       }
+
+       public synchronized Session getSession() {
+               return session;
+       }
+
+       public synchronized void setSession(Session session) {
+               this.session = session;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/jsch/SwingUserInfo.java b/org.argeo.slc.support/src/org/argeo/slc/jsch/SwingUserInfo.java
new file mode 100644 (file)
index 0000000..963cbab
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.jsch;
+
+import java.awt.Container;
+import java.awt.GridLayout;
+import java.awt.Panel;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Arrays;
+
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JPasswordField;
+
+/** Retrieves a password or a passphrase using standard Swing */
+public class SwingUserInfo extends SimpleUserInfo {
+
+       private Boolean alwaysPrompt = false;
+
+       public boolean promptPassphrase(String message) {
+               if (passphrase != null)
+                       return true;
+
+               if (!alwaysPrompt && passphraseSafe != null)
+                       return true;
+
+               PasswordDialog dialog = new PasswordDialog(message) {
+                       private static final long serialVersionUID = 3266299327166418364L;
+
+                       @Override
+                       protected void useCredentials(char[] password) {
+                               passphraseSafe = new char[password.length];
+                               System.arraycopy(password, 0, passphraseSafe, 0,
+                                               password.length);
+                               // passphraseSafe = Arrays.copyOf(password, password.length);
+                       }
+               };
+               dialog.setVisible(true);
+               return dialog.getWasProvided();
+       }
+
+       public boolean promptPassword(String message) {
+               if (password != null)
+                       return true;
+
+               if (!alwaysPrompt && passwordSafe != null)
+                       return true;
+
+               PasswordDialog dialog = new PasswordDialog(message) {
+                       private static final long serialVersionUID = 3266299327166418364L;
+
+                       @Override
+                       protected void useCredentials(char[] password) {
+                               // passwordSafe = Arrays.copyOf(password, password.length);
+                               passwordSafe = new char[password.length];
+                               System.arraycopy(password, 0, passwordSafe, 0, password.length);
+                       }
+               };
+               dialog.setVisible(true);
+               return dialog.getWasProvided();
+       }
+
+       public void setAlwaysPrompt(Boolean alwaysPrompt) {
+               this.alwaysPrompt = alwaysPrompt;
+       }
+
+       protected static class PasswordDialog extends JDialog implements
+                       ActionListener {
+               private static final long serialVersionUID = 3399155607980846207L;
+
+               private static final String OK = "ok";
+
+               private JPasswordField password = new JPasswordField("", 10);
+
+               private JButton okButton;
+               private JButton cancelButton;
+
+               private Boolean wasProvided = false;
+
+               public PasswordDialog(String title) {
+                       setTitle(title);
+                       setModal(true);
+                       setLocationRelativeTo(null);
+                       setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+
+                       JPanel p1 = new JPanel(new GridLayout(1, 2, 3, 3));
+                       p1.add(new JLabel("Password"));
+                       password.setActionCommand(OK);
+                       password.addActionListener(this);
+                       p1.add(password);
+                       add("Center", p1);
+
+                       Panel p2 = new Panel();
+                       okButton = addButton(p2, "OK");
+                       okButton.setActionCommand(OK);
+                       cancelButton = addButton(p2, "Cancel");
+                       add("South", p2);
+                       setSize(240, 120);
+
+                       pack();
+               }
+
+               /** To be overridden */
+               protected void useCredentials(char[] password) {
+                       // does nothing
+               }
+
+               private JButton addButton(Container c, String name) {
+                       JButton button = new JButton(name);
+                       button.addActionListener(this);
+                       c.add(button);
+                       return button;
+               }
+
+               public final void actionPerformed(ActionEvent evt) {
+                       Object source = evt.getSource();
+                       if (source == okButton || evt.getActionCommand().equals(OK)) {
+                               char[] p = password.getPassword();
+                               useCredentials(p);
+                               wasProvided = true;
+                               Arrays.fill(p, '0');
+                               cleanUp();
+                       } else if (source == cancelButton)
+                               cleanUp();
+               }
+
+               private void cleanUp() {
+                       password.setText("");
+                       dispose();
+               }
+
+               public Boolean getWasProvided() {
+                       return wasProvided;
+               }
+
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java b/org.argeo.slc.support/src/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java
new file mode 100644 (file)
index 0000000..d2bb56b
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.jcr;
+
+import java.util.UUID;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+
+import javax.jcr.Credentials;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryFactory;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelectInfo;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+
+/** Backups a JCR repository */
+public class JcrRepositoryBackup implements Runnable {
+       private final static Log log = LogFactory.getLog(JcrRepositoryBackup.class);
+
+       private String sourceRepo;
+       private String sourceDatastore;
+       private String targetFile;
+
+       private String sourceWksp;
+
+       private String sourceUsername;
+       private char[] sourcePassword;
+
+       private RepositoryFactory repositoryFactory;
+       private FileSystemManager fileSystemManager;
+
+       public void run() {
+               Session sourceDefaultSession = null;
+               try {
+                       long begin = System.currentTimeMillis();
+
+                       FileObject archiveRoot = fileSystemManager.resolveFile(targetFile);
+                       archiveRoot.createFolder();
+
+                       String datastoreFolderName = "datastore";
+                       if (hasDatastore())
+                               backupDataStore(archiveRoot.resolveFile(datastoreFolderName));
+
+                       Repository sourceRepository = ArgeoJcrUtils.getRepositoryByUri(
+                                       repositoryFactory, sourceRepo);
+                       Credentials sourceCredentials = null;
+                       if (sourceUsername != null)
+                               sourceCredentials = new SimpleCredentials(sourceUsername,
+                                               sourcePassword);
+
+                       sourceDefaultSession = sourceRepository.login(sourceCredentials);
+                       for (String sourceWorkspaceName : sourceDefaultSession
+                                       .getWorkspace().getAccessibleWorkspaceNames()) {
+                               if (Thread.interrupted()) {
+                                       log.error("Workspace backup interrupted");
+                                       Thread.currentThread().interrupt();
+                                       return;
+                               }
+
+                               if (sourceWksp != null && !sourceWksp.trim().equals("")
+                                               && !sourceWorkspaceName.equals(sourceWksp))
+                                       continue;
+                               Session sourceSession = null;
+                               JarOutputStream out = null;
+                               FileObject workspaceBackup = null;
+                               try {
+                                       Manifest manifest = new Manifest();
+                                       manifest.getMainAttributes().put(
+                                                       Attributes.Name.MANIFEST_VERSION, "1.0");
+                                       manifest.getMainAttributes().putValue("Backup-UUID",
+                                                       UUID.randomUUID().toString());
+                                       manifest.getMainAttributes().putValue("Backup-Timestamp",
+                                                       Long.toString(System.currentTimeMillis()));
+                                       manifest.getMainAttributes().putValue(
+                                                       "Backup-JCR-Workspace", sourceWorkspaceName);
+                                       workspaceBackup = fileSystemManager.resolveFile(targetFile
+                                                       + "/" + sourceWorkspaceName + ".jar");
+
+                                       out = new JarOutputStream(workspaceBackup.getContent()
+                                                       .getOutputStream(), manifest);
+                                       sourceSession = sourceRepository.login(sourceCredentials,
+                                                       sourceWorkspaceName);
+                                       backupWorkspace(sourceSession, out);
+                               } finally {
+                                       JcrUtils.logoutQuietly(sourceSession);
+                                       IOUtils.closeQuietly(out);
+                                       if (workspaceBackup != null)
+                                               workspaceBackup.close();
+                               }
+                       }
+
+                       // in case some binaries have been added during the backup
+                       if (hasDatastore())
+                               backupDataStore(archiveRoot.resolveFile(datastoreFolderName));
+
+                       long duration = (System.currentTimeMillis() - begin) / 1000;// s
+                       log.info("Backed-up " + sourceRepo + " in " + (duration / 60)
+                                       + "min " + (duration % 60) + "s");
+               } catch (Exception e) {
+                       throw new SlcException("Cannot backup " + sourceRepo, e);
+               } finally {
+                       JcrUtils.logoutQuietly(sourceDefaultSession);
+               }
+       }
+
+       protected Boolean hasDatastore() {
+               return sourceDatastore != null && !sourceDatastore.trim().equals("");
+       }
+
+       protected void backupWorkspace(Session sourceSession, JarOutputStream out) {
+               try {
+                       if (log.isTraceEnabled())
+                               log.trace("Backup " + sourceSession.getWorkspace().getName()
+                                               + "...");
+                       Boolean skipBinaries = hasDatastore();
+                       for (NodeIterator it = sourceSession.getRootNode().getNodes(); it
+                                       .hasNext();) {
+                               if (Thread.interrupted()) {
+                                       log.error("Node backup interrupted");
+                                       Thread.currentThread().interrupt();
+                                       return;
+                               }
+                               Node node = it.nextNode();
+                               JarEntry entry = new JarEntry(node.getPath());
+                               out.putNextEntry(entry);
+                               sourceSession.exportSystemView(node.getPath(), out,
+                                               skipBinaries, false);
+                               out.flush();
+                               out.closeEntry();
+                       }
+                       if (log.isDebugEnabled())
+                               log.debug("Backed up " + sourceSession.getWorkspace().getName());
+               } catch (Exception e) {
+                       throw new SlcException("Cannot backup "
+                                       + sourceSession.getWorkspace().getName(), e);
+               }
+       }
+
+       protected void backupDataStore(final FileObject targetDatastore) {
+               try {
+                       targetDatastore.createFolder();
+                       final FileObject sourceDataStore = fileSystemManager
+                                       .resolveFile(sourceDatastore);
+                       if (log.isDebugEnabled())
+                               log.debug("Backup " + sourceDatastore);
+                       targetDatastore.copyFrom(sourceDataStore, new FileSelector() {
+                               public boolean traverseDescendents(FileSelectInfo fileInfo)
+                                               throws Exception {
+                                       return true;
+                               }
+
+                               public boolean includeFile(FileSelectInfo fileInfo)
+                                               throws Exception {
+                                       String relativeName = fileInfo
+                                                       .getFile()
+                                                       .getName()
+                                                       .getPath()
+                                                       .substring(
+                                                                       sourceDataStore.getName().getPath()
+                                                                                       .length());
+                                       FileObject target = targetDatastore
+                                                       .resolveFile(relativeName);
+                                       if (target.exists()) {
+                                               return false;
+                                       } else {
+                                               return true;
+                                       }
+                               }
+                       });
+                       if (log.isDebugEnabled())
+                               log.debug("Backed-up " + sourceDatastore);
+               } catch (FileSystemException e) {
+                       throw new SlcException("Cannot backup datastore", e);
+               }
+       }
+
+       public void setSourceRepo(String sourceRepo) {
+               this.sourceRepo = sourceRepo;
+       }
+
+       public void setSourceWksp(String sourceWksp) {
+               this.sourceWksp = sourceWksp;
+       }
+
+       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
+               this.repositoryFactory = repositoryFactory;
+       }
+
+       public void setSourceUsername(String sourceUsername) {
+               this.sourceUsername = sourceUsername;
+       }
+
+       public void setSourcePassword(char[] sourcePassword) {
+               this.sourcePassword = sourcePassword;
+       }
+
+       public void setFileSystemManager(FileSystemManager fileSystemManager) {
+               this.fileSystemManager = fileSystemManager;
+       }
+
+       public void setTargetFile(String targetFile) {
+               this.targetFile = targetFile;
+       }
+
+       public void setSourceDatastore(String sourceDatastore) {
+               this.sourceDatastore = sourceDatastore;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java
new file mode 100644 (file)
index 0000000..641e404
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import org.argeo.slc.core.deploy.MultiResourceSet;
+import org.argeo.slc.core.deploy.ResourceSet;
+
+public class DefaultRedhatDeploymentData implements RedhatDeploymentData {
+       private ResourceSet configurationFiles;
+       private String runlevelsScript;
+       private String permissionsScript;
+
+       private RedhatDeploymentData parent;
+
+       public ResourceSet getConfigurationFiles() {
+               if (parent != null && parent.getConfigurationFiles() != null) {
+                       MultiResourceSet mrs = new MultiResourceSet();
+                       mrs.getResourceSets().add(parent.getConfigurationFiles());
+                       mrs.getResourceSets().add(configurationFiles);
+                       return mrs;
+               } else {
+                       return configurationFiles;
+               }
+       }
+
+       public String getRunlevelsScript() {
+               if (parent != null && parent.getRunlevelsScript() != null)
+                       return parent.getRunlevelsScript() + "\n" + runlevelsScript;
+               else
+                       return runlevelsScript;
+       }
+
+       public String getPermissionsScript() {
+               if (parent != null && parent.getPermissionsScript() != null)
+                       return parent.getPermissionsScript() + "\n" + permissionsScript;
+               else
+                       return permissionsScript;
+       }
+
+       public void setRunlevelsScript(String runlevelsScript) {
+               this.runlevelsScript = runlevelsScript;
+       }
+
+       public void setConfigurationFiles(ResourceSet configurationFiles) {
+               this.configurationFiles = configurationFiles;
+       }
+
+       public void setPermissionsScript(String permissionsScript) {
+               this.permissionsScript = permissionsScript;
+       }
+
+       public void setParent(RedhatDeploymentData parentDeploymentData) {
+               this.parent = parentDeploymentData;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRpmDistribution.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DefaultRpmDistribution.java
new file mode 100644 (file)
index 0000000..0e51a23
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import java.util.List;
+
+public class DefaultRpmDistribution implements RpmDistribution {
+       private List<String> additionalPackages;
+
+       public String getDistributionId() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public List<String> getAdditionalPackages() {
+               return additionalPackages;
+       }
+
+       public void setAdditionalPackages(List<String> additionalPackages) {
+               this.additionalPackages = additionalPackages;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DeployLxcContainer.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/DeployLxcContainer.java
new file mode 100644 (file)
index 0000000..3325dc0
--- /dev/null
@@ -0,0 +1,84 @@
+package org.argeo.slc.lib.linux;
+
+import java.io.File;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+
+/** Deploy and initialize an LXC container. */
+public class DeployLxcContainer implements Runnable {
+
+       private String chroot;
+
+       private Resource hostScript = new ClassPathResource(
+                       "/org/argeo/slc/lib/linux/lxc-init-host.sh", getClass()
+                                       .getClassLoader());
+       private Resource guestScript = new ClassPathResource(
+                       "/org/argeo/slc/lib/linux/lxc-init-guest.sh", getClass()
+                                       .getClassLoader());;
+
+       // private CallbackHandler callbackHandler;
+
+       private Integer ram = 1024;
+       private Integer vcpu = 2;
+
+       @Override
+       public void run() {
+               if (chroot == null || chroot.trim().equals(""))
+                       throw new SlcException("A chroot directory must be defined");
+
+               File chrootDir = new File(chroot);
+               chrootDir.mkdirs();
+
+               ScriptCall hostCall = new ScriptCall(hostScript);
+               hostCall.setLogCommand(true);
+               hostCall.arg(chroot);
+               // hostCall.getEnvironmentVariables().put("CHROOT", chroot);
+               // hostCall.setSudo("");
+               // hostCall.setCallbackHandler(callbackHandler);
+               hostCall.run();
+
+               ScriptCall guestCall = new ScriptCall(guestScript);
+               guestCall.setLogCommand(true);
+               // guestCall.setSudo("");
+               // guestCall.setCallbackHandler(callbackHandler);
+               guestCall.setChroot(chroot);
+               guestCall.run();
+
+               SystemCall virtInstall = new SystemCall(
+                               "virt-install --connect lxc:/// --name " + chrootDir.getName()
+                                               + " --ram " + ram + " --vcpu " + vcpu
+                                               + " --filesystem " + chrootDir.getAbsolutePath()
+                                               + ",/ --noautoconsole");
+               virtInstall.setLogCommand(true);
+               // virtInstall.setSudo("");
+               virtInstall.run();
+       }
+
+       public void setChroot(String chroot) {
+               this.chroot = chroot;
+       }
+
+       public void setHostScript(Resource hostScript) {
+               this.hostScript = hostScript;
+       }
+
+       public void setGuestScript(Resource guestScript) {
+               this.guestScript = guestScript;
+       }
+
+       // public void setCallbackHandler(CallbackHandler callbackHandler) {
+       // this.callbackHandler = callbackHandler;
+       // }
+
+       public void setRam(Integer ram) {
+               this.ram = ram;
+       }
+
+       public void setVcpu(Integer vcpu) {
+               this.vcpu = vcpu;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatDeploymentData.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatDeploymentData.java
new file mode 100644 (file)
index 0000000..e62bb1c
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import org.argeo.slc.core.deploy.ResourceSet;
+import org.argeo.slc.deploy.DeploymentData;
+
+public interface RedhatDeploymentData extends DeploymentData {
+       public ResourceSet getConfigurationFiles();
+
+       public String getRunlevelsScript();
+
+       public String getPermissionsScript();
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatHostManager.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RedhatHostManager.java
new file mode 100644 (file)
index 0000000..a59b664
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.deploy.LocalFilesDeployment;
+import org.argeo.slc.core.deploy.ResourceSet;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.argeo.slc.jsch.RemoteExec;
+import org.argeo.slc.jsch.SshFilesDeployment;
+import org.argeo.slc.jsch.SshTarget;
+
+public class RedhatHostManager {
+
+       private SimpleLinuxHost host;
+
+       // SSH
+       private Boolean useSsh = true;
+       private SshTarget sshTarget = null;
+
+       public void installPackages() {
+               StringBuffer cmd = new StringBuffer("yum --nogpgcheck -y install");
+               for (String pkg : ((RpmDistribution) host.getDistribution())
+                               .getAdditionalPackages()) {
+                       cmd.append(' ').append(pkg);
+               }
+               executeCommand(cmd.toString());
+
+               RedhatDeploymentData rdd = (RedhatDeploymentData) host
+                               .getDeploymentData();
+               executeCommand(rdd.getRunlevelsScript());
+       }
+
+       public void deployConfig() {
+               RedhatDeploymentData rdd = (RedhatDeploymentData) host
+                               .getDeploymentData();
+               deploy(rdd.getConfigurationFiles());
+               executeCommand(rdd.getPermissionsScript());
+       }
+
+       // GENERIC?
+       protected void deploy(ResourceSet resourceSet) {
+               if (useSsh)
+                       new SshFilesDeployment(getSshTarget(), resourceSet).run();
+               else
+                       new LocalFilesDeployment(resourceSet).run();
+
+       }
+
+       protected void executeCommand(String command) {
+               if (command == null)
+                       return;
+
+               if (useSsh) {
+                       RemoteExec rExec = new RemoteExec(getSshTarget(), command);
+                       rExec.setFailOnBadExitStatus(false);
+                       rExec.run();
+               } else
+                       new SystemCall(command).run();
+       }
+
+       protected SshTarget getSshTarget() {
+               if (sshTarget == null)
+                       throw new SlcException("No SSH target defined");
+               return sshTarget;
+       }
+
+       public void setHost(SimpleLinuxHost host) {
+               this.host = host;
+       }
+
+       public void setUseSsh(Boolean useSsh) {
+               this.useSsh = useSsh;
+       }
+
+       public void setSshTarget(SshTarget sshTarget) {
+               this.sshTarget = sshTarget;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RpmDistribution.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/RpmDistribution.java
new file mode 100644 (file)
index 0000000..6b4d9b5
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import java.util.List;
+
+import org.argeo.slc.build.Distribution;
+
+public interface RpmDistribution extends Distribution {
+       public List<String> getAdditionalPackages();
+
+       public void setAdditionalPackages(List<String> additionalPackages);
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/ScriptCall.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/ScriptCall.java
new file mode 100644 (file)
index 0000000..d4f664a
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.core.io.Resource;
+
+/** Call to the interpreter of a script language. */
+public class ScriptCall extends SystemCall implements InitializingBean {
+       private Resource script;
+       private List<Object> scriptArgs = new ArrayList<Object>();
+
+       private Boolean localScriptCopy = false;
+
+       /** For use in Spring. */
+       public ScriptCall() {
+               super();
+       }
+
+       /** For use in code ({@link #init()} is called). */
+       public ScriptCall(Resource script) {
+               this.script = script;
+               init();
+       }
+
+       public void init() {
+               initInterpreter();
+               for (Object obj : scriptArgs) {
+                       arg(obj.toString());
+               }
+       }
+
+       public void afterPropertiesSet() throws Exception {
+               init();
+       }
+
+       protected void initInterpreter() {
+               String ext = FilenameUtils.getExtension(script.getFilename());
+
+               if (localScriptCopy) {
+                       File scriptFile = copyScript();
+                       if ("sh".equals(ext))
+                               arg("/bin/sh").arg(scriptFile.getAbsolutePath());
+                       else if ("pl".equals(ext))
+                               arg("/usr/bin/perl").arg(scriptFile.getAbsolutePath());
+                       else if ("py".equals(ext))
+                               arg("/usr/bin/python").arg(scriptFile.getAbsolutePath());
+                       else
+                               throw new SlcException(
+                                               "Cannot initialize script intepreter for " + script);
+               } else {
+                       setStdInFile(script);
+                       if ("sh".equals(ext))
+                               arg("/bin/sh").arg("-s");
+                       else if ("pl".equals(ext))
+                               arg("/usr/bin/perl").arg("/dev/stdin");
+                       else if ("py".equals(ext))
+                               arg("/usr/bin/python").arg("-");
+                       else
+                               throw new SlcException(
+                                               "Cannot initialize script intepreter for " + script);
+               }
+       }
+
+       private File copyScript() {
+               InputStream in = null;
+               OutputStream out = null;
+               try {
+                       File scriptFile = File.createTempFile("script", ".sh");
+                       scriptFile.deleteOnExit();
+                       in = script.getInputStream();
+                       out = new FileOutputStream(scriptFile);
+                       IOUtils.copy(in, out);
+                       return scriptFile;
+               } catch (Exception e) {
+                       throw new SlcException("Cannot copy " + script, e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+               }
+       }
+
+       public void setScript(Resource script) {
+               this.script = script;
+       }
+
+       public void setScriptArgs(List<Object> scriptArgs) {
+               this.scriptArgs = scriptArgs;
+       }
+
+       public void setLocalScriptCopy(Boolean localScriptCopy) {
+               this.localScriptCopy = localScriptCopy;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/SimpleLinuxHost.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/SimpleLinuxHost.java
new file mode 100644 (file)
index 0000000..b25e9f4
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux;
+
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.deploy.DeployedSystem;
+import org.argeo.slc.deploy.DeploymentData;
+import org.argeo.slc.deploy.TargetData;
+
+public class SimpleLinuxHost implements DeployedSystem {
+       private DeploymentData deploymentData;
+       private Distribution distribution;
+       private TargetData targetData;
+
+       public String getDeployedSystemId() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public DeploymentData getDeploymentData() {
+               return deploymentData;
+       }
+
+       public void setDeploymentData(DeploymentData deploymentData) {
+               this.deploymentData = deploymentData;
+       }
+
+       public Distribution getDistribution() {
+               return distribution;
+       }
+
+       public void setDistribution(Distribution distribution) {
+               this.distribution = distribution;
+       }
+
+       public TargetData getTargetData() {
+               return targetData;
+       }
+
+       public void setTargetData(TargetData targetData) {
+               this.targetData = targetData;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-guest.sh b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-guest.sh
new file mode 100644 (file)
index 0000000..11ecc4e
--- /dev/null
@@ -0,0 +1,29 @@
+echo demo | passwd root --stdin
+
+#Fix root login on console
+echo "pts/0" >>/etc/securetty
+sed -i s/"session    required     pam_selinux.so close"/"#session    required     pam_selinux.so close"/g /etc/pam.d/login
+sed -i s/"session    required     pam_selinux.so open"/"#session    required     pam_selinux.so open"/g /etc/pam.d/login
+sed -i s/"session    required     pam_loginuid.so"/"#session    required     pam_loginuid.so"/g /etc/pam.d/login
+
+#Configuring basic networking
+cat > /etc/sysconfig/network << EOF
+NETWORKING=yes
+HOSTNAME=demo
+EOF
+cat > /etc/sysconfig/network-scripts/ifcfg-eth0 << EOF
+DEVICE=eth0
+BOOTPROTO=dhcp
+ONBOOT=yes
+EOF
+
+#Enabling sshd
+chkconfig sshd on
+
+# Fixing root login for sshd
+sed -i s/"session    required     pam_selinux.so close"/"#session    required     pam_selinux.so close"/g /etc/pam.d/sshd
+sed -i s/"session    required     pam_loginuid.so"/"#session    required     pam_loginuid.so"/g /etc/pam.d/sshd
+sed -i s/"session    required     pam_selinux.so open env_params"/"#session    required     pam_selinux.so open env_params"/g /etc/pam.d/sshd
+
+# Leaving the chroot'ed filesystem
+exit
\ No newline at end of file
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-host.sh b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/lxc-init-host.sh
new file mode 100644 (file)
index 0000000..9e0d75d
--- /dev/null
@@ -0,0 +1,8 @@
+#!/bin/sh
+CHROOT=$1
+echo Init LXC container $CHROOT
+
+mkdir $CHROOT/etc/yum.repos.d/ -p  
+cat /etc/yum.repos.d/CentOS-Base.repo |sed s/'$releasever'/6/g > $CHROOT/etc/yum.repos.d/CentOS-Base.repo
+yum groupinstall core --installroot=$CHROOT --nogpgcheck -y
+yum install plymouth libselinux-python --installroot=$CHROOT --nogpgcheck -y
\ No newline at end of file
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/redhat.xml b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/redhat.xml
new file mode 100644 (file)
index 0000000..8379b8a
--- /dev/null
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+\r
+    Copyright (C) 2007-2012 Argeo GmbH\r
+\r
+    Licensed under the Apache License, Version 2.0 (the "License");\r
+    you may not use this file except in compliance with the License.\r
+    You may obtain a copy of the License at\r
+\r
+            http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+    Unless required by applicable law or agreed to in writing, software\r
+    distributed under the License is distributed on an "AS IS" BASIS,\r
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+    See the License for the specific language governing permissions and\r
+    limitations under the License.\r
+\r
+-->\r
+<!-- Copyright (C) 2007-2012 Mathieu Baudier Licensed under the Apache License, \r
+       Version 2.0 (the "License"); you may not use this file except in compliance \r
+       with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 \r
+       Unless required by applicable law or agreed to in writing, software distributed \r
+       under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES \r
+       OR CONDITIONS OF ANY KIND, either express or implied. See the License for \r
+       the specific language governing permissions and limitations under the License. -->\r
+<beans xmlns="http://www.springframework.org/schema/beans"\r
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"\r
+       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:flow="http://www.argeo.org/schema/slc-flow"\r
+       xsi:schemaLocation="\r
+       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
+       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd\r
+       http://www.argeo.org/schema/slc-flow http://www.argeo.org/schema/slc-flow-1.2.xsd">\r
+\r
+       <bean id="hostManager" class="org.argeo.slc.lib.linux.RedhatHostManager">\r
+               <property name="sshTarget" ref="sshTarget" />\r
+               <property name="host" ref="host" />\r
+       </bean>\r
+\r
+       <!-- Execution Flows -->\r
+       <bean flow:as-flow="deployConfig" class="org.argeo.slc.core.execution.tasks.MethodCall"\r
+               p:target-ref="hostManager" p:method="deployConfig" />\r
+\r
+       <bean flow:as-flow="system/reboot" p:command="shutdown -r now"\r
+               p:sshTarget-ref="sshTarget" class="org.argeo.slc.jsch.RemoteExec" />\r
+\r
+       <bean flow:as-flow="system/shutdown" p:command="shutdown -h now"\r
+               p:sshTarget-ref="sshTarget" class="org.argeo.slc.jsch.RemoteExec" />\r
+\r
+       <bean flow:as-flow="system/packages/install" class="org.argeo.slc.core.execution.tasks.MethodCall"\r
+               p:target-ref="hostManager" p:method="installPackages" />\r
+\r
+       <bean flow:as-flow="system/packages/update" p:sshTarget-ref="sshTarget"\r
+               class="org.argeo.slc.jsch.RemoteExec">\r
+               <property name="systemCall">\r
+                       <bean class="org.argeo.slc.core.execution.tasks.SystemCall">\r
+                               <property name="cmd" value="yum -y update" />\r
+                       </bean>\r
+               </property>\r
+       </bean>\r
+\r
+       <bean flow:as-flow="system/security/firewall" p:script="osgibundle:/scripts/firewall.sh"\r
+               p:sshTarget-ref="sshTarget" class="org.argeo.slc.jsch.RemoteExec" />\r
+\r
+       <flow:flow name="system/security/authconfig">\r
+               <flow:spec>\r
+                       <flow:primitive name="ldapserver" />\r
+                       <flow:primitive name="ldapbasedn" />\r
+               </flow:spec>\r
+               <bean p:sshTarget-ref="sshTarget" class="org.argeo.slc.jsch.RemoteExec">\r
+                       <flow:variable />\r
+                       <property name="systemCall">\r
+                               <bean class="org.argeo.slc.core.execution.tasks.SystemCall">\r
+                                       <property name="command">\r
+                                               <list>\r
+                                                       <value>authconfig</value>\r
+                                                       <value>--enableldap</value>\r
+                                                       <value>--enableldapauth</value>\r
+                                                       <value>--enablecache</value>\r
+                                                       <value>--enablemkhomedir</value>\r
+                                                       <value>--ldapserver=@{ldapserver}</value>\r
+                                                       <value>--ldapbasedn=@{ldapbasedn}</value>\r
+                                                       <value>--passalgo=sha256</value>\r
+                                                       <value>--updateall</value>\r
+                                               </list>\r
+                                       </property>\r
+                               </bean>\r
+                       </property>\r
+               </bean>\r
+       </flow:flow>\r
+\r
+</beans>
\ No newline at end of file
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java
new file mode 100644 (file)
index 0000000..1bafe8c
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.exec.Executor;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+
+/** Rebuild an SRPM in mock. (Historical) Replaces the build-mock.sh script. */
+public class BuildInMock implements Runnable {
+       private final static Log log = LogFactory.getLog(BuildInMock.class);
+
+       /** Mock flavour provided by the EPEL repository */
+       public final static String EPEL = "EPEL";
+       /** Mock flavour provided by CentOS until v5 */
+       public final static String CENTOS = "CENTOS";
+
+       public final static String NOARCH = "noarch";
+
+       private String mockVar = "/var/lib/mock";
+
+       private String mockFlavour = EPEL;
+       private String mockConfig = null;
+
+       private String repository;
+       private String release = null;
+       private String level = null;
+       private String arch = NOARCH;
+
+       private String rpmPackage = null;
+
+       private Boolean mkdirs = true;
+
+       private RpmBuildEnvironment buildEnvironment;
+       private Executor executor;
+
+       private String debuginfoDirName = "debuginfo";
+
+       public void run() {
+               // TODO check if caller is in mock group
+
+               String cfgId = repository + "-" + release + "-" + arch;
+               String cfg = mockConfig != null ? mockConfig : "slc/" + cfgId;
+
+               // prepare mock call
+               SystemCall mock = new SystemCall();
+               if (arch != null)
+                       mock.arg("setarch").arg(arch);
+               mock.arg("mock");
+               if (mockFlavour.equals(EPEL))
+                       mock.arg("-v");
+               else if (mockFlavour.equals(CENTOS))
+                       mock.arg("--debug");
+               if (arch != null)
+                       mock.arg("--arch=" + arch);
+               mock.arg("-r").arg(cfg);
+
+               mock.arg("--scm-enable");
+               mock.arg("--scm-option").arg("package=" + rpmPackage);
+
+               mock.setLogCommand(true);
+
+               // mock command execution
+               mock.setExecutor(executor);
+               mock.run();
+
+               // File repoDir = new File(buildEnvironment.getStagingBase() + "/"
+               // + repository + "/" + level + "/" + release);
+               File repoDir = new File(buildEnvironment.getStagingBase() + "/"
+                               + repository + "-" + release + "-staging");
+               File srpmDir = new File(repoDir, "SRPMS");
+               if (mkdirs)
+                       srpmDir.mkdirs();
+               File archDir = null;
+               File debuginfoDir = null;
+               if (!arch.equals(NOARCH)) {
+                       archDir = new File(repoDir, arch);
+                       debuginfoDir = new File(archDir, debuginfoDirName);
+                       debuginfoDir.mkdirs();
+               }
+
+               // copy RPMs
+               Set<File> reposToRecreate = new HashSet<File>();
+               File resultDir = new File(mockVar + "/" + cfgId + "/result");
+               rpms: for (File file : resultDir.listFiles()) {
+                       if (file.isDirectory())
+                               continue rpms;
+
+                       File[] targetDirs;
+                       if (file.getName().contains(".src.rpm"))
+                               targetDirs = new File[] { srpmDir };
+                       else if (file.getName().contains("-debuginfo-"))
+                               targetDirs = new File[] { debuginfoDir };
+                       else if (!arch.equals(NOARCH)
+                                       && file.getName().contains("." + arch + ".rpm"))
+                               targetDirs = new File[] { archDir };
+                       else if (file.getName().contains(".noarch.rpm")) {
+                               List<File> dirs = new ArrayList<File>();
+                               for (String arch : buildEnvironment.getArchs())
+                                       dirs.add(new File(repoDir, arch));
+                               targetDirs = dirs.toArray(new File[dirs.size()]);
+                       } else if (file.getName().contains(".rpm"))
+                               throw new SlcException("Don't know where to copy " + file);
+                       else {
+                               if (log.isTraceEnabled())
+                                       log.trace("Skip " + file);
+                               continue rpms;
+                       }
+
+                       reposToRecreate.addAll(Arrays.asList(targetDirs));
+                       copyToDirs(file, targetDirs);
+               }
+
+               // recreate changed repos
+               for (File repoToRecreate : reposToRecreate) {
+                       SystemCall createrepo = new SystemCall();
+                       createrepo.arg("createrepo");
+                       // sqllite db
+                       createrepo.arg("-d");
+                       // debuginfo
+                       if (!repoToRecreate.getName().equals(debuginfoDirName))
+                               createrepo.arg("-x").arg(debuginfoDirName + "/*");
+                       // quiet
+                       createrepo.arg("-q");
+                       createrepo.arg(repoToRecreate.getAbsolutePath());
+
+                       createrepo.setExecutor(executor);
+                       createrepo.run();
+                       log.info("Updated repo " + repoToRecreate);
+               }
+       }
+
+       protected void copyToDirs(File file, File[] dirs) {
+               for (File dir : dirs) {
+                       try {
+                               FileUtils.copyFileToDirectory(file, dir);
+                               if (log.isDebugEnabled())
+                                       log.debug(file + " => " + dir);
+                       } catch (IOException e) {
+                               throw new SlcException("Cannot copy " + file + " to " + dir, e);
+                       }
+               }
+       }
+
+       public void setMockFlavour(String mockFlavour) {
+               this.mockFlavour = mockFlavour;
+       }
+
+       public void setMockConfig(String mockConfig) {
+               this.mockConfig = mockConfig;
+       }
+
+       public void setRepository(String repo) {
+               this.repository = repo;
+       }
+
+       public void setRelease(String release) {
+               this.release = release;
+       }
+
+       public void setLevel(String level) {
+               this.level = level;
+       }
+
+       public void setArch(String arch) {
+               this.arch = arch;
+       }
+
+       public void setRpmPackage(String rpmPackage) {
+               this.rpmPackage = rpmPackage;
+       }
+
+       public void setMockVar(String mockVar) {
+               this.mockVar = mockVar;
+       }
+
+       public void setMkdirs(Boolean mkdirs) {
+               this.mkdirs = mkdirs;
+       }
+
+       public void setBuildEnvironment(RpmBuildEnvironment buildEnvironment) {
+               this.buildEnvironment = buildEnvironment;
+       }
+
+       public void setExecutor(Executor executor) {
+               this.executor = executor;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java
new file mode 100644 (file)
index 0000000..b5f7bd0
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.exec.Executor;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.UrlResource;
+
+/** Generates an SRPM from a spec file */
+public class CreateSrpm implements Runnable {
+       private final static Log log = LogFactory.getLog(CreateSrpm.class);
+
+       private File topdir;
+
+       /** Directory where to cache downloaded distributions. */
+       private File distributionCache;
+
+       private Resource specFile;
+
+       private RpmBuildEnvironment rpmBuildEnvironment;
+
+       private Boolean overwriteSources = false;
+
+       private File srpmFile;
+
+       private Executor executor;
+
+       public void run() {
+               File sourcesDir = new File(topdir, "SOURCES");
+               sourcesDir.mkdirs();
+               File specsDir = new File(topdir, "SPECS");
+               File srpmsDir = new File(topdir, "SRPMS");
+
+               try {
+                       // Parse spec file and copy required resources
+                       RpmSpecFile spec = new RpmSpecFile(specFile);
+                       copyToSources(spec, sourcesDir);
+
+                       // Copy spec file
+                       File targetFile = new File(specsDir, specFile.getFilename())
+                                       .getCanonicalFile();
+                       copyResourceToFile(specFile, targetFile);
+
+                       // Generate rpmbuild config files
+                       rpmBuildEnvironment.writeRpmbuildConfigFiles(topdir);
+
+                       // Build SRPM
+                       srpmsDir.mkdirs();
+                       SystemCall packageSrpm = new SystemCall();
+                       packageSrpm.arg("rpmbuild");
+                       packageSrpm.arg("-bs").arg("--nodeps");
+                       packageSrpm.arg("--rcfile=rpmrc");
+                       packageSrpm.arg("--macros=" + RpmBuildEnvironment.defaultMacroFiles
+                                       + ":rpmmacros");
+                       // buildSrpm.arg("-D", "_topdir " + topdir.getCanonicalPath() + "");
+                       packageSrpm.arg("SPECS/" + specFile.getFilename());
+                       packageSrpm.setExecDir(topdir.getCanonicalPath());
+                       packageSrpm.setLogCommand(true);
+
+                       // Execute
+                       packageSrpm.setExecutor(executor);
+                       String answer = packageSrpm.function();
+
+                       // Extract generated SRPM path
+                       // TODO: make it safer
+                       String srpmPath = answer.split(":")[1].trim();
+                       srpmFile = new File(srpmPath);
+               } catch (IOException e) {
+                       throw new SlcException("Cannot generate SRPM from " + specFile, e);
+               }
+
+       }
+
+       protected void copyToSources(RpmSpecFile spec, File sourcesDir) {
+               try {
+                       List<Resource> toCopyToSources = new ArrayList<Resource>();
+                       List<Resource> toDownload = new ArrayList<Resource>();
+                       for (String file : spec.getSources().values()) {
+                               try {
+                                       Resource res;
+                                       try {
+                                               res = specFile.createRelative("../SOURCES/" + file);
+                                               if (!res.exists())
+                                                       res = new UrlResource(file);
+
+                                       } catch (Exception e) {
+                                               res = new UrlResource(file);
+                                               toDownload.add(res);
+                                       }
+                                       toCopyToSources.add(res);
+                               } catch (Exception e) {
+                                       log.error("Cannot interpret " + file, e);
+                               }
+                       }
+                       for (String file : spec.getPatches().values()) {
+                               try {
+                                       Resource res;
+                                       try {
+                                               res = specFile.createRelative("../SOURCES/" + file);
+                                               if (!res.exists()) {
+                                                       res = new UrlResource(file);
+                                               }
+                                       } catch (Exception e) {
+                                               res = new UrlResource(file);
+                                               toDownload.add(res);
+                                       }
+                                       toCopyToSources.add(res);
+                               } catch (Exception e) {
+                                       log.error("Cannot interpret " + file, e);
+                               }
+                       }
+
+                       // FIXME: we may have missed some files here
+                       for (Resource res : toCopyToSources) {
+                               File targetDir;
+                               if (distributionCache != null && toDownload.contains(res)) {
+                                       if (!distributionCache.exists())
+                                               distributionCache.mkdirs();
+                                       targetDir = distributionCache;
+                                       if (log.isDebugEnabled())
+                                               log.debug("Cache " + res + " in " + targetDir);
+                               } else
+                                       targetDir = sourcesDir;
+                               File targetFile = new File(targetDir, res.getFilename())
+                                               .getCanonicalFile();
+                               if (!targetFile.exists() || overwriteSources)
+                                       copyResourceToFile(res, targetFile);
+                               if (!targetDir.equals(sourcesDir)) {
+                                       File fileInSourcesDir = new File(sourcesDir,
+                                                       targetFile.getName());
+                                       if (!fileInSourcesDir.exists()
+                                                       || !(fileInSourcesDir.length() == targetFile
+                                                                       .length()))
+                                               FileUtils.copyFile(targetFile, fileInSourcesDir);
+                               }
+                       }
+               } catch (Exception e) {
+                       throw new SlcException("Cannot copy to " + sourcesDir, e);
+               }
+       }
+
+       private static void copyResourceToFile(Resource res, File targetFile) {
+               try {
+                       if (targetFile.equals(res.getFile())) {
+                               if (log.isDebugEnabled())
+                                       log.debug("Target identical to source, skipping... "
+                                                       + targetFile + " <=> " + res);
+                               return;
+                       }
+               } catch (IOException e1) {
+                       // silent
+               }
+
+               OutputStream out = null;
+               InputStream in = null;
+               try {
+                       out = FileUtils.openOutputStream(targetFile);
+                       in = res.getInputStream();
+                       IOUtils.copy(in, out);
+                       if (log.isDebugEnabled())
+                               log.debug("Copied " + targetFile + " from " + res);
+               } catch (Exception e) {
+                       throw new SlcException("Cannot copy " + res + " to " + targetFile,
+                                       e);
+               } finally {
+                       IOUtils.closeQuietly(in);
+                       IOUtils.closeQuietly(out);
+               }
+
+       }
+
+       public void setSpecFile(Resource specFile) {
+               this.specFile = specFile;
+       }
+
+       public void setTopdir(File topdir) {
+               this.topdir = topdir;
+       }
+
+       public void setOverwriteSources(Boolean overwriteSources) {
+               this.overwriteSources = overwriteSources;
+       }
+
+       public File getSrpmFile() {
+               return srpmFile;
+       }
+
+       public void setRpmBuildEnvironment(RpmBuildEnvironment rpmBuildEnvironment) {
+               this.rpmBuildEnvironment = rpmBuildEnvironment;
+       }
+
+       public void setDistributionCache(File distributionCache) {
+               this.distributionCache = distributionCache;
+       }
+
+       public void setExecutor(Executor executor) {
+               this.executor = executor;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java
new file mode 100644 (file)
index 0000000..cd170e3
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
+
+import java.io.File;
+
+import org.argeo.slc.core.execution.tasks.SystemCall;
+
+/** Install an SRPM into a working copy */
+public class ImportSrpm implements Runnable {
+       private File baseDir;
+       private File srpmFile;
+       private RpmBuildEnvironment rpmBuildEnvironment;
+
+       public void run() {
+               SystemCall rpmQuery = new SystemCall(
+                               "rpm --queryformat '%{NAME}\n' -qp " + srpmFile);
+               String packageName = rpmQuery.function();
+
+               File topdir = new File(baseDir, packageName);
+
+               // prepare SVN
+               // TODO: do it with SVNKit
+               topdir.mkdirs();
+               new SystemCall("svn add " + topdir).run();
+               new SystemCall("svn propset svn:ignore rpm*\nBUILD\nSRPMS\nRPMS " + topdir).run();
+               File sourcesDir = new File(topdir, "SOURCES");
+               sourcesDir.mkdirs();
+               new SystemCall("svn add " + sourcesDir).run();
+               new SystemCall("svn propset svn:ignore *gz\n*bz2\n*.zip\n*.jar " + sourcesDir).run();
+               File specsDir = new File(topdir, "SPECS");
+               specsDir.mkdirs();
+               new SystemCall("svn add " + specsDir).run();
+
+               // Write rpm config files
+               File rpmmacroFile = new File(topdir, "rpmmacros");
+               File rpmrcFile = new File(topdir, "rpmrc");
+               rpmBuildEnvironment.writeRpmbuildConfigFiles(topdir, rpmmacroFile,
+                               rpmrcFile);
+
+               // Install SRPM
+               SystemCall installSrpm = new SystemCall();
+               installSrpm.arg("rpm");
+               installSrpm.arg("-Uvh");
+               installSrpm.arg("--rcfile=" + rpmrcFile.getAbsolutePath());
+               installSrpm.arg(srpmFile.getAbsolutePath());
+               installSrpm.setExecDir(topdir.getAbsolutePath());
+               installSrpm.setLogCommand(true);
+               installSrpm.run();
+       }
+
+       public void setBaseDir(File basedir) {
+               this.baseDir = basedir;
+       }
+
+       public void setSrpmFile(File srpmFile) {
+               this.srpmFile = srpmFile;
+       }
+
+       public void setRpmBuildEnvironment(RpmBuildEnvironment rpmBuildEnvironment) {
+               this.rpmBuildEnvironment = rpmBuildEnvironment;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java
new file mode 100644 (file)
index 0000000..a5c1fc7
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.io.FileUtils;
+import org.argeo.slc.SlcException;
+
+/**
+ * Defines a build environment. This information is typically used by other
+ * components performing the various actions related to RPM build.
+ */
+public class RpmBuildEnvironment {
+       static String defaultMacroFiles = "/usr/lib/rpm/macros:/usr/lib/rpm/ia32e-linux/macros:/usr/lib/rpm/redhat/macros:/etc/rpm/macros.*:/etc/rpm/macros:/etc/rpm/ia32e-linux/macros:~/.rpmmacros";
+
+       private Map<String, String> rpmmacros = new HashMap<String, String>();
+
+       private List<String> archs = new ArrayList<String>();
+
+       private String stagingBase = "/mnt/slc/repos/rpm";
+
+       /** Write (topdir)/rpmmacros and (topdir)/rpmrc */
+       public void writeRpmbuildConfigFiles(File topdir) {
+               writeRpmbuildConfigFiles(topdir, new File(topdir, "rpmmacros"),
+                               new File(topdir, "rpmrc"));
+       }
+
+       public void writeRpmbuildConfigFiles(File topdir, File rpmmacroFile,
+                       File rpmrcFile) {
+               try {
+                       List<String> macroLines = new ArrayList<String>();
+                       macroLines.add("%_topdir " + topdir.getCanonicalPath());
+                       for (String macroKey : rpmmacros.keySet()) {
+                               macroLines.add(macroKey + " " + rpmmacros.get(macroKey));
+                       }
+                       FileUtils.writeLines(rpmmacroFile, macroLines);
+
+                       List<String> rpmrcLines = new ArrayList<String>();
+                       rpmrcLines.add("include: /usr/lib/rpm/rpmrc");
+                       rpmrcLines.add("macrofiles: " + defaultMacroFiles + ":"
+                                       + rpmmacroFile.getCanonicalPath());
+                       FileUtils.writeLines(rpmrcFile, rpmrcLines);
+               } catch (IOException e) {
+                       throw new SlcException("Cannot write rpmbuild config files", e);
+               }
+
+       }
+
+       public Map<String, String> getRpmmacros() {
+               return rpmmacros;
+       }
+
+       public void setRpmmacros(Map<String, String> rpmmacros) {
+               this.rpmmacros = rpmmacros;
+       }
+
+       public String getDefaultMacroFiles() {
+               return defaultMacroFiles;
+       }
+
+       public void setDefaultMacroFiles(String defaultMacroFiles) {
+               this.defaultMacroFiles = defaultMacroFiles;
+       }
+
+       public void setArchs(List<String> archs) {
+               this.archs = archs;
+       }
+
+       public List<String> getArchs() {
+               return archs;
+       }
+
+       public String getStagingBase() {
+               return stagingBase;
+       }
+
+       public void setStagingBase(String stagingBase) {
+               this.stagingBase = stagingBase;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java b/org.argeo.slc.support/src/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java
new file mode 100644 (file)
index 0000000..f248654
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.io.IOUtils;
+import org.springframework.core.io.Resource;
+
+public class RpmSpecFile {
+       private Resource specFile;
+
+       private String name;
+       private String version;
+       private String release;
+       private Map<String, String> sources = new HashMap<String, String>();
+       private Map<String, String> patches = new HashMap<String, String>();
+
+       public RpmSpecFile(Resource specFile) {
+               this.specFile = specFile;
+               parseSpecFile();
+       }
+
+       public void init() {
+               parseSpecFile();
+       }
+
+       @SuppressWarnings("unchecked")
+       protected void parseSpecFile() {
+               try {
+                       List<String> lines = (List<String>) IOUtils.readLines(specFile
+                                       .getInputStream());
+
+                       lines: for (String line : lines) {
+                               int indexSemiColon = line.indexOf(':');
+                               if (indexSemiColon <= 0)
+                                       continue lines;
+                               String directive = line.substring(0, indexSemiColon).trim();
+                               String value = line.substring(indexSemiColon + 1).trim();
+                               if ("name".equals(directive.toLowerCase()))
+                                       name = value;
+                               else if ("version".equals(directive.toLowerCase()))
+                                       version = value;
+                               else if ("release".equals(directive.toLowerCase()))
+                                       release = value;
+                               else if (directive.toLowerCase().startsWith("source"))
+                                       sources.put(directive, interpret(value));
+                               else if (directive.toLowerCase().startsWith("patch"))
+                                       patches.put(directive, interpret(value));
+                       }
+
+               } catch (IOException e) {
+                       throw new RuntimeException("Cannot parse spec file " + specFile, e);
+               }
+       }
+
+       protected String interpret(String value) {
+               StringBuffer buf = new StringBuffer(value.length());
+               StringBuffer currKey = null;
+               boolean mayBeKey = false;
+               chars: for (char c : value.toCharArray()) {
+                       if (c == '%')
+                               mayBeKey = true;
+                       else if (c == '{') {
+                               if (mayBeKey)
+                                       currKey = new StringBuffer();
+                       } else if (c == '}') {
+                               if (currKey == null)
+                                       continue chars;
+                               String key = currKey.toString();
+                               if ("name".equals(key.toLowerCase()))
+                                       buf.append(name);
+                               else if ("version".equals(key.toLowerCase()))
+                                       buf.append(version);
+                               else
+                                       buf.append("%{").append(key).append('}');
+                               currKey = null;
+                       } else {
+                               if (currKey != null)
+                                       currKey.append(c);
+                               else
+                                       buf.append(c);
+                       }
+               }
+               return buf.toString();
+       }
+
+       public Resource getSpecFile() {
+               return specFile;
+       }
+
+       public String getName() {
+               return name;
+       }
+
+       public String getVersion() {
+               return version;
+       }
+
+       public String getRelease() {
+               return release;
+       }
+
+       public Map<String, String> getSources() {
+               return sources;
+       }
+
+       public Map<String, String> getPatches() {
+               return patches;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/svn/SvnKitDriver.java b/org.argeo.slc.support/src/org/argeo/slc/lib/svn/SvnKitDriver.java
new file mode 100644 (file)
index 0000000..e75b199
--- /dev/null
@@ -0,0 +1,182 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.lib.svn;\r
+\r
+import java.io.File;\r
+import java.io.OutputStream;\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+import org.apache.commons.logging.Log;\r
+import org.apache.commons.logging.LogFactory;\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.deploy.VersioningDriver;\r
+import org.tmatesoft.svn.core.SVNDepth;\r
+import org.tmatesoft.svn.core.SVNException;\r
+import org.tmatesoft.svn.core.SVNURL;\r
+import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;\r
+import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;\r
+import org.tmatesoft.svn.core.io.SVNRepository;\r
+import org.tmatesoft.svn.core.wc.SVNClientManager;\r
+import org.tmatesoft.svn.core.wc.SVNRevision;\r
+import org.tmatesoft.svn.core.wc.SVNWCUtil;\r
+import org.tmatesoft.svn.core.wc.admin.ISVNChangeEntryHandler;\r
+import org.tmatesoft.svn.core.wc.admin.SVNChangeEntry;\r
+\r
+/** Versioning driver with a Subversion backen, based on SVNKit */\r
+public class SvnKitDriver implements VersioningDriver {\r
+       private final static Log log = LogFactory.getLog(SvnKitDriver.class);\r
+\r
+       private final SVNClientManager manager;\r
+\r
+       public SvnKitDriver() {\r
+               DAVRepositoryFactory.setup();\r
+               FSRepositoryFactory.setup();\r
+               manager = SVNClientManager.newInstance();\r
+       }\r
+\r
+       @SuppressWarnings("deprecation")\r
+       public void updateToHead(File fileOrDir) {\r
+               try {\r
+                       manager.getUpdateClient().doUpdate(fileOrDir, SVNRevision.HEAD,\r
+                                       true);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot update " + fileOrDir, e);\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("deprecation")\r
+       public void importFileOrDir(String repositoryUrl, File fileOrDir) {\r
+               try {\r
+                       manager.getCommitClient().doImport(fileOrDir,\r
+                                       SVNURL.parseURIDecoded(repositoryUrl),\r
+                                       "Import " + fileOrDir, true);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot import " + repositoryUrl + " to "\r
+                                       + fileOrDir, e);\r
+               }\r
+       }\r
+\r
+       public Boolean checkout(String repositoryUrl, File destDir,\r
+                       Boolean recursive) {\r
+               try {\r
+                       SVNRevision previousRevision = null;\r
+                       if (destDir.exists() && SVNWCUtil.isVersionedDirectory(destDir)) {\r
+                               previousRevision = manager.getWCClient().doInfo(destDir, null)\r
+                                               .getRevision();\r
+                       }\r
+                       if (previousRevision == null && log.isDebugEnabled())\r
+                               log.debug("Checking out " + repositoryUrl + " to " + destDir\r
+                                               + "...");\r
+                       long revision = manager.getUpdateClient().doCheckout(\r
+                                       SVNURL.parseURIDecoded(repositoryUrl), destDir,\r
+                                       SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNDepth.INFINITY,\r
+                                       recursive);\r
+                       if (previousRevision != null\r
+                                       && previousRevision.getNumber() == revision) {\r
+                               if (log.isTraceEnabled())\r
+                                       log.trace(destDir + " already at revision " + revision);\r
+                               return false;\r
+\r
+                       } else {\r
+                               if (log.isDebugEnabled())\r
+                                       if (previousRevision != null)\r
+                                               log.debug(destDir + " updated to revision " + revision\r
+                                                               + " from " + previousRevision.getNumber());\r
+                                       else\r
+                                               log.debug(destDir + " checked out to revision "\r
+                                                               + revision);\r
+                               return true;\r
+                       }\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot checkout " + repositoryUrl + " to "\r
+                                       + destDir, e);\r
+               }\r
+       }\r
+\r
+       public void getFileFromRepository(String repositoryBaseUrl,\r
+                       String location, OutputStream out) {\r
+               try {\r
+                       SVNURL url = SVNURL.parseURIDecoded(repositoryBaseUrl);\r
+                       SVNRepository repo = manager.createRepository(url, true);\r
+                       repo.getFile(location, -1, null, out);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot retrieve file " + location\r
+                                       + " from " + repositoryBaseUrl, e);\r
+               }\r
+\r
+       }\r
+\r
+       public String getRelativePath(String repositoryUrl) {\r
+               try {\r
+                       SVNURL url = SVNURL.parseURIDecoded(repositoryUrl);\r
+                       SVNRepository repo = manager.createRepository(url, true);\r
+                       return repo.getRepositoryPath("");\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot get relative path for "\r
+                                       + repositoryUrl, e);\r
+               }\r
+       }\r
+\r
+       public String getRepositoryRoot(String repositoryUrl) {\r
+               try {\r
+                       SVNURL url = SVNURL.parseURIDecoded(repositoryUrl);\r
+                       SVNRepository repo = manager.createRepository(url, true);\r
+                       return repo.getRepositoryRoot(true).toDecodedString();\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot get repository root for "\r
+                                       + repositoryUrl, e);\r
+               }\r
+       }\r
+\r
+       public List<String> getChangedPaths(File repositoryRoot, Long revision) {\r
+               try {\r
+                       final List<String> paths = new Vector<String>();\r
+                       ISVNChangeEntryHandler handler = new ISVNChangeEntryHandler() {\r
+                               public void handleEntry(SVNChangeEntry entry)\r
+                                               throws SVNException {\r
+                                       paths.add(entry.getPath());\r
+                               }\r
+                       };\r
+                       manager.getLookClient().doGetChanged(repositoryRoot,\r
+                                       SVNRevision.create(revision), handler, false);\r
+                       return paths;\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot get changed paths at "\r
+                                       + repositoryRoot + " for revision " + revision, e);\r
+               }\r
+       }\r
+\r
+       public void createRepository(String filePath) {\r
+               try {\r
+                       manager.getAdminClient().doCreateRepository(new File(filePath),\r
+                                       null, false, false);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot create repository " + filePath, e);\r
+               }\r
+       }\r
+\r
+       @SuppressWarnings("deprecation")\r
+       public void commit(File fileOrDir, String commitMessage) {\r
+               try {\r
+                       manager.getCommitClient().doCommit(new File[] { fileOrDir }, true,\r
+                                       commitMessage, false, true);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot commit " + fileOrDir, e);\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxMachine.java b/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxMachine.java
new file mode 100644 (file)
index 0000000..cf30bbb
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.vbox;
+
+import org.argeo.slc.UnsupportedException;
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.deploy.DeployedSystem;
+import org.argeo.slc.deploy.DeploymentData;
+import org.argeo.slc.deploy.TargetData;
+import org.springframework.beans.factory.BeanNameAware;
+import org.springframework.beans.factory.InitializingBean;
+
+public class VBoxMachine implements DeployedSystem, BeanNameAware,
+               InitializingBean {
+       private String deployedSystemId = null;
+       private String name;
+       private String beanName;
+
+       public String getDeployedSystemId() {
+               return deployedSystemId;
+       }
+
+       public DeploymentData getDeploymentData() {
+               throw new UnsupportedException();
+       }
+
+       public Distribution getDistribution() {
+               throw new UnsupportedException();
+       }
+
+       public TargetData getTargetData() {
+               throw new UnsupportedException();
+       }
+
+       public String getName() {
+               return name;
+       }
+
+       public void setName(String name) {
+               this.name = name;
+       }
+
+       public void setDeployedSystemId(String deployedSystemId) {
+               this.deployedSystemId = deployedSystemId;
+       }
+
+       public void setBeanName(String beanName) {
+               this.beanName = name;
+       }
+
+       public void afterPropertiesSet() throws Exception {
+               if (name == null)
+                       name = beanName;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxManager.java b/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxManager.java
new file mode 100644 (file)
index 0000000..34e8993
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.vbox;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+import org.springframework.core.io.Resource;
+
+public class VBoxManager {
+       private final static Log log = LogFactory.getLog(VBoxManager.class);
+
+       private VBoxMachine vm;
+       private String executable = "VBoxManage";
+
+       private List<VBoxNat> nats = new ArrayList<VBoxNat>();
+
+       public void importOvf(Resource ovfDefinition) {
+               try {
+                       List<Object> cmd = new ArrayList<Object>();
+                       cmd.add(executable);
+                       cmd.add("import");
+                       cmd.add(ovfDefinition.getFile().getCanonicalPath());
+                       cmd.add("--vsys 0 --vmname <name>");
+                       cmd.add("0");
+                       cmd.add("--vmname");
+                       cmd.add(vm.getName());
+                       new SystemCall(cmd).run();
+               } catch (IOException e) {
+                       throw new SlcException("Cannot import OVF appliance "
+                                       + ovfDefinition, e);
+               }
+       }
+
+       public void startVm() {
+               startVm("gui");
+       }
+
+       public void startVmHeadless() {
+               startVm("vrdp");
+       }
+
+       public void startVm(String type) {
+               List<Object> cmd = new ArrayList<Object>();
+               cmd.add(executable);
+               cmd.add("startvm");
+               cmd.add(vm.getName());
+               cmd.add("--type");
+               cmd.add(type);
+               new SystemCall(cmd).run();
+       }
+
+       public void applyNats() {
+               StringBuffer script = new StringBuffer("");
+               for (VBoxNat vBoxNat : nats) {
+                       for (String id : vBoxNat.getMappings().keySet()) {
+                               VBoxPortMapping mapping = vBoxNat.getMappings().get(id);
+
+                               // Try to delete rule first
+                               try {
+                                       StringBuffer delCmd = new StringBuffer(
+                                                       "VBoxManage modifyvm");
+                                       delCmd.append(" \"").append(vm.getName()).append("\"");
+                                       delCmd.append(" --natpf").append(vBoxNat.getDevice())
+                                                       .append(" ");
+                                       delCmd.append(" delete ");
+                                       delCmd.append("\"").append(id).append("\"");
+                                       new SystemCall(delCmd.toString()).run();
+                                       script.append(delCmd).append("\n");
+                               } catch (Exception e) {
+                                       // silent
+                               }
+
+                               StringBuffer cmd = new StringBuffer("VBoxManage modifyvm");
+                               cmd.append(" \"").append(vm.getName()).append("\"");
+                               cmd.append(" --natpf").append(vBoxNat.getDevice()).append(" ");
+                               cmd.append("\"");
+                               cmd.append(id).append(",");
+                               cmd.append(mapping.getProtocol()).append(",");
+                               cmd.append(",");
+                               cmd.append(mapping.getHostPort()).append(",");
+                               cmd.append(vBoxNat.getGuestIp()).append(",");
+                               cmd.append(mapping.getGuestPort());
+                               cmd.append("\"");
+
+                               new SystemCall(cmd.toString()).run();
+                               script.append(cmd).append("\n");
+
+                               // Older VirtualBox
+                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
+                               // "Protocol", mapping.getProtocol(), script)).run();
+                               // script.append('\n');
+                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
+                               // "GuestPort", mapping.getGuest(), script)).run();
+                               // script.append('\n');
+                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
+                               // "HostPort", mapping.getHost(), script)).run();
+                               // script.append('\n');
+                               // script.append('\n');
+                       }
+                       script.append('\n');
+               }
+
+               if (log.isDebugEnabled())
+                       log.debug("Port setting script:\n" + script);
+       }
+
+       protected List<Object> createNatCommand(String id, String device,
+                       String cfgKey, String value, StringBuffer script) {
+               List<Object> cmd = new ArrayList<Object>();
+               cmd.add(executable);
+               cmd.add("setextradata");
+               cmd.add(vm.getName());
+               cmd.add("VBoxInternal/Devices/" + device + "/0/LUN#0/Config/" + id
+                               + "/" + cfgKey);
+               cmd.add(value);
+
+               for (Object arg : cmd) {
+                       script.append(arg).append(' ');
+               }
+
+               return cmd;
+       }
+
+       public String getExecutable() {
+               return executable;
+       }
+
+       public void setExecutable(String executable) {
+               this.executable = executable;
+       }
+
+       public List<VBoxNat> getNats() {
+               return nats;
+       }
+
+       public void setNats(List<VBoxNat> boxNats) {
+               nats = boxNats;
+       }
+
+       public void setVm(VBoxMachine vm) {
+               this.vm = vm;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxNat.java b/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxNat.java
new file mode 100644 (file)
index 0000000..e69eba1
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.vbox;
+
+import java.util.Map;
+
+/** The NAT mapping table */
+public class VBoxNat {
+       private String device = "1";
+       private String guestIp = "";
+       private Map<String, VBoxPortMapping> mappings;
+
+       public String getDevice() {
+               return device;
+       }
+
+       public void setDevice(String device) {
+               this.device = device;
+       }
+
+       public Map<String, VBoxPortMapping> getMappings() {
+               return mappings;
+       }
+
+       public void setMappings(Map<String, VBoxPortMapping> mappings) {
+               this.mappings = mappings;
+       }
+
+       public String getGuestIp() {
+               return guestIp;
+       }
+
+       public void setGuestIp(String guestIp) {
+               this.guestIp = guestIp;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxPortMapping.java b/org.argeo.slc.support/src/org/argeo/slc/lib/vbox/VBoxPortMapping.java
new file mode 100644 (file)
index 0000000..dc9783f
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.lib.vbox;
+
+/** The mapping of one port. */
+public class VBoxPortMapping {
+       private String protocol = "TCP";
+       private String guestPort;
+       private String hostPort;
+
+       public String getProtocol() {
+               return protocol;
+       }
+
+       public void setProtocol(String type) {
+               this.protocol = type;
+       }
+
+       public String getGuestPort() {
+               return guestPort;
+       }
+
+       public void setGuestPort(String guestPort) {
+               this.guestPort = guestPort;
+       }
+
+       public String getHostPort() {
+               return hostPort;
+       }
+
+       public void setHostPort(String hostPort) {
+               this.hostPort = hostPort;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/log4j/SlcExecutionAppender.java b/org.argeo.slc.support/src/org/argeo/slc/log4j/SlcExecutionAppender.java
new file mode 100644 (file)
index 0000000..190a0b6
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.log4j;
+
+import java.util.Date;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.log4j.spi.LoggingEvent;
+import org.argeo.slc.core.execution.ExecutionThread;
+import org.argeo.slc.core.execution.ProcessThreadGroup;
+import org.argeo.slc.execution.ExecutionStep;
+
+/** Not meant to be used directly in standard log4j config */
+public class SlcExecutionAppender extends AppenderSkeleton {
+
+       private Boolean disabled = false;
+
+       private String level = null;
+
+       private Level log4jLevel = null;
+
+       /** Marker to prevent stack overflow */
+       private ThreadLocal<Boolean> dispatching = new ThreadLocal<Boolean>() {
+
+               @Override
+               protected Boolean initialValue() {
+                       return false;
+               }
+       };
+
+       // private Layout layout = null;
+       // private String pattern = "%m - %c%n";
+       private Boolean onlyExecutionThread = false;
+
+       public void init() {
+               // if (layout != null)
+               // setLayout(layout);
+               // else
+               // setLayout(new PatternLayout(pattern));
+               Logger.getRootLogger().addAppender(this);
+       }
+
+       @Override
+       protected void append(LoggingEvent event) {
+               if (disabled)
+                       return;
+
+               if (dispatching.get())
+                       return;
+
+               if (level != null && !level.trim().equals("")) {
+                       if (log4jLevel == null || !log4jLevel.toString().equals(level))
+                               try {
+                                       log4jLevel = Level.toLevel(level);
+                               } catch (Exception e) {
+                                       System.err
+                                                       .println("Log4j level could not be set for level '"
+                                                                       + level + "', resetting it to null.");
+                                       e.printStackTrace();
+                                       level = null;
+                               }
+
+                       if (log4jLevel != null
+                                       && !event.getLevel().isGreaterOrEqual(log4jLevel)) {
+                               return;
+                       }
+               }
+
+               // Check whether we are within an executing process
+               Thread currentThread = Thread.currentThread();
+               if (currentThread.getThreadGroup() instanceof ProcessThreadGroup) {
+                       if (onlyExecutionThread
+                                       && !(currentThread instanceof ExecutionThread))
+                               return;
+
+                       final String type;
+                       if (event.getLevel().equals(Level.ERROR)
+                                       || event.getLevel().equals(Level.FATAL))
+                               type = ExecutionStep.ERROR;
+                       else if (event.getLevel().equals(Level.WARN))
+                               type = ExecutionStep.WARNING;
+                       else if (event.getLevel().equals(Level.INFO))
+                               type = ExecutionStep.INFO;
+                       else if (event.getLevel().equals(Level.DEBUG))
+                               type = ExecutionStep.DEBUG;
+                       else if (event.getLevel().equals(Level.TRACE))
+                               type = ExecutionStep.TRACE;
+                       else
+                               type = ExecutionStep.INFO;
+
+                       ExecutionStep step = new ExecutionStep(event.getLoggerName(),
+                                       new Date(event.getTimeStamp()), type, event.getMessage()
+                                                       .toString());
+
+                       try {
+                               dispatching.set(true);
+                               BlockingQueue<ExecutionStep> steps = ((ProcessThreadGroup) currentThread
+                                               .getThreadGroup()).getSteps();
+                               if (steps.remainingCapacity() == 0) {
+                                       stdOut("WARNING: execution steps queue is full, skipping step: "
+                                                       + step);
+                                       // FIXME understand why it block indefinitely: the queue
+                                       // should be emptied by the logging thread
+                               } else {
+                                       steps.add(step);
+                               }
+                       } finally {
+                               dispatching.set(false);
+                       }
+               }
+       }
+
+       public void destroy() throws Exception {
+               Logger.getRootLogger().removeAppender(this);
+       }
+
+       public void close() {
+       }
+
+       public boolean requiresLayout() {
+               return false;
+       }
+
+       // public void setLayout(Layout layout) {
+       // this.layout = layout;
+       // }
+
+       /** For development purpose, since using regular logging is not easy here */
+       static void stdOut(Object obj) {
+               System.out.println(obj);
+       }
+
+       // public void setPattern(String pattern) {
+       // this.pattern = pattern;
+       // }
+
+       public void setOnlyExecutionThread(Boolean onlyExecutionThread) {
+               this.onlyExecutionThread = onlyExecutionThread;
+       }
+
+       public void setDisabled(Boolean disabled) {
+               this.disabled = disabled;
+       }
+
+       public void setLevel(String level) {
+               this.level = level;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/mail/SendMail.java b/org.argeo.slc.support/src/org/argeo/slc/mail/SendMail.java
new file mode 100644 (file)
index 0000000..d2e2780
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.mail;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.mail.Message;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.execution.tasks.SystemCall;
+
+/** Sends a mail via JavaMail, local mail command or Google Mail. */
+public class SendMail implements Runnable {
+       // See:
+       // http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#JavaMailUsage
+       // http://java.sun.com/products/javamail/FAQ.html#gmail
+
+       private final static Log log = LogFactory.getLog(SendMail.class);
+
+       private String host;
+       private String from;
+       private String to;
+       private String subject;
+       private String text;
+       private String username;
+       private String password;
+       private Map<String, String> javaMailProperties = new HashMap<String, String>();
+
+       public void run() {
+               if ("local".equals(host))
+                       sendWithMailCommand();
+               else if ("smtp.gmail.com".equals(host))
+                       sendWithGMail();
+               else
+                       sendWithJavaMail();
+       }
+
+       protected void sendWithMailCommand() {
+               SystemCall mail = new SystemCall("mail");
+               mail.arg("-s", subject).arg(to);
+               mail.run();
+               if (log.isDebugEnabled())
+                       log.debug("Sent mail to " + to + " with OS mail command");
+       }
+
+       protected void sendWithJavaMail() {
+               try {
+                       // Get system properties
+                       Properties props = System.getProperties();
+
+                       // Setup mail server
+                       props.put("mail.smtp.host", host);
+
+                       for (String key : javaMailProperties.keySet())
+                               props.put(key, javaMailProperties.get(key));
+
+                       // Get session
+                       Session session = Session.getDefaultInstance(props, null);
+
+                       // Define message
+                       MimeMessage message = new MimeMessage(session);
+                       buildJavaMailMessage(message);
+
+                       // Send message
+                       Transport.send(message);
+                       if (log.isDebugEnabled())
+                               log.debug("Sent mail to " + to + " with JavaMail");
+               } catch (Exception e) {
+                       throw new SlcException("Cannot send message.", e);
+               }
+       }
+
+       protected void sendWithGMail() {
+               try {
+                       Properties props = new Properties();
+                       props.put("mail.smtps.auth", "true");
+                       props.put("mail.smtps.host", host);
+                       Session session = Session.getDefaultInstance(props, null);
+                       MimeMessage message = new MimeMessage(session);
+                       buildJavaMailMessage(message);
+                       Transport t = session.getTransport("smtps");
+                       try {
+                               t.connect(host, username, password);
+                               t.sendMessage(message, message.getAllRecipients());
+                       } finally {
+                               t.close();
+                       }
+                       if (log.isDebugEnabled())
+                               log.debug("Sent mail to " + to + " with Google Mail");
+               } catch (Exception e) {
+                       throw new SlcException("Cannot send message.", e);
+               }
+       }
+
+       protected void buildJavaMailMessage(Message message) throws Exception {
+               message.setFrom(new InternetAddress(from));
+               message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
+               message.setSubject(subject);
+               message.setText(text);
+       }
+
+       public void setHost(String host) {
+               this.host = host;
+       }
+
+       public void setFrom(String from) {
+               this.from = from;
+       }
+
+       public void setTo(String to) {
+               this.to = to;
+       }
+
+       public void setSubject(String subject) {
+               this.subject = subject;
+       }
+
+       public void setText(String text) {
+               this.text = text;
+       }
+
+       public void setJavaMailProperties(Map<String, String> javaMailProperties) {
+               this.javaMailProperties = javaMailProperties;
+       }
+
+       public void setUsername(String username) {
+               this.username = username;
+       }
+
+       public void setPassword(String password) {
+               this.password = password;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java
new file mode 100644 (file)
index 0000000..d7489ee
--- /dev/null
@@ -0,0 +1,83 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.io.File;\r
+\r
+import org.apache.commons.logging.Log;\r
+import org.apache.commons.logging.LogFactory;\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.build.Distribution;\r
+import org.argeo.slc.deploy.DeployEnvironment;\r
+import org.argeo.slc.deploy.DeployedSystem;\r
+import org.argeo.slc.deploy.Deployment;\r
+import org.argeo.slc.deploy.DeploymentData;\r
+import org.argeo.slc.deploy.TargetData;\r
+\r
+public class HttpdApplicationDeployment implements Deployment {\r
+       private static final Log log = LogFactory\r
+                       .getLog(HttpdApplicationDeployment.class);\r
+\r
+       private HttpdApplicationTargetData targetData;\r
+       private DeploymentData deploymentData;\r
+       private SimpleHttpdApplication deployedSystem;\r
+       private Distribution distribution;\r
+\r
+       private DeployEnvironment deployEnvironment;\r
+\r
+       public void run() {\r
+               try {\r
+                       deployEnvironment.unpackTo(distribution, targetData\r
+                                       .getTargetRootLocation(), null);\r
+\r
+                       // FIXME: make it generic\r
+                       String deployDataPath = targetData.getTargetRootLocation()\r
+                                       .getCanonicalPath();\r
+\r
+                       deployEnvironment.unpackTo(deploymentData,\r
+                                       new File(deployDataPath), null);\r
+                       deployedSystem = new SimpleHttpdApplication();\r
+                       deployedSystem.setTargetData(targetData);\r
+\r
+                       log.info("Deployed " + distribution + " to " + targetData);\r
+               } catch (Exception e) {\r
+                       throw new SlcException("Cannot deploy " + distribution + " to "\r
+                                       + targetData, e);\r
+               }\r
+\r
+       }\r
+\r
+       public void setTargetData(TargetData targetData) {\r
+               this.targetData = (HttpdApplicationTargetData) targetData;\r
+       }\r
+\r
+       public void setDeploymentData(DeploymentData deploymentData) {\r
+               this.deploymentData = deploymentData;\r
+       }\r
+\r
+       public DeployedSystem getDeployedSystem() {\r
+               return deployedSystem;\r
+       }\r
+\r
+       public void setDistribution(Distribution distribution) {\r
+               this.distribution = distribution;\r
+       }\r
+\r
+       public void setDeployEnvironment(DeployEnvironment deployEnvironment) {\r
+               this.deployEnvironment = deployEnvironment;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java
new file mode 100644 (file)
index 0000000..3bc08c7
--- /dev/null
@@ -0,0 +1,80 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.io.File;\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.deploy.TargetData;\r
+\r
+public class HttpdApplicationTargetData implements TargetData {\r
+       private HttpdServer webServer;\r
+       private String relativePath;\r
+       private String targetRootPath;\r
+\r
+       public HttpdServer getWebServer() {\r
+               return webServer;\r
+       }\r
+\r
+       public void setWebServer(HttpdServer webServer) {\r
+               this.webServer = webServer;\r
+       }\r
+\r
+       public String getRelativePath() {\r
+               return relativePath;\r
+       }\r
+\r
+       /**\r
+        * If targetRootLocation not set, used to build the targetRootLocation,\r
+        * relative to the webserver base.\r
+        */\r
+       public void setRelativePath(String relativePath) {\r
+               this.relativePath = relativePath;\r
+       }\r
+\r
+       public String getTargetRootPath() {\r
+               return targetRootPath;\r
+       }\r
+\r
+       public void setTargetRootPath(String targetRootPath) {\r
+               this.targetRootPath = targetRootPath;\r
+       }\r
+\r
+       public URL getTargetBaseUrl() {\r
+               try {\r
+                       URL wsUrl = getWebServer().getBaseUrl();\r
+                       // TODO: use URI\r
+                       return new URL(wsUrl, wsUrl.getFile() + '/' + relativePath);\r
+               } catch (MalformedURLException e) {\r
+                       throw new SlcException("Cannot get base url for " + relativePath, e);\r
+               }\r
+       }\r
+\r
+       public File getTargetRootLocation() {\r
+               if (targetRootPath != null && !targetRootPath.equals("")) {\r
+                       return new File(targetRootPath);\r
+               } else {\r
+                       HttpdServerTargetData targetData = (HttpdServerTargetData) getWebServer()\r
+                                       .getTargetData();\r
+                       String path = targetData.getServerRoot() + File.separator\r
+                                       + getRelativePath();\r
+                       return new File(path);\r
+               }\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServer.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServer.java
new file mode 100644 (file)
index 0000000..9416f21
--- /dev/null
@@ -0,0 +1,65 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.io.IOException;\r
+import java.net.URL;\r
+\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.build.Distribution;\r
+import org.argeo.slc.deploy.DeploymentData;\r
+import org.argeo.slc.deploy.TargetData;\r
+\r
+public class HttpdServer implements WebServer {\r
+       private HttpdServerTargetData targetData;\r
+       private HttpdServerDeploymentData deploymentData;\r
+\r
+       public URL getBaseUrl() {\r
+               try {\r
+                       return new URL("http://localhost:" + targetData.getPort());\r
+               } catch (IOException e) {\r
+                       throw new SlcException("Cannot get url for Httpd server "\r
+                                       + getDeployedSystemId(), e);\r
+               }\r
+       }\r
+\r
+       public String getDeployedSystemId() {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+       public Distribution getDistribution() {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+       public DeploymentData getDeploymentData() {\r
+               return deploymentData;\r
+       }\r
+\r
+       public TargetData getTargetData() {\r
+               return targetData;\r
+       }\r
+\r
+       public void setTargetData(TargetData targetData) {\r
+               this.targetData = (HttpdServerTargetData)targetData;\r
+       }\r
+\r
+       public void setDeploymentData(DeploymentData deploymentData) {\r
+               this.deploymentData = (HttpdServerDeploymentData)deploymentData;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeployment.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeployment.java
new file mode 100644 (file)
index 0000000..f7915d8
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy;
+
+import org.argeo.slc.build.Distribution;
+import org.argeo.slc.deploy.DeployedSystem;
+import org.argeo.slc.deploy.Deployment;
+import org.argeo.slc.deploy.DeploymentData;
+import org.argeo.slc.deploy.TargetData;
+
+public class HttpdServerDeployment implements Deployment {
+//     private HttpdServerTargetData targetData;
+
+       public void run() {
+               // TODO Auto-generated method stub
+
+       }
+
+       public DeployedSystem getDeployedSystem() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public void setDeploymentData(DeploymentData deploymentData) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public void setDistribution(Distribution distribution) {
+       }
+
+       public void setTargetData(TargetData targetData) {
+//             this.targetData = (HttpdServerTargetData) targetData;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java
new file mode 100644 (file)
index 0000000..fd9b681
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy;
+
+import org.argeo.slc.deploy.DeploymentData;
+
+public class HttpdServerDeploymentData implements DeploymentData {
+       private String configFile;
+
+       public String getConfigFile() {
+               return configFile;
+       }
+
+       public void setConfigFile(String configFile) {
+               this.configFile = configFile;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerManager.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerManager.java
new file mode 100644 (file)
index 0000000..3fd76ed
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.deploy.DeployedSystemManager;
+
+public class HttpdServerManager implements DeployedSystemManager<HttpdServer> {
+       private final static Log log = LogFactory.getLog(HttpdServerManager.class);
+
+       private HttpdServer httpdServer;
+
+       public void start() {
+               runProcessAsync(createCommandLine("start"));
+               log.info("Started httpd server with root "
+                               + getHttpdServerTargetData().getServerRoot());
+       }
+
+       public void stop() {
+               runProcessAsync(createCommandLine("stop"));
+               log.info("Stopped httpd server with root "
+                               + getHttpdServerTargetData().getServerRoot());
+       }
+
+       protected String[] createCommandLine(String action) {
+               String httpdPath = getHttpdServerTargetData().getExecutables()
+                               .getExecutablePath("httpd");
+               String[] cmd = { httpdPath, "-d",
+                               getHttpdServerTargetData().getServerRoot(), "-f",
+                               getHttpdServerDeploymentData().getConfigFile(), "-k", action };
+               if (log.isDebugEnabled())
+                       log.debug("Command line: " + Arrays.asList(cmd));
+               return cmd;
+       }
+
+       protected static void runProcessAsync(String... command) {
+               ProcessBuilder procBuilder = new ProcessBuilder(command);
+               procBuilder.redirectErrorStream(true);
+               try {
+                       Process proc = procBuilder.start();
+                       final InputStream in = proc.getInputStream();
+                       Thread logThread = new Thread() {
+
+                               @Override
+                               public void run() {
+                                       BufferedReader reader = new BufferedReader(
+                                                       new InputStreamReader(in));
+                                       String line = null;
+                                       try {
+                                               while ((line = reader.readLine()) != null)
+                                                       log.info(line);
+                                       } catch (IOException e) {
+                                               log.error("Failed to read stdout", e);
+                                       }
+                               }
+                       };
+
+                       logThread.start();
+               } catch (IOException e) {
+                       throw new SlcException("Could not run command", e);
+               }
+       }
+
+       public void setDeployedSystem(HttpdServer httpdServer) {
+               this.httpdServer = httpdServer;
+       }
+
+       protected HttpdServerDeploymentData getHttpdServerDeploymentData() {
+               return (HttpdServerDeploymentData) httpdServer.getDeploymentData();
+       }
+
+       protected HttpdServerTargetData getHttpdServerTargetData() {
+               return (HttpdServerTargetData) httpdServer.getTargetData();
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerTargetData.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/HttpdServerTargetData.java
new file mode 100644 (file)
index 0000000..fa4e3f9
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy;
+
+import org.argeo.slc.deploy.InstalledExecutables;
+import org.argeo.slc.deploy.TargetData;
+
+public class HttpdServerTargetData implements TargetData {
+       private String serverRoot;
+       private Integer port;
+       private InstalledExecutables executables;
+
+       public String getServerRoot() {
+               return serverRoot;
+       }
+
+       public void setServerRoot(String serverRoot) {
+               this.serverRoot = serverRoot;
+       }
+
+       public Integer getPort() {
+               return port;
+       }
+
+       public void setPort(Integer port) {
+               this.port = port;
+       }
+
+       public InstalledExecutables getExecutables() {
+               return executables;
+       }
+
+       public void setExecutables(InstalledExecutables executables) {
+               this.executables = executables;
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/SimpleHttpdApplication.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/SimpleHttpdApplication.java
new file mode 100644 (file)
index 0000000..45c67f4
--- /dev/null
@@ -0,0 +1,62 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.io.File;\r
+import java.net.URL;\r
+\r
+import org.argeo.slc.build.Distribution;\r
+import org.argeo.slc.deploy.DeploymentData;\r
+\r
+public class SimpleHttpdApplication implements WebApplication {\r
+       private HttpdApplicationTargetData targetData;\r
+       private Distribution distribution;\r
+\r
+       public void setDistribution(Distribution distribution) {\r
+               this.distribution = distribution;\r
+       }\r
+\r
+       public URL getBaseUrl() {\r
+               return targetData.getTargetBaseUrl();\r
+       }\r
+\r
+       public File getRootLocation() {\r
+               return targetData.getTargetRootLocation();\r
+       }\r
+\r
+       public String getDeployedSystemId() {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+       public HttpdApplicationTargetData getTargetData() {\r
+               return targetData;\r
+       }\r
+\r
+       public void setTargetData(HttpdApplicationTargetData targetData) {\r
+               this.targetData = targetData;\r
+       }\r
+\r
+       public Distribution getDistribution() {\r
+               return distribution;\r
+       }\r
+\r
+       public DeploymentData getDeploymentData() {\r
+               // TODO Auto-generated method stub\r
+               return null;\r
+       }\r
+\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebApplication.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebApplication.java
new file mode 100644 (file)
index 0000000..6d1b38d
--- /dev/null
@@ -0,0 +1,27 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.io.File;\r
+import java.net.URL;\r
+\r
+import org.argeo.slc.deploy.DeployedSystem;\r
+\r
+public interface WebApplication extends DeployedSystem {\r
+       public URL getBaseUrl();\r
+\r
+       public File getRootLocation();\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebServer.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/WebServer.java
new file mode 100644 (file)
index 0000000..f1dbc10
--- /dev/null
@@ -0,0 +1,24 @@
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *         http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.support.deploy;\r
+\r
+import java.net.URL;\r
+\r
+import org.argeo.slc.deploy.DeployedSystem;\r
+\r
+public interface WebServer extends DeployedSystem {\r
+       public URL getBaseUrl();\r
+}\r
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/DbModel.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/DbModel.java
new file mode 100644 (file)
index 0000000..49f651b
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy.db;
+
+import java.sql.Connection;
+
+public interface DbModel {
+       public void createSchema(Connection connection);
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/JdbcAware.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/JdbcAware.java
new file mode 100644 (file)
index 0000000..5c10939
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy.db;
+
+import javax.sql.DataSource;
+
+public interface JdbcAware {
+       public DataSource getDataSource();
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java b/org.argeo.slc.support/src/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java
new file mode 100644 (file)
index 0000000..e04a3e5
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.support.deploy.db;
+
+import javax.sql.DataSource;
+
+import org.argeo.slc.deploy.AbstractDeployedSystem;
+
+public class SimpleJdbcDatabase extends AbstractDeployedSystem implements
+               JdbcAware {
+       private DataSource dataSource;
+
+       public String getDeployedSystemId() {
+               return dataSource.toString();
+       }
+
+       public DataSource getDataSource() {
+               return dataSource;
+       }
+
+       public void setDataSource(DataSource dataSource) {
+               this.dataSource = dataSource;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResource.java b/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResource.java
new file mode 100644 (file)
index 0000000..920fb8b
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.vfs;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import org.apache.commons.io.IOExceptionWithCause;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.NameScope;
+import org.argeo.slc.SlcException;
+import org.springframework.core.io.Resource;
+
+public class VfsResource implements Resource {
+       private FileObject fileObject;
+
+       public VfsResource(FileObject fileObject) {
+               this.fileObject = fileObject;
+       }
+
+       public Resource createRelative(String relativePath) throws IOException {
+               return new VfsResource(fileObject.resolveFile(relativePath,
+                               NameScope.DESCENDENT_OR_SELF));
+       }
+
+       public boolean exists() {
+               try {
+                       return fileObject.exists();
+               } catch (FileSystemException e) {
+                       throw new SlcException("Cannot find out whether " + fileObject
+                                       + " exists", e);
+               }
+       }
+
+       public String getDescription() {
+               return "VFS resource " + fileObject;
+       }
+
+       public File getFile() throws IOException {
+               throw new IOException("Cannot access " + getDescription()
+                               + " as a local file");
+               // TODO: access local files
+               // if(fileObject instanceof LocalFile){
+               // ((LocalFile)fileObject).
+               // }
+               // return null;
+       }
+
+       public String getFilename() {
+               return fileObject.getName().getBaseName();
+       }
+
+       public URI getURI() throws IOException {
+               try {
+                       return new URI(fileObject.getName().getURI());
+               } catch (URISyntaxException e) {
+                       throw new IOExceptionWithCause(e);
+               }
+       }
+
+       public URL getURL() throws IOException {
+               return fileObject.getURL();
+       }
+
+       public boolean isOpen() {
+               return fileObject.isContentOpen();
+       }
+
+       public boolean isReadable() {
+               try {
+                       return fileObject.isReadable();
+               } catch (FileSystemException e) {
+                       throw new SlcException("Cannot find out whether " + fileObject
+                                       + " is readable", e);
+               }
+       }
+
+       public long lastModified() throws IOException {
+               return fileObject.getContent().getLastModifiedTime();
+       }
+
+       public InputStream getInputStream() throws IOException {
+               return fileObject.getContent().getInputStream();
+       }
+
+       public FileObject getFileObject() {
+               return fileObject;
+       }
+
+       public long contentLength(){
+               return -1;
+       }
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceFactory.java b/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceFactory.java
new file mode 100644 (file)
index 0000000..6a3b6ca
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.vfs;
+
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.StandardFileSystemManager;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.core.io.Resource;
+
+public class VfsResourceFactory implements FactoryBean, InitializingBean {
+       private String url;
+       private FileSystemManager fileSystemManager;
+
+       public Object getObject() throws Exception {
+               return new VfsResource(fileSystemManager.resolveFile(url));
+       }
+
+       public Class<?> getObjectType() {
+               return Resource.class;
+       }
+
+       public boolean isSingleton() {
+               return false;
+       }
+
+       public void afterPropertiesSet() throws Exception {
+               if (fileSystemManager == null) {
+                       fileSystemManager = new StandardFileSystemManager();
+                       ((StandardFileSystemManager) fileSystemManager)
+                                       .setCacheStrategy(CacheStrategy.ON_RESOLVE);
+                       ((StandardFileSystemManager) fileSystemManager).init();
+               }
+
+       }
+
+}
diff --git a/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceSet.java b/org.argeo.slc.support/src/org/argeo/slc/vfs/VfsResourceSet.java
new file mode 100644 (file)
index 0000000..8adb276
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed 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 org.argeo.slc.vfs;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.core.deploy.ResourceSet;
+import org.springframework.core.io.Resource;
+
+public class VfsResourceSet implements ResourceSet {
+       private String base;
+
+       public Map<String, Resource> listResources() {
+               try {
+                       FileSystemManager fileSystemManager = VFS.getManager();
+                       FileObject fileObject = fileSystemManager.resolveFile(base);
+                       Map<String, Resource> map = new HashMap<String, Resource>();
+                       addToMap(map, "", fileObject);
+
+                       // TODO: add filters
+                       return map;
+               } catch (FileSystemException e) {
+                       throw new SlcException("Cannot list VFS resources from " + base, e);
+               }
+       }
+
+       /** recursive */
+       protected void addToMap(Map<String, Resource> map, String parentPath,
+                       FileObject fileObject) {
+               try {
+                       String newParentPath = parentPath
+                                       + fileObject.getName().getBaseName() + '/';
+                       if (fileObject.getType().hasChildren()) {
+                               for (FileObject child : fileObject.getChildren()) {
+                                       addToMap(map, newParentPath, child);
+                               }
+                       } else {
+                               map.put(parentPath + fileObject.getName().getBaseName(),
+                                               new VfsResource(fileObject));
+                       }
+               } catch (FileSystemException e) {
+                       throw new SlcException("Cannot add children from " + parentPath, e);
+               }
+       }
+
+       public void setBase(String base) {
+               this.base = base;
+       }
+
+}
diff --git a/pom.xml b/pom.xml
index 91d640de574b447ee722a0cc7acd7fe3c108e3d0..6c15049a6845531d0876af8df371db885be34d3b 100644 (file)
--- a/pom.xml
+++ b/pom.xml
                <developmentCycle.slc>2.1</developmentCycle.slc>
                <developmentCycle.startDate>2015-02-12</developmentCycle.startDate>
                <version.slc>2.1.1-SNAPSHOT</version.slc>
+               <!-- Libraries versions -->
+               <version.argeo-tp-extras>2.1.5</version.argeo-tp-extras>
        </properties>
        <modules>
                <module>org.argeo.slc.api</module>
                <module>org.argeo.slc.core</module>
                <module>org.argeo.slc.unit</module>
+               <module>org.argeo.slc.repo</module>
 
 <!--           <module>runtime</module> -->
 <!--           <module>modules</module> -->
@@ -117,7 +120,35 @@ limitations under the License.
                                <checksumPolicy>warn</checksumPolicy>
                        </releases>
                </repository>
+               <!-- 
+               <repository>
+                       <id>argeo-tp-extras</id>
+                       <url>https://forge.argeo.org/data/public/java/argeo-tp-extras-2.1</url>
+                       <releases>
+                               <enabled>true</enabled>
+                               <updatePolicy>daily</updatePolicy>
+                               <checksumPolicy>warn</checksumPolicy>
+                       </releases>
+               </repository>
+                -->
+               <repository>
+                       <id>argeo-tp-extras-local</id>
+                       <url>http://localhost:7080/data/public/java/argeo-tp-extras-2.1</url>
+                       <releases>
+                               <enabled>true</enabled>
+                               <updatePolicy>daily</updatePolicy>
+                               <checksumPolicy>warn</checksumPolicy>
+                       </releases>
+               </repository>
        </repositories>
+       <dependencies>
+               <dependency>
+                       <groupId>org.argeo.tp.extras</groupId>
+                       <artifactId>argeo-tp-extras</artifactId>
+                       <version>${version.argeo-tp-extras}</version>
+                       <scope>provided</scope>
+               </dependency>
+       </dependencies>
        <distributionManagement>
                <repository>
                        <id>staging</id>
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArgeoOsgiDistribution.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArgeoOsgiDistribution.java
deleted file mode 100644 (file)
index 493486e..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.argeo.slc.repo;
-
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.build.ModularDistribution;
-
-/** Aether compatible OSGi distribution */
-public interface ArgeoOsgiDistribution extends Distribution,
-               CategorizedNameVersion, ModularDistribution {
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactDistribution.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactDistribution.java
deleted file mode 100644 (file)
index d76da46..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.argeo.slc.repo;
-
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.build.Distribution;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/** A {@link Distribution} based on an Aether {@link Artifact} */
-public class ArtifactDistribution implements Distribution,
-               CategorizedNameVersion {
-       private final Artifact artifact;
-
-       public ArtifactDistribution(Artifact artifact) {
-               this.artifact = artifact;
-       }
-
-       public ArtifactDistribution(String coords) {
-               this(new DefaultArtifact(coords));
-       }
-
-       /** Aether coordinates of the underlying artifact. */
-       public String getDistributionId() {
-               return artifact.toString();
-       }
-
-       public Artifact getArtifact() {
-               return artifact;
-       }
-
-       public String getName() {
-               return getArtifact().getArtifactId();
-       }
-
-       public String getVersion() {
-               return getArtifact().getVersion();
-       }
-
-       public String getCategory() {
-               return getArtifact().getGroupId();
-       }
-
-       @Override
-       public int hashCode() {
-               return artifact.hashCode();
-       }
-
-       @Override
-       public boolean equals(Object obj) {
-               if (obj instanceof CategorizedNameVersion) {
-                       CategorizedNameVersion cnv = (CategorizedNameVersion) obj;
-                       return getCategory().equals(cnv.getCategory())
-                                       && getName().equals(cnv.getName())
-                                       && getVersion().equals(cnv.getVersion());
-               } else
-                       return artifact.equals(obj);
-       }
-
-       @Override
-       public String toString() {
-               return getDistributionId();
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ArtifactIndexer.java
deleted file mode 100644 (file)
index 27c6806..0000000
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherUtils;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.osgi.framework.Constants;
-import org.sonatype.aether.artifact.Artifact;
-
-/**
- * Add {@link Artifact} properties to a {@link Node}. Does nothing if the node
- * name doesn't start with the artifact id (in order to skip Maven metadata XML
- * files and other non artifact files).
- */
-public class ArtifactIndexer implements NodeIndexer, SlcNames {
-       private Log log = LogFactory.getLog(ArtifactIndexer.class);
-       private Boolean force = false;
-
-       public Boolean support(String path) {
-               String relativePath = getRelativePath(path);
-               if (relativePath == null)
-                       return false;
-               Artifact artifact = null;
-               try {
-                       artifact = AetherUtils.convertPathToArtifact(relativePath, null);
-               } catch (Exception e) {
-                       if (log.isTraceEnabled())
-                               log.trace("Malformed path " + path + ", skipping silently", e);
-               }
-               return artifact != null;
-       }
-
-       public void index(Node fileNode) {
-               Artifact artifact = null;
-               try {
-                       if (!support(fileNode.getPath()))
-                               return;
-
-                       // Already indexed
-                       if (!force && fileNode.isNodeType(SlcTypes.SLC_ARTIFACT))
-                               return;
-
-                       if (!fileNode.isNodeType(NodeType.NT_FILE))
-                               return;
-
-                       String relativePath = getRelativePath(fileNode.getPath());
-                       if (relativePath == null)
-                               return;
-                       artifact = AetherUtils.convertPathToArtifact(relativePath, null);
-                       // support() guarantees that artifact won't be null, no NPE check
-                       fileNode.addMixin(SlcTypes.SLC_ARTIFACT);
-                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_ID,
-                                       artifact.getArtifactId());
-                       fileNode.setProperty(SlcNames.SLC_GROUP_ID, artifact.getGroupId());
-                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_VERSION,
-                                       artifact.getVersion());
-                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_EXTENSION,
-                                       artifact.getExtension());
-                       // can be null but ok for JCR API
-                       fileNode.setProperty(SlcNames.SLC_ARTIFACT_CLASSIFIER,
-                                       artifact.getClassifier());
-                       JcrUtils.updateLastModified(fileNode);
-
-                       // make sure there are checksums
-                       String shaNodeName = fileNode.getName() + ".sha1";
-                       if (!fileNode.getParent().hasNode(shaNodeName)) {
-                               String sha = JcrUtils.checksumFile(fileNode, "SHA-1");
-                               JcrUtils.copyBytesAsFile(fileNode.getParent(), shaNodeName,
-                                               sha.getBytes());
-                       }
-                       String md5NodeName = fileNode.getName() + ".md5";
-                       if (!fileNode.getParent().hasNode(md5NodeName)) {
-                               String md5 = JcrUtils.checksumFile(fileNode, "MD5");
-                               JcrUtils.copyBytesAsFile(fileNode.getParent(), md5NodeName,
-                                               md5.getBytes());
-                       }
-
-                       // Create a default pom if none already exist
-                       String fileNodeName = fileNode.getName();
-                       String pomName = null;
-                       if (fileNodeName.endsWith(".jar"))
-                               pomName = fileNodeName.substring(0, fileNodeName.length()
-                                               - ".jar".length())
-                                               + ".pom";
-
-                       if (pomName != null && !fileNode.getParent().hasNode(pomName)) {
-                               String pom = generatePomForBundle(fileNode);
-                               Node pomNode = JcrUtils.copyBytesAsFile(fileNode.getParent(),
-                                               pomName, pom.getBytes());
-                               // corresponding check sums
-                               String sha = JcrUtils.checksumFile(pomNode, "SHA-1");
-                               JcrUtils.copyBytesAsFile(fileNode.getParent(), pomName
-                                               + ".sha1", sha.getBytes());
-                               String md5 = JcrUtils.checksumFile(fileNode, "MD5");
-                               JcrUtils.copyBytesAsFile(fileNode.getParent(),
-                                               pomName + ".md5", md5.getBytes());
-                       }
-
-                       // set higher levels
-                       Node artifactVersionBase = fileNode.getParent();
-                       if (!artifactVersionBase
-                                       .isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
-                               artifactVersionBase
-                                               .addMixin(SlcTypes.SLC_ARTIFACT_VERSION_BASE);
-                               artifactVersionBase.setProperty(SlcNames.SLC_ARTIFACT_VERSION,
-                                               artifact.getBaseVersion());
-                               artifactVersionBase.setProperty(SlcNames.SLC_ARTIFACT_ID,
-                                               artifact.getArtifactId());
-                               artifactVersionBase.setProperty(SlcNames.SLC_GROUP_ID,
-                                               artifact.getGroupId());
-                       }
-                       JcrUtils.updateLastModified(artifactVersionBase);
-
-                       // pom
-                       if (artifact.getExtension().equals("pom")) {
-                               // TODO read to make it a distribution
-                       }
-
-                       Node artifactBase = artifactVersionBase.getParent();
-                       if (!artifactBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
-                               artifactBase.addMixin(SlcTypes.SLC_ARTIFACT_BASE);
-                               artifactBase.setProperty(SlcNames.SLC_ARTIFACT_ID,
-                                               artifact.getArtifactId());
-                               artifactBase.setProperty(SlcNames.SLC_GROUP_ID,
-                                               artifact.getGroupId());
-                       }
-                       JcrUtils.updateLastModified(artifactBase);
-
-                       Node groupBase = artifactBase.getParent();
-                       if (!groupBase.isNodeType(SlcTypes.SLC_GROUP_BASE)) {
-                               // if (groupBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
-                               // log.warn("Group base " + groupBase.getPath()
-                               // + " is also artifact base");
-                               // }
-                               groupBase.addMixin(SlcTypes.SLC_GROUP_BASE);
-                               groupBase.setProperty(SlcNames.SLC_GROUP_BASE_ID,
-                                               artifact.getGroupId());
-                       }
-                       JcrUtils.updateLastModifiedAndParents(groupBase,
-                                       RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH);
-
-                       if (log.isTraceEnabled())
-                               log.trace("Indexed artifact " + artifact + " on " + fileNode);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot index artifact " + artifact
-                                       + " metadata on node " + fileNode, e);
-               }
-       }
-
-       private String getRelativePath(String nodePath) {
-               String basePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-               if (!nodePath.startsWith(basePath))
-                       return null;
-               String relativePath = nodePath.substring(basePath.length());
-               return relativePath;
-       }
-
-       public void setForce(Boolean force) {
-               this.force = force;
-       }
-
-       private String generatePomForBundle(Node n) throws RepositoryException {
-               StringBuffer p = new StringBuffer();
-               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
-               p.append("<modelVersion>4.0.0</modelVersion>");
-
-               // Categorized name version
-               p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
-                               .append("</groupId>\n");
-               p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
-                               .append("</artifactId>\n");
-               p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
-                               .append("</version>\n");
-               // TODO make it more generic
-               p.append("<packaging>jar</packaging>\n");
-               if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
-                       p.append("<name>")
-                                       .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
-                                       .append("</name>\n");
-               if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
-                       p.append("<description>")
-                                       .append(JcrUtils
-                                                       .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
-                                       .append("</description>\n");
-
-               // Dependencies in case of a distribution
-               if (n.isNodeType(SlcTypes.SLC_MODULAR_DISTRIBUTION)) {
-                       p.append(getDependenciesSnippet(n.getNode(SlcNames.SLC_MODULES)
-                                       .getNodes()));
-                       p.append(getDependencyManagementSnippet(n.getNode(
-                                       SlcNames.SLC_MODULES).getNodes()));
-               }
-               p.append("</project>\n");
-               return p.toString();
-       }
-
-       private String getDependenciesSnippet(NodeIterator nit)
-                       throws RepositoryException {
-               StringBuilder b = new StringBuilder();
-               b.append("<dependencies>\n");
-               while (nit.hasNext()) {
-                       Node currModule = nit.nextNode();
-                       if (currModule.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
-                               b.append(getDependencySnippet(
-                                               currModule.getProperty(SlcNames.SLC_CATEGORY)
-                                                               .getString(),
-                                               currModule.getProperty(SlcNames.SLC_NAME).getString(),
-                                               null));
-                       }
-               }
-               b.append("</dependencies>\n");
-               return b.toString();
-       }
-
-       private String getDependencyManagementSnippet(NodeIterator nit)
-                       throws RepositoryException {
-               StringBuilder b = new StringBuilder();
-               b.append("<dependencyManagement>\n");
-               b.append("<dependencies>\n");
-               while (nit.hasNext()) {
-                       Node currModule = nit.nextNode();
-                       if (currModule.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
-                               b.append(getDependencySnippet(
-                                               currModule.getProperty(SlcNames.SLC_CATEGORY)
-                                                               .getString(),
-                                               currModule.getProperty(SlcNames.SLC_NAME).getString(),
-                                               currModule.getProperty(SlcNames.SLC_VERSION)
-                                                               .getString()));
-                       }
-               }
-               b.append("</dependencies>\n");
-               b.append("</dependencyManagement>\n");
-               return b.toString();
-       }
-
-       private String getDependencySnippet(String category, String name,
-                       String version) {
-               StringBuilder b = new StringBuilder();
-               b.append("<dependency>\n");
-               b.append("\t<groupId>").append(category).append("</groupId>\n");
-               b.append("\t<artifactId>").append(name).append("</artifactId>\n");
-               if (version != null)
-                       b.append("\t<version>").append(version).append("</version>\n");
-               b.append("</dependency>\n");
-               return b.toString();
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/FreeLicense.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/FreeLicense.java
deleted file mode 100644 (file)
index 1b83666..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-package org.argeo.slc.repo;
-
-import java.io.InputStream;
-import java.net.URL;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.build.License;
-
-/** A free software license */
-public abstract class FreeLicense implements License {
-       final static String RESOURCES = "/org/argeo/slc/repo/license/";
-
-       /** GNU */
-       public final static FreeLicense GPL_v3 = new FreeLicense(
-                       "GNU General Public License, version 3.0",
-                       "http://www.gnu.org/licenses/gpl-3.0.txt",
-                       "http://www.gnu.org/licenses/", RESOURCES + "gpl-3.0.txt") {
-       };
-
-       public final static FreeLicense GPL_v2 = new FreeLicense(
-                       "GNU General Public License, version 2.0",
-                       "http://www.gnu.org/licenses/gpl-2.0.txt",
-                       "http://www.gnu.org/licenses/", RESOURCES + "gpl-2.0.txt") {
-       };
-       public final static FreeLicense GPL = GPL_v3;
-
-       public final static FreeLicense LGPL_v3 = new FreeLicense(
-                       "GNU Lesser General Public License, version 3.0",
-                       "http://www.gnu.org/licenses/lgpl-3.0.txt",
-                       "http://www.gnu.org/licenses/", RESOURCES + "lgpl-3.0.txt") {
-       };
-
-       public final static FreeLicense LGPL_v2 = new FreeLicense(
-                       "GNU Lesser General Public License, version 2.1",
-                       "http://www.gnu.org/licenses/lgpl-2.1.txt",
-                       "http://www.gnu.org/licenses/", RESOURCES + "lgpl-2.1.txt") {
-       };
-       public final static FreeLicense LGPL = LGPL_v3;
-
-       /** Apache */
-       public final static FreeLicense APACHE_v2 = new FreeLicense(
-                       "Apache License, Version 2.0",
-                       "http://www.apache.org/licenses/LICENSE-2.0.txt",
-                       "http://www.apache.org/licenses/", RESOURCES + "apache-2.0.txt") {
-       };
-       public final static FreeLicense APACHE = APACHE_v2;
-
-       /** Eclipse */
-       public final static FreeLicense EPL_v1 = new FreeLicense(
-                       "Eclipse Public License, Version 1.0",
-                       "http://www.eclipse.org/legal/epl-v10.html",
-                       "http://www.eclipse.org/legal/eplfaq.php", RESOURCES
-                                       + "epl-1.0.txt") {
-       };
-       public final static FreeLicense EPL = EPL_v1;
-
-       /** Miscellaneous */
-       public final static FreeLicense MIT = new FreeLicense("The MIT License",
-                       "http://opensource.org/licenses/MIT", null, RESOURCES + "mit.txt") {
-       };
-
-       public final static FreeLicense BSD_NEW = new FreeLicense(
-                       "The BSD 3-Clause License",
-                       "http://opensource.org/licenses/BSD-3-Clause", null, RESOURCES
-                                       + "bsd-3-clause.txt") {
-       };
-
-       public final static FreeLicense BSD = BSD_NEW;
-
-       public final static FreeLicense CDDL_v1 = new FreeLicense(
-                       "Common Development and Distribution License",
-                       "http://opensource.org/licenses/CDDL-1.0", null, RESOURCES
-                                       + "cddl-1.0.txt") {
-       };
-       public final static FreeLicense CDDL = CDDL_v1;
-
-       /** Public domain corner case */
-       public final static License PUBLIC_DOMAIN = new License() {
-
-               public String getUri() {
-                       return "http://creativecommons.org/about/pdm";
-               }
-
-               public String getText() {
-                       return "This work is free of known copyright restrictions.";
-               }
-
-               public String getName() {
-                       return "Public Domain License";
-               }
-
-               public String getLink() {
-                       return "http://wiki.creativecommons.org/PDM_FAQ";
-               }
-       };
-
-       private final String name, uri, link, resource;
-
-       public FreeLicense(String name, String uri) {
-               this(name, uri, null, null);
-       }
-
-       public FreeLicense(String name, String uri, String link) {
-               this(name, uri, link, null);
-       }
-
-       public FreeLicense(String name, String uri, String link, String resource) {
-               if (uri == null)
-                       throw new SlcException("URI cannot be null");
-               this.name = name;
-               this.uri = uri;
-               this.link = link;
-               this.resource = resource;
-               getText();
-       }
-
-       public String getName() {
-               return name;
-       }
-
-       public String getUri() {
-               return uri;
-       }
-
-       public String getLink() {
-               return link;
-       }
-
-       @Override
-       public String getText() {
-               InputStream in = null;
-               URL url = null;
-               try {
-                       if (resource != null)
-                               url = getClass().getClassLoader().getResource(resource);
-                       else
-                               url = new URL(uri);
-                       in = url.openStream();
-                       String text = IOUtils.toString(in);
-                       return text;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot retrieve license " + name + " from "
-                                       + url, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       @Override
-       public boolean equals(Object obj) {
-               if (!(obj instanceof License))
-                       return false;
-               return ((License) obj).getUri().equals(getUri());
-       }
-
-       @Override
-       public int hashCode() {
-               return getUri().hashCode();
-       }
-
-       @Override
-       public String toString() {
-               return name + " (" + uri + ")";
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JarFileIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JarFileIndexer.java
deleted file mode 100644 (file)
index b07cade..0000000
+++ /dev/null
@@ -1,498 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-import java.util.jar.Attributes;
-import java.util.jar.Attributes.Name;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import java.util.jar.Manifest;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Version;
-
-/**
- * Indexes jar file, currently supports standard J2SE and OSGi metadata (both
- * from MANIFEST)
- */
-public class JarFileIndexer implements NodeIndexer, SlcNames {
-       private final static Log log = LogFactory.getLog(JarFileIndexer.class);
-       private Boolean force = false;
-
-       public Boolean support(String path) {
-               return FilenameUtils.getExtension(path).equals("jar");
-       }
-
-       public void index(Node fileNode) {
-               Binary fileBinary = null;
-               JarInputStream jarIn = null;
-               ByteArrayOutputStream bo = null;
-               ByteArrayInputStream bi = null;
-               Binary manifestBinary = null;
-               try {
-                       if (!support(fileNode.getPath()))
-                               return;
-
-                       // Already indexed
-                       if (!force && fileNode.isNodeType(SlcTypes.SLC_JAR_FILE))
-                               return;
-
-                       if (!fileNode.isNodeType(NodeType.NT_FILE))
-                               return;
-
-                       Session jcrSession = fileNode.getSession();
-                       Node contentNode = fileNode.getNode(Node.JCR_CONTENT);
-                       fileBinary = contentNode.getProperty(Property.JCR_DATA).getBinary();
-
-                       jarIn = new JarInputStream(fileBinary.getStream());
-                       Manifest manifest = jarIn.getManifest();
-                       if (manifest == null) {
-                               log.error(fileNode + " has no MANIFEST");
-                               return;
-                       }
-
-                       bo = new ByteArrayOutputStream();
-                       manifest.write(bo);
-                       byte[] newManifest = bo.toByteArray();
-                       if (fileNode.hasProperty(SLC_MANIFEST)) {
-                               byte[] storedManifest = JcrUtils.getBinaryAsBytes(fileNode
-                                               .getProperty(SLC_MANIFEST));
-                               if (Arrays.equals(newManifest, storedManifest)) {
-                                       if (log.isTraceEnabled())
-                                               log.trace("Manifest not changed, doing nothing "
-                                                               + fileNode);
-                                       return;
-                               }
-                       }
-
-                       bi = new ByteArrayInputStream(newManifest);
-                       manifestBinary = jcrSession.getValueFactory().createBinary(bi);
-
-                       // standard jar file
-                       fileNode.addMixin(SlcTypes.SLC_JAR_FILE);
-
-                       fileNode.setProperty(SlcNames.SLC_MANIFEST, manifestBinary);
-                       Attributes attrs = manifest.getMainAttributes();
-
-                       getI18nValues(fileBinary, attrs);
-
-                       // standard J2SE MANIFEST attributes
-                       addAttr(Attributes.Name.MANIFEST_VERSION, fileNode, attrs);
-                       addAttr(Attributes.Name.SIGNATURE_VERSION, fileNode, attrs);
-                       addAttr(Attributes.Name.CLASS_PATH, fileNode, attrs);
-                       addAttr(Attributes.Name.MAIN_CLASS, fileNode, attrs);
-                       addAttr(Attributes.Name.EXTENSION_NAME, fileNode, attrs);
-                       addAttr(Attributes.Name.IMPLEMENTATION_VERSION, fileNode, attrs);
-                       addAttr(Attributes.Name.IMPLEMENTATION_VENDOR, fileNode, attrs);
-                       addAttr(Attributes.Name.IMPLEMENTATION_VENDOR_ID, fileNode, attrs);
-                       addAttr(Attributes.Name.SPECIFICATION_TITLE, fileNode, attrs);
-                       addAttr(Attributes.Name.SPECIFICATION_VERSION, fileNode, attrs);
-                       addAttr(Attributes.Name.SPECIFICATION_VENDOR, fileNode, attrs);
-                       addAttr(Attributes.Name.SEALED, fileNode, attrs);
-
-                       // OSGi
-                       if (attrs.containsKey(new Name(Constants.BUNDLE_SYMBOLICNAME))) {
-                               addOsgiMetadata(fileNode, attrs);
-                               if (log.isTraceEnabled())
-                                       log.trace("Indexed OSGi bundle " + fileNode);
-                       } else {
-                               if (log.isTraceEnabled())
-                                       log.trace("Indexed JAR file " + fileNode);
-                       }
-
-                       JcrUtils.updateLastModified(fileNode);
-
-               } catch (Exception e) {
-                       throw new SlcException("Cannot index jar " + fileNode, e);
-               } finally {
-                       IOUtils.closeQuietly(bi);
-                       IOUtils.closeQuietly(bo);
-                       IOUtils.closeQuietly(jarIn);
-                       JcrUtils.closeQuietly(manifestBinary);
-                       JcrUtils.closeQuietly(fileBinary);
-               }
-
-       }
-
-       private void getI18nValues(Binary fileBinary, Attributes attrs)
-                       throws IOException {
-               JarInputStream jarIn = null;
-               try {
-                       jarIn = new JarInputStream(fileBinary.getStream());
-                       String bundleLocalization = null;
-
-                       String blKey = Constants.BUNDLE_LOCALIZATION; // "Bundle-Localization";
-                       Name blkName = new Name(blKey);
-
-                       browse: for (Object obj : attrs.keySet()) {
-                               String value = attrs.getValue((Attributes.Name) obj);
-                               if (value.startsWith("%")) {
-                                       if (attrs.containsKey(blkName)) {
-                                               bundleLocalization = attrs.getValue(blkName);
-                                               break browse;
-                                       }
-                               }
-                       }
-
-                       JarEntry jarEntry = null;
-                       byte[] propBytes = null;
-                       ByteArrayOutputStream baos = null;
-                       browse: if (bundleLocalization != null) {
-                               JarEntry entry = jarIn.getNextJarEntry();
-                               while (entry != null) {
-                                       if (entry.getName().equals(
-                                                       bundleLocalization + ".properties")) {
-                                               jarEntry = entry;
-
-                                               // if(je.getSize() != -1){
-                                               // propBytes = new byte[(int)je.getSize()];
-                                               // int len = (int) je.getSize();
-                                               // int offset = 0;
-                                               // while (offset != len)
-                                               // offset += jarIn.read(propBytes, offset, len -
-                                               // offset);
-                                               // } else {
-                                               baos = new ByteArrayOutputStream();
-                                               while (true) {
-                                                       int qwe = jarIn.read();
-                                                       if (qwe == -1)
-                                                               break;
-                                                       baos.write(qwe);
-                                               }
-                                               propBytes = baos.toByteArray();
-                                               break browse;
-                                       }
-                                       entry = jarIn.getNextJarEntry();
-                               }
-                       }
-
-                       if (jarEntry != null) {
-                               Properties prop = new Properties();
-                               InputStream is = new ByteArrayInputStream(propBytes);
-                               prop.load(is);
-
-                               for (Object obj : attrs.keySet()) {
-                                       String value = attrs.getValue((Attributes.Name) obj);
-                                       if (value.startsWith("%")) {
-                                               String newVal = prop.getProperty(value.substring(1));
-                                               if (newVal != null)
-                                                       attrs.put(obj, newVal);
-                                       }
-                               }
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException(
-                                       "Error while reading the jar binary content " + fileBinary,
-                                       e);
-               } catch (IOException ioe) {
-                       throw new SlcException("unable to get internationalized values",
-                                       ioe);
-               } finally {
-                       IOUtils.closeQuietly(jarIn);
-               }
-       }
-
-       protected void addOsgiMetadata(Node fileNode, Attributes attrs)
-                       throws RepositoryException {
-
-               // TODO remove this ?
-               // Compulsory for the time being, because bundle artifact extends
-               // artifact
-               if (!fileNode.isNodeType(SlcTypes.SLC_ARTIFACT)) {
-                       ArtifactIndexer indexer = new ArtifactIndexer();
-                       indexer.index(fileNode);
-               }
-
-               fileNode.addMixin(SlcTypes.SLC_BUNDLE_ARTIFACT);
-
-               // symbolic name
-               String symbolicName = attrs.getValue(Constants.BUNDLE_SYMBOLICNAME);
-               // make sure there is no directive
-               symbolicName = symbolicName.split(";")[0];
-               fileNode.setProperty(SlcNames.SLC_SYMBOLIC_NAME, symbolicName);
-
-               // direct mapping
-               addAttr(Constants.BUNDLE_SYMBOLICNAME, fileNode, attrs);
-               addAttr(Constants.BUNDLE_NAME, fileNode, attrs);
-               addAttr(Constants.BUNDLE_DESCRIPTION, fileNode, attrs);
-               addAttr(Constants.BUNDLE_MANIFESTVERSION, fileNode, attrs);
-               addAttr(Constants.BUNDLE_CATEGORY, fileNode, attrs);
-               addAttr(Constants.BUNDLE_ACTIVATIONPOLICY, fileNode, attrs);
-               addAttr(Constants.BUNDLE_COPYRIGHT, fileNode, attrs);
-               addAttr(Constants.BUNDLE_VENDOR, fileNode, attrs);
-               addAttr("Bundle-License", fileNode, attrs);
-               addAttr(Constants.BUNDLE_DOCURL, fileNode, attrs);
-               addAttr(Constants.BUNDLE_CONTACTADDRESS, fileNode, attrs);
-               addAttr(Constants.BUNDLE_ACTIVATOR, fileNode, attrs);
-               addAttr(Constants.BUNDLE_UPDATELOCATION, fileNode, attrs);
-               addAttr(Constants.BUNDLE_LOCALIZATION, fileNode, attrs);
-
-               // required execution environment
-               if (attrs.containsKey(new Name(
-                               Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)))
-                       fileNode.setProperty(SlcNames.SLC_
-                                       + Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, attrs
-                                       .getValue(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)
-                                       .split(","));
-
-               // bundle classpath
-               if (attrs.containsKey(new Name(Constants.BUNDLE_CLASSPATH)))
-                       fileNode.setProperty(SlcNames.SLC_ + Constants.BUNDLE_CLASSPATH,
-                                       attrs.getValue(Constants.BUNDLE_CLASSPATH).split(","));
-
-               // version
-               Version version = new Version(attrs.getValue(Constants.BUNDLE_VERSION));
-               fileNode.setProperty(SlcNames.SLC_BUNDLE_VERSION, version.toString());
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.BUNDLE_VERSION);
-               Node bundleVersionNode = fileNode.addNode(SlcNames.SLC_
-                               + Constants.BUNDLE_VERSION, SlcTypes.SLC_OSGI_VERSION);
-               mapOsgiVersion(version, bundleVersionNode);
-
-               // fragment
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.FRAGMENT_HOST);
-               if (attrs.containsKey(new Name(Constants.FRAGMENT_HOST))) {
-                       String fragmentHost = attrs.getValue(Constants.FRAGMENT_HOST);
-                       String[] tokens = fragmentHost.split(";");
-                       Node node = fileNode.addNode(SlcNames.SLC_
-                                       + Constants.FRAGMENT_HOST, SlcTypes.SLC_FRAGMENT_HOST);
-                       node.setProperty(SlcNames.SLC_SYMBOLIC_NAME, tokens[0]);
-                       for (int i = 1; i < tokens.length; i++) {
-                               if (tokens[i].startsWith(Constants.BUNDLE_VERSION_ATTRIBUTE)) {
-                                       node.setProperty(SlcNames.SLC_BUNDLE_VERSION,
-                                                       attributeValue(tokens[i]));
-                               }
-                       }
-               }
-
-               // imported packages
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.IMPORT_PACKAGE);
-               if (attrs.containsKey(new Name(Constants.IMPORT_PACKAGE))) {
-                       String importPackages = attrs.getValue(Constants.IMPORT_PACKAGE);
-                       List<String> packages = parseCommaSeparated(importPackages);
-                       for (String pkg : packages) {
-                               String[] tokens = pkg.split(";");
-                               Node node = fileNode.addNode(SlcNames.SLC_
-                                               + Constants.IMPORT_PACKAGE,
-                                               SlcTypes.SLC_IMPORTED_PACKAGE);
-                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
-                               for (int i = 1; i < tokens.length; i++) {
-                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
-                                               node.setProperty(SlcNames.SLC_VERSION,
-                                                               attributeValue(tokens[i]));
-                                       } else if (tokens[i]
-                                                       .startsWith(Constants.RESOLUTION_DIRECTIVE)) {
-                                               node.setProperty(
-                                                               SlcNames.SLC_OPTIONAL,
-                                                               directiveValue(tokens[i]).equals(
-                                                                               Constants.RESOLUTION_OPTIONAL));
-                                       }
-                               }
-                       }
-               }
-
-               // dynamic import package
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.DYNAMICIMPORT_PACKAGE);
-               if (attrs.containsKey(new Name(Constants.DYNAMICIMPORT_PACKAGE))) {
-                       String importPackages = attrs
-                                       .getValue(Constants.DYNAMICIMPORT_PACKAGE);
-                       List<String> packages = parseCommaSeparated(importPackages);
-                       for (String pkg : packages) {
-                               String[] tokens = pkg.split(";");
-                               Node node = fileNode.addNode(SlcNames.SLC_
-                                               + Constants.DYNAMICIMPORT_PACKAGE,
-                                               SlcTypes.SLC_DYNAMIC_IMPORTED_PACKAGE);
-                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
-                               for (int i = 1; i < tokens.length; i++) {
-                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
-                                               node.setProperty(SlcNames.SLC_VERSION,
-                                                               attributeValue(tokens[i]));
-                                       }
-                               }
-                       }
-               }
-
-               // exported packages
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.EXPORT_PACKAGE);
-               if (attrs.containsKey(new Name(Constants.EXPORT_PACKAGE))) {
-                       String exportPackages = attrs.getValue(Constants.EXPORT_PACKAGE);
-                       List<String> packages = parseCommaSeparated(exportPackages);
-                       for (String pkg : packages) {
-                               String[] tokens = pkg.split(";");
-                               Node node = fileNode.addNode(SlcNames.SLC_
-                                               + Constants.EXPORT_PACKAGE,
-                                               SlcTypes.SLC_EXPORTED_PACKAGE);
-                               node.setProperty(SlcNames.SLC_NAME, tokens[0]);
-                               // TODO: are these cleans really necessary?
-                               cleanSubNodes(node, SlcNames.SLC_USES);
-                               cleanSubNodes(node, SlcNames.SLC_VERSION);
-                               for (int i = 1; i < tokens.length; i++) {
-                                       if (tokens[i].startsWith(Constants.VERSION_ATTRIBUTE)) {
-                                               String versionStr = attributeValue(tokens[i]);
-                                               Node versionNode = node.addNode(SlcNames.SLC_VERSION,
-                                                               SlcTypes.SLC_OSGI_VERSION);
-                                               mapOsgiVersion(new Version(versionStr), versionNode);
-                                       } else if (tokens[i].startsWith(Constants.USES_DIRECTIVE)) {
-                                               String usedPackages = directiveValue(tokens[i]);
-                                               // log.debug("uses='" + usedPackages + "'");
-                                               for (String usedPackage : usedPackages.split(",")) {
-                                                       // log.debug("usedPackage='" +
-                                                       // usedPackage +
-                                                       // "'");
-                                                       Node usesNode = node.addNode(SlcNames.SLC_USES,
-                                                                       SlcTypes.SLC_JAVA_PACKAGE);
-                                                       usesNode.setProperty(SlcNames.SLC_NAME, usedPackage);
-                                               }
-                                       }
-                               }
-                       }
-               }
-
-               // required bundle
-               cleanSubNodes(fileNode, SlcNames.SLC_ + Constants.REQUIRE_BUNDLE);
-               if (attrs.containsKey(new Name(Constants.REQUIRE_BUNDLE))) {
-                       String requireBundle = attrs.getValue(Constants.REQUIRE_BUNDLE);
-                       List<String> bundles = parseCommaSeparated(requireBundle);
-                       for (String bundle : bundles) {
-                               String[] tokens = bundle.split(";");
-                               Node node = fileNode.addNode(SlcNames.SLC_
-                                               + Constants.REQUIRE_BUNDLE,
-                                               SlcTypes.SLC_REQUIRED_BUNDLE);
-                               node.setProperty(SlcNames.SLC_SYMBOLIC_NAME, tokens[0]);
-                               for (int i = 1; i < tokens.length; i++) {
-                                       if (tokens[i]
-                                                       .startsWith(Constants.BUNDLE_VERSION_ATTRIBUTE)) {
-                                               node.setProperty(SlcNames.SLC_BUNDLE_VERSION,
-                                                               attributeValue(tokens[i]));
-                                       } else if (tokens[i]
-                                                       .startsWith(Constants.RESOLUTION_DIRECTIVE)) {
-                                               node.setProperty(
-                                                               SlcNames.SLC_OPTIONAL,
-                                                               directiveValue(tokens[i]).equals(
-                                                                               Constants.RESOLUTION_OPTIONAL));
-                                       }
-                               }
-                       }
-               }
-
-       }
-
-       private void addAttr(String key, Node node, Attributes attrs)
-                       throws RepositoryException {
-               addAttr(new Name(key), node, attrs);
-       }
-
-       private void addAttr(Name key, Node node, Attributes attrs)
-                       throws RepositoryException {
-               if (attrs.containsKey(key)) {
-                       String value = attrs.getValue(key);
-                       node.setProperty(SlcNames.SLC_ + key, value);
-               }
-       }
-
-       private void cleanSubNodes(Node node, String name)
-                       throws RepositoryException {
-               if (node.hasNode(name)) {
-                       NodeIterator nit = node.getNodes(name);
-                       while (nit.hasNext())
-                               nit.nextNode().remove();
-               }
-       }
-
-       private String attributeValue(String str) {
-               return extractValue(str, "=");
-       }
-
-       private String directiveValue(String str) {
-               return extractValue(str, ":=");
-       }
-
-       private String extractValue(String str, String eq) {
-               String[] tokens = str.split(eq);
-               // String key = tokens[0];
-               String value = tokens[1].trim();
-               // TODO: optimize?
-               if (value.startsWith("\""))
-                       value = value.substring(1);
-               if (value.endsWith("\""))
-                       value = value.substring(0, value.length() - 1);
-               return value;
-       }
-
-       /** Parse package list with nested directive with ',' */
-       private List<String> parseCommaSeparated(String str) {
-               List<String> res = new ArrayList<String>();
-               StringBuffer curr = new StringBuffer("");
-               boolean in = false;
-               for (char c : str.toCharArray()) {
-                       if (c == ',') {
-                               if (!in) {// new package
-                                       res.add(curr.toString());
-                                       curr = new StringBuffer("");
-                               } else {// a ',' within " "
-                                       curr.append(c);
-                               }
-                       } else if (c == '\"') {
-                               in = !in;
-                               curr.append(c);
-                       } else {
-                               curr.append(c);
-                       }
-               }
-               res.add(curr.toString());
-               // log.debug(res);
-               return res;
-       }
-
-       protected void mapOsgiVersion(Version version, Node versionNode)
-                       throws RepositoryException {
-               versionNode.setProperty(SlcNames.SLC_AS_STRING, version.toString());
-               versionNode.setProperty(SlcNames.SLC_MAJOR, version.getMajor());
-               versionNode.setProperty(SlcNames.SLC_MINOR, version.getMinor());
-               versionNode.setProperty(SlcNames.SLC_MICRO, version.getMicro());
-               if (!version.getQualifier().equals(""))
-                       versionNode.setProperty(SlcNames.SLC_QUALIFIER,
-                                       version.getQualifier());
-       }
-
-       public void setForce(Boolean force) {
-               this.force = force;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JavaRepoManager.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/JavaRepoManager.java
deleted file mode 100644 (file)
index 4d7c3ef..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.argeo.slc.repo;
-
-/** Java-specific operations */
-public interface JavaRepoManager {
-       public void createWorkspace(String workspaceName);
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/MavenProxyService.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/MavenProxyService.java
deleted file mode 100644 (file)
index 8df4a53..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import org.argeo.jcr.proxy.ResourceProxy;
-
-/** Marker interface (useful for OSGi servcies references), maybe extended later */
-public interface MavenProxyService extends ResourceProxy {
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionFactory.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionFactory.java
deleted file mode 100644 (file)
index 79d3b51..0000000
+++ /dev/null
@@ -1,538 +0,0 @@
-package org.argeo.slc.repo;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.osgi.framework.Constants;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Creates a jar bundle from an ArgeoOsgiDistribution. This jar is then
- * persisted and indexed in a java repository using the OSGI Factory.
- * 
- * It does the following <list><li>Creates a Manifest</li><li>Creates files
- * indexes (csv, feature.xml ...)</li><li>Populate the corresponding jar</li><li>
- * Save it in the repository</li><li>Index the node and creates corresponding
- * sha1 and md5 files</li> </list>
- * 
- */
-public class ModularDistributionFactory implements Runnable {
-
-       private OsgiFactory osgiFactory;
-       private Session javaSession;
-       private ArgeoOsgiDistribution osgiDistribution;
-       private String modularDistributionSeparator = ",";
-       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-       private String artifactType = "jar";
-
-       // Constants
-       private final static String CSV_FILE_NAME = "modularDistribution.csv";
-
-       // private final static String FEATURE_FILE_NAME = "feature.xml";
-       // private static int BUFFER_SIZE = 10240;
-
-       /** Convenience constructor with minimal configuration */
-       public ModularDistributionFactory(OsgiFactory osgiFactory,
-                       ArgeoOsgiDistribution osgiDistribution) {
-               this.osgiFactory = osgiFactory;
-               this.osgiDistribution = osgiDistribution;
-       }
-
-       @Override
-       public void run() {
-               byte[] distFile = null;
-               try {
-                       javaSession = osgiFactory.openJavaSession();
-
-                       if (artifactType == "jar")
-                               distFile = generateJarFile();
-                       else if (artifactType == "pom")
-                               distFile = generatePomFile();
-                       else
-                               throw new SlcException(
-                                               "Unimplemented distribution artifact type: "
-                                                               + artifactType + " for "
-                                                               + osgiDistribution.toString());
-
-                       // Save in java repository
-                       Artifact osgiArtifact = new DefaultArtifact(
-                                       osgiDistribution.getCategory(), osgiDistribution.getName(),
-                                       artifactType, osgiDistribution.getVersion());
-
-                       Node distNode = RepoUtils.copyBytesAsArtifact(
-                                       javaSession.getNode(artifactBasePath), osgiArtifact,
-                                       distFile);
-
-                       // index
-                       osgiFactory.indexNode(distNode);
-
-                       // We use a specific session. Save before closing
-                       javaSession.save();
-               } catch (RepositoryException e) {
-                       throw new SlcException(
-                                       "JCR error while persisting modular distribution in JCR "
-                                                       + osgiDistribution.toString(), e);
-               } finally {
-                       JcrUtils.logoutQuietly(javaSession);
-               }
-       }
-
-       private byte[] generateJarFile() {
-               ByteArrayOutputStream byteOut = null;
-               JarOutputStream jarOut = null;
-               try {
-                       byteOut = new ByteArrayOutputStream();
-                       jarOut = new JarOutputStream(byteOut, createManifest());
-                       // Create various indexes
-                       addToJar(createCsvDescriptor(), CSV_FILE_NAME, jarOut);
-                       jarOut.close();
-                       return byteOut.toByteArray();
-               } catch (IOException e) {
-                       throw new SlcException(
-                                       "IO error while generating modular distribution "
-                                                       + osgiDistribution.toString(), e);
-               } finally {
-                       IOUtils.closeQuietly(byteOut);
-                       IOUtils.closeQuietly(jarOut);
-               }
-       }
-
-       // private void indexDistribution(Node distNode) throws RepositoryException
-       // {
-       // distNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
-       // distNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
-       // distNode.setProperty(SlcNames.SLC_CATEGORY,
-       // osgiDistribution.getCategory());
-       // distNode.setProperty(SlcNames.SLC_NAME, osgiDistribution.getName());
-       // distNode.setProperty(SlcNames.SLC_VERSION,
-       // osgiDistribution.getVersion());
-       //
-       // if (distNode.hasNode(SlcNames.SLC_MODULES))
-       // distNode.getNode(SlcNames.SLC_MODULES).remove();
-       // Node modules = distNode.addNode(SlcNames.SLC_MODULES,
-       // NodeType.NT_UNSTRUCTURED);
-       //
-       // for (Iterator<? extends NameVersion> it = osgiDistribution
-       // .nameVersions(); it.hasNext();)
-       // addModule(modules, it.next());
-       // }
-
-       private Manifest createManifest() {
-               Manifest manifest = new Manifest();
-
-               // TODO make this configurable
-               manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
-                               "1.0");
-               addManifestAttribute(manifest,
-                               Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "JavaSE-1.6");
-               addManifestAttribute(manifest, Constants.BUNDLE_VENDOR, "Argeo");
-               addManifestAttribute(manifest, Constants.BUNDLE_MANIFESTVERSION, "2");
-               addManifestAttribute(manifest, "Bundle-License",
-                               "http://www.apache.org/licenses/LICENSE-2.0.txt");
-
-               // TODO define a user friendly name
-               addManifestAttribute(manifest, Constants.BUNDLE_NAME,
-                               osgiDistribution.getName());
-
-               // Categorized name version
-               addManifestAttribute(manifest, RepoConstants.SLC_GROUP_ID,
-                               osgiDistribution.getCategory());
-               addManifestAttribute(manifest, Constants.BUNDLE_SYMBOLICNAME,
-                               osgiDistribution.getName());
-               addManifestAttribute(manifest, Constants.BUNDLE_VERSION,
-                               osgiDistribution.getVersion());
-
-               return manifest;
-       }
-
-       private void addManifestAttribute(Manifest manifest, String name,
-                       String value) {
-               manifest.getMainAttributes().put(new Attributes.Name(name), value);
-       }
-
-       private byte[] createCsvDescriptor() {
-               Writer writer = null;
-               try {
-                       // FIXME remove use of tmp file.
-                       File tmpFile = File.createTempFile("modularDistribution", "csv");
-                       tmpFile.deleteOnExit();
-                       writer = new FileWriter(tmpFile);
-                       // Populate the file
-                       for (Iterator<? extends NameVersion> it = osgiDistribution
-                                       .nameVersions(); it.hasNext();)
-                               writer.write(getCsvLine(it.next()));
-                       writer.flush();
-                       return FileUtils.readFileToByteArray(tmpFile);
-               } catch (Exception e) {
-                       throw new SlcException(
-                                       "unable to create csv distribution file for "
-                                                       + osgiDistribution.toString(), e);
-               } finally {
-                       IOUtils.closeQuietly(writer);
-               }
-       }
-
-       @SuppressWarnings("unused")
-       private byte[] createFeatureDescriptor() {
-               // Directly retrieved from Argeo maven plugin
-               // Does not work due to the lack of org.codehaus.plexus/plexus-archiver
-               // third party dependency
-
-               throw new SlcException("Unimplemented method");
-
-               // // protected void writeFeatureDescriptor() throws
-               // MojoExecutionException {
-               // File featureDesc = File.createTempFile("feature", "xml");
-               // featureDesc.deleteOnExit();
-               //
-               // Writer writer = null;
-               // try {
-               // writer = new FileWriter(featureDesc);
-               // PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
-               // xmlWriter.startElement("feature");
-               // xmlWriter.addAttribute("id", project.getArtifactId());
-               // xmlWriter.addAttribute("label", project.getName());
-               //
-               // // Version
-               // String projectVersion = project.getVersion();
-               // int indexSnapshot = projectVersion.indexOf("-SNAPSHOT");
-               // if (indexSnapshot > -1)
-               // projectVersion = projectVersion.substring(0, indexSnapshot);
-               // projectVersion = projectVersion + ".qualifier";
-               //
-               // // project.
-               // xmlWriter.addAttribute("version", projectVersion);
-               //
-               // Organization organization = project.getOrganization();
-               // if (organization != null && organization.getName() != null)
-               // xmlWriter.addAttribute("provider-name", organization.getName());
-               //
-               // if (project.getDescription() != null || project.getUrl() != null) {
-               // xmlWriter.startElement("description");
-               // if (project.getUrl() != null)
-               // xmlWriter.addAttribute("url", project.getUrl());
-               // if (project.getDescription() != null)
-               // xmlWriter.writeText(project.getDescription());
-               // xmlWriter.endElement();// description
-               // }
-               //
-               // if (feature != null && feature.getCopyright() != null
-               // || (organization != null && organization.getUrl() != null)) {
-               // xmlWriter.startElement("copyright");
-               // if (organization != null && organization.getUrl() != null)
-               // xmlWriter.addAttribute("url", organization.getUrl());
-               // if (feature.getCopyright() != null)
-               // xmlWriter.writeText(feature.getCopyright());
-               // xmlWriter.endElement();// copyright
-               // }
-               //
-               // if (feature != null && feature.getUpdateSite() != null) {
-               // xmlWriter.startElement("url");
-               // xmlWriter.startElement("update");
-               // xmlWriter.addAttribute("url", feature.getUpdateSite());
-               // xmlWriter.endElement();// update
-               // xmlWriter.endElement();// url
-               // }
-               //
-               // List licenses = project.getLicenses();
-               // if (licenses.size() > 0) {
-               // // take the first one
-               // License license = (License) licenses.get(0);
-               // xmlWriter.startElement("license");
-               //
-               // if (license.getUrl() != null)
-               // xmlWriter.addAttribute("url", license.getUrl());
-               // if (license.getComments() != null)
-               // xmlWriter.writeText(license.getComments());
-               // else if (license.getName() != null)
-               // xmlWriter.writeText(license.getName());
-               // xmlWriter.endElement();// license
-               // }
-               //
-               // // deploymentRepository.pathOf(null);
-               // if (jarDirectory == null) {
-               // Set dependencies = mavenDependencyManager
-               // .getTransitiveProjectDependencies(project, remoteRepos,
-               // local);
-               // // // protected void writeFeatureDescriptor() throws
-               // MojoExecutionException {
-               // File featureDesc = File.createTempFile("feature", "xml");
-               // featureDesc.deleteOnExit();
-               //
-               // Writer writer = null;
-               // try {
-               // writer = new FileWriter(featureDesc);
-               // PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
-               // xmlWriter.startElement("feature");
-               // xmlWriter.addAttribute("id", project.getArtifactId());
-               // xmlWriter.addAttribute("label", project.getName());
-               //
-               // // Version
-               // String projectVersion = project.getVersion();
-               // int indexSnapshot = projectVersion.indexOf("-SNAPSHOT");
-               // if (indexSnapshot > -1)
-               // projectVersion = projectVersion.substring(0, indexSnapshot);
-               // projectVersion = projectVersion + ".qualifier";
-               //
-               // // project.
-               // xmlWriter.addAttribute("version", projectVersion);
-               //
-               // Organization organization = project.getOrganization();
-               // if (organization != null && organization.getName() != null)
-               // xmlWriter.addAttribute("provider-name", organization.getName());
-               //
-               // if (project.getDescription() != null || project.getUrl() != null) {
-               // xmlWriter.startElement("description");
-               // if (project.getUrl() != null)
-               // xmlWriter.addAttribute("url", project.getUrl());
-               // if (project.getDescription() != null)
-               // xmlWriter.writeText(project.getDescription());
-               // xmlWriter.endElement();// description
-               // }
-               //
-               // if (feature != null && feature.getCopyright() != null
-               // || (organization != null && organization.getUrl() != null)) {
-               // xmlWriter.startElement("copyright");
-               // if (organization != null && organization.getUrl() != null)
-               // xmlWriter.addAttribute("url", organization.getUrl());
-               // if (feature.getCopyright() != null)
-               // xmlWriter.writeText(feature.getCopyright());
-               // xmlWriter.endElement();// copyright
-               // }
-               //
-               // if (feature != null && feature.getUpdateSite() != null) {
-               // xmlWriter.startElement("url");
-               // xmlWriter.startElement("update");
-               // xmlWriter.addAttribute("url", feature.getUpdateSite());
-               // xmlWriter.endElement();// update
-               // xmlWriter.endElement();// url
-               // }
-               //
-               // List licenses = project.getLicenses();
-               // if (licenses.size() > 0) {
-               // // take the first one
-               // License license = (License) licenses.get(0);
-               // xmlWriter.startElement("license");
-               //
-               // if (license.getUrl() != null)
-               // xmlWriter.addAttribute("url", license.getUrl());
-               // if (license.getComments() != null)
-               // xmlWriter.writeText(license.getComments());
-               // else if (license.getName() != null)
-               // xmlWriter.writeText(license.getName());
-               // xmlWriter.endElement();// license
-               // }
-               //
-               // // deploymentRepository.pathOf(null);
-               // if (jarDirectory == null) {
-               // Set dependencies = mavenDependencyManager
-               // .getTransitiveProjectDependencies(project, remoteRepos,
-               // local);
-               // for (Iterator it = dependencies.iterator(); it.hasNext();) {
-               // Artifact artifact = (Artifact) it.next();
-               // writeFeaturePlugin(xmlWriter, artifact.getFile());
-               // }
-               // } else {
-               // // TODO: filter jars
-               // File[] jars = jarDirectory.listFiles();
-               // if (jars == null)
-               // throw new MojoExecutionException("No jar found in "
-               // + jarDirectory);
-               // for (int i = 0; i < jars.length; i++) {
-               // writeFeaturePlugin(xmlWriter, jars[i]);
-               // }
-               // }
-               //
-               // xmlWriter.endElement();// feature
-               //
-               // if (getLog().isDebugEnabled())
-               // getLog().debug("Wrote Eclipse feature descriptor.");
-               // } catch (Exception e) {
-               // throw new MojoExecutionException("Cannot write feature descriptor",
-               // e);
-               // } finally {
-               // IOUtil.close(writer);
-               // }for (Iterator it = dependencies.iterator(); it.hasNext();) {
-               // Artifact artifact = (Artifact) it.next();
-               // writeFeaturePlugin(xmlWriter, artifact.getFile());
-               // }
-               // } else {
-               // // TODO: filter jars
-               // File[] jars = jarDirectory.listFiles();
-               // if (jars == null)
-               // throw new MojoExecutionException("No jar found in "
-               // + jarDirectory);
-               // for (int i = 0; i < jars.length; i++) {
-               // writeFeaturePlugin(xmlWriter, jars[i]);
-               // }
-               // }
-               //
-               // xmlWriter.endElement();// feature
-               //
-               // if (getLog().isDebugEnabled())
-               // getLog().debug("Wrote Eclipse feature descriptor.");
-               // } catch (Exception e) {
-               // throw new MojoExecutionException("Cannot write feature descriptor",
-               // e);
-               // } finally {
-               // IOUtil.close(writer);
-               // }
-       }
-
-       /** Create an Aether like distribution artifact */
-       private byte[] generatePomFile() {
-               StringBuilder b = new StringBuilder();
-               // XML header
-               b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-               b.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
-               b.append("<modelVersion>4.0.0</modelVersion>");
-
-               // Artifact
-               b.append("<groupId>").append(osgiDistribution.getCategory())
-                               .append("</groupId>\n");
-               b.append("<artifactId>").append(osgiDistribution.getName())
-                               .append("</artifactId>\n");
-               b.append("<version>").append(osgiDistribution.getVersion())
-                               .append("</version>\n");
-               b.append("<packaging>pom</packaging>\n");
-               // p.append("<name>").append("Bundle Name").append("</name>\n");
-               // p.append("<description>").append("Bundle Description").append("</description>\n");
-
-               // Dependencies
-               b.append("<dependencies>\n");
-               for (Iterator<? extends NameVersion> it = osgiDistribution
-                               .nameVersions(); it.hasNext();) {
-                       NameVersion nameVersion = it.next();
-                       if (!(nameVersion instanceof CategorizedNameVersion))
-                               throw new SlcException("Unsupported type "
-                                               + nameVersion.getClass());
-                       CategorizedNameVersion nv = (CategorizedNameVersion) nameVersion;
-                       b.append(getDependencySnippet(nv, false));
-               }
-               b.append("</dependencies>\n");
-
-               // Dependency management
-               b.append("<dependencyManagement>\n");
-               b.append("<dependencies>\n");
-
-               for (Iterator<? extends NameVersion> it = osgiDistribution
-                               .nameVersions(); it.hasNext();)
-                       b.append(getDependencySnippet((CategorizedNameVersion) it.next(),
-                                       true));
-               b.append("</dependencies>\n");
-               b.append("</dependencyManagement>\n");
-
-               b.append("</project>\n");
-               return b.toString().getBytes();
-       }
-
-       private String getDependencySnippet(CategorizedNameVersion cnv,
-                       boolean includeVersion) { // , String type, String scope
-               StringBuilder b = new StringBuilder();
-               b.append("<dependency>\n");
-               b.append("\t<groupId>").append(cnv.getCategory())
-                               .append("</groupId>\n");
-               b.append("\t<artifactId>").append(cnv.getName())
-                               .append("</artifactId>\n");
-               if (includeVersion)
-                       b.append("\t<version>").append(cnv.getVersion())
-                                       .append("</version>\n");
-               // if (type!= null)
-               // p.append("\t<type>").append(type).append("</type>\n");
-               // if (type!= null)
-               // p.append("\t<scope>").append(scope).append("</scope>\n");
-               b.append("</dependency>\n");
-               return b.toString();
-       }
-
-       // Helpers
-       private void addToJar(byte[] content, String name, JarOutputStream target)
-                       throws IOException {
-               ByteArrayInputStream in = null;
-               try {
-                       target.putNextEntry(new JarEntry(name));
-                       in = new ByteArrayInputStream(content);
-                       byte[] buffer = new byte[1024];
-                       while (true) {
-                               int count = in.read(buffer);
-                               if (count == -1)
-                                       break;
-                               target.write(buffer, 0, count);
-                       }
-                       target.closeEntry();
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       private String getCsvLine(NameVersion nameVersion)
-                       throws RepositoryException {
-               if (!(nameVersion instanceof CategorizedNameVersion))
-                       throw new SlcException("Unsupported type " + nameVersion.getClass());
-               CategorizedNameVersion cnv = (CategorizedNameVersion) nameVersion;
-               StringBuilder builder = new StringBuilder();
-
-               builder.append(cnv.getName());
-               builder.append(modularDistributionSeparator);
-               builder.append(nameVersion.getVersion());
-               builder.append(modularDistributionSeparator);
-               builder.append(cnv.getCategory().replace('.', '/'));
-               // MavenConventionsUtils.groupPath("", cnv.getCategory());
-               builder.append('/');
-               builder.append(cnv.getName());
-               builder.append('/');
-               builder.append(cnv.getVersion());
-               builder.append('/');
-               builder.append(cnv.getName());
-               builder.append('-');
-               builder.append(cnv.getVersion());
-               builder.append('.');
-               // TODO make this dynamic
-               builder.append("jar");
-               builder.append("\n");
-
-               return builder.toString();
-       }
-
-       /** Enable dependency injection */
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-
-       public void setOsgiDistribution(ArgeoOsgiDistribution osgiDistribution) {
-               this.osgiDistribution = osgiDistribution;
-       }
-
-       public void setModularDistributionSeparator(
-                       String modularDistributionSeparator) {
-               this.modularDistributionSeparator = modularDistributionSeparator;
-       }
-
-       public void setArtifactBasePath(String artifactBasePath) {
-               this.artifactBasePath = artifactBasePath;
-       }
-
-       public void setArtifactType(String artifactType) {
-               this.artifactType = artifactType;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/ModularDistributionIndexer.java
deleted file mode 100644 (file)
index bca0496..0000000
+++ /dev/null
@@ -1,322 +0,0 @@
-package org.argeo.slc.repo;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.StringTokenizer;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import java.util.jar.Manifest;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherUtils;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.osgi.framework.Constants;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Create or update JCR meta-data for an SLC Modular Distribution
- * 
- * Currently, following types are managed: <list><li>* .jar: dependency
- * artifacts with csv index</li> <li>@Deprecated : .pom: artifact (binaries)
- * that indexes a group, the .pom file contains a tag "dependencyManagement"
- * that list all modules</li> </list>
- */
-public class ModularDistributionIndexer implements NodeIndexer, SlcNames {
-       private final static Log log = LogFactory
-                       .getLog(ModularDistributionIndexer.class);
-
-       // Constants for csv indexing
-       private final static String INDEX_FILE_NAME = "modularDistribution.csv";
-       private String separator = ",";
-
-       // TODO remove this: binaries have been replaced by modular distribution
-       // // Artifact indexing
-       // private final static List<String> BINARIES_ARTIFACTS_NAME;
-       // static {
-       // List<String> tmpList = new ArrayList<String>();
-       // tmpList.add(RepoConstants.BINARIES_ARTIFACT_ID);
-       // // tmpList.add(RepoConstants.SOURCES_ARTIFACT_ID);
-       // // tmpList.add(RepoConstants.SDK_ARTIFACT_ID);
-       // BINARIES_ARTIFACTS_NAME = Collections.unmodifiableList(tmpList);
-       // }
-
-       private Manifest manifest;
-
-       public Boolean support(String path) {
-               if (FilenameUtils.getExtension(path).equals("jar"))
-                       return true;
-               // if (FilenameUtils.getExtension(path).equals("pom")
-               // && BINARIES_ARTIFACTS_NAME.contains(FilenameUtils.getName(path)
-               // .split("-")[0]))
-               // return true;
-               return false;
-       }
-
-       public void index(Node fileNode) {
-               Binary fileBinary = null;
-               try {
-
-                       String fileNodePath = fileNode.getPath();
-                       if (!support(fileNodePath))
-                               return;
-
-                       if (!fileNode.isNodeType(NodeType.NT_FILE))
-                               return;
-
-                       Node contentNode = fileNode.getNode(Node.JCR_CONTENT);
-                       fileBinary = contentNode.getProperty(Property.JCR_DATA).getBinary();
-
-                       MyModularDistribution currDist = null;
-                       if (FilenameUtils.getExtension(fileNode.getPath()).equals("jar"))
-                               currDist = listModulesFromCsvIndex(fileNode, fileBinary);
-                       // else if (FilenameUtils.getExtension(fileNode.getPath()).equals(
-                       // "pom"))
-                       // currDist = listModulesFromPomIndex(fileNode, fileBinary);
-
-                       if (fileNode.isNodeType(SlcTypes.SLC_MODULAR_DISTRIBUTION)
-                                       || currDist == null || !currDist.nameVersions().hasNext())
-                               return; // already indexed or no modules found
-                       else {
-                               fileNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
-                               fileNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
-                               if (currDist.getCategory() != null)
-                                       fileNode.setProperty(SLC_CATEGORY, currDist.getCategory());
-                               fileNode.setProperty(SLC_NAME, currDist.getName());
-                               fileNode.setProperty(SLC_VERSION, currDist.getVersion());
-                               indexDistribution(currDist, fileNode);
-                       }
-
-                       if (log.isTraceEnabled())
-                               log.trace("Indexed " + fileNode + " as modular distribution");
-               } catch (Exception e) {
-                       throw new SlcException("Cannot list dependencies from " + fileNode,
-                                       e);
-               }
-       }
-
-       private void indexDistribution(ArgeoOsgiDistribution osgiDist, Node distNode)
-                       throws RepositoryException {
-               distNode.addMixin(SlcTypes.SLC_MODULAR_DISTRIBUTION);
-               distNode.addMixin(SlcTypes.SLC_CATEGORIZED_NAME_VERSION);
-               distNode.setProperty(SlcNames.SLC_CATEGORY, osgiDist.getCategory());
-               distNode.setProperty(SlcNames.SLC_NAME, osgiDist.getName());
-               distNode.setProperty(SlcNames.SLC_VERSION, osgiDist.getVersion());
-               if (distNode.hasNode(SLC_MODULES))
-                       distNode.getNode(SLC_MODULES).remove();
-               Node modules = distNode.addNode(SLC_MODULES, NodeType.NT_UNSTRUCTURED);
-
-               for (Iterator<? extends NameVersion> it = osgiDist.nameVersions(); it
-                               .hasNext();)
-                       addModule(modules, it.next());
-       }
-
-       // Helpers
-       private Node addModule(Node modules, NameVersion nameVersion)
-                       throws RepositoryException {
-               CategorizedNameVersion cnv = (CategorizedNameVersion) nameVersion;
-               Node moduleCoord = null;
-               moduleCoord = modules.addNode(cnv.getName(),
-                               SlcTypes.SLC_MODULE_COORDINATES);
-               moduleCoord.setProperty(SlcNames.SLC_CATEGORY, cnv.getCategory());
-               moduleCoord.setProperty(SlcNames.SLC_NAME, cnv.getName());
-               moduleCoord.setProperty(SlcNames.SLC_VERSION, cnv.getVersion());
-               return moduleCoord;
-       }
-
-       private MyModularDistribution listModulesFromCsvIndex(Node fileNode,
-                       Binary fileBinary) {
-               JarInputStream jarIn = null;
-               BufferedReader reader = null;
-               try {
-                       jarIn = new JarInputStream(fileBinary.getStream());
-
-                       List<CategorizedNameVersion> modules = new ArrayList<CategorizedNameVersion>();
-
-                       // meta data
-                       manifest = jarIn.getManifest();
-                       if (manifest == null) {
-                               log.error(fileNode + " has no MANIFEST");
-                               return null;
-                       }
-                       String category = manifest.getMainAttributes().getValue(
-                                       RepoConstants.SLC_GROUP_ID);
-                       String name = manifest.getMainAttributes().getValue(
-                                       Constants.BUNDLE_SYMBOLICNAME);
-                       String version = manifest.getMainAttributes().getValue(
-                                       Constants.BUNDLE_VERSION);
-
-                       Artifact distribution = new DefaultArtifact(category, name, "jar",
-                                       version);
-                       // Retrieve the index file
-                       JarEntry indexEntry;
-                       while ((indexEntry = jarIn.getNextJarEntry()) != null) {
-                               String entryName = indexEntry.getName();
-                               if (entryName.equals(INDEX_FILE_NAME)) {
-                                       break;
-                               }
-                               try {
-                                       jarIn.closeEntry();
-                               } catch (SecurityException se) {
-                                       log.error("Invalid signature file digest "
-                                                       + "for Manifest main attributes: " + entryName
-                                                       + " while looking for an index in bundle " + name);
-                               }
-                       }
-                       if (indexEntry == null)
-                               return null; // Not a modular definition
-
-                       // Process the index
-                       reader = new BufferedReader(new InputStreamReader(jarIn));
-                       String line = null;
-                       while ((line = reader.readLine()) != null) {
-                               StringTokenizer st = new StringTokenizer(line, separator);
-                               st.nextToken(); // moduleName
-                               st.nextToken(); // moduleVersion
-                               String relativeUrl = st.nextToken();
-                               Artifact currModule = AetherUtils.convertPathToArtifact(
-                                               relativeUrl, null);
-                               modules.add(new MyCategorizedNameVersion(currModule
-                                               .getGroupId(), currModule.getArtifactId(), currModule
-                                               .getVersion()));
-                       }
-                       return new MyModularDistribution(distribution, modules);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot list artifacts", e);
-               } finally {
-                       IOUtils.closeQuietly(jarIn);
-                       IOUtils.closeQuietly(reader);
-               }
-       }
-
-       // private MyModularDistribution listModulesFromPomIndex(Node fileNode,
-       // Binary fileBinary) {
-       // InputStream input = null;
-       // List<CategorizedNameVersion> modules = new
-       // ArrayList<CategorizedNameVersion>();
-       // try {
-       // input = fileBinary.getStream();
-       //
-       // DocumentBuilder documentBuilder = DocumentBuilderFactory
-       // .newInstance().newDocumentBuilder();
-       // Document doc = documentBuilder.parse(input);
-       // // properties
-       // Properties props = new Properties();
-       // // props.setProperty("project.version",
-       // // pomArtifact.getBaseVersion());
-       // NodeList properties = doc.getElementsByTagName("properties");
-       // if (properties.getLength() > 0) {
-       // NodeList propertiesElems = properties.item(0).getChildNodes();
-       // for (int i = 0; i < propertiesElems.getLength(); i++) {
-       // if (propertiesElems.item(i) instanceof Element) {
-       // Element property = (Element) propertiesElems.item(i);
-       // props.put(property.getNodeName(),
-       // property.getTextContent());
-       // }
-       // }
-       // }
-       //
-       // // full coordinates are under <dependencyManagement><dependencies>
-       // NodeList dependencies = ((Element) doc.getElementsByTagName(
-       // "dependencyManagement").item(0))
-       // .getElementsByTagName("dependency");
-       // for (int i = 0; i < dependencies.getLength(); i++) {
-       // Element dependency = (Element) dependencies.item(i);
-       // String groupId = dependency.getElementsByTagName("groupId")
-       // .item(0).getTextContent().trim();
-       // String artifactId = dependency
-       // .getElementsByTagName("artifactId").item(0)
-       // .getTextContent().trim();
-       // String version = dependency.getElementsByTagName("version")
-       // .item(0).getTextContent().trim();
-       // modules.add(new MyCategorizedNameVersion(groupId, artifactId,
-       // version));
-       // }
-       //
-       // String groupId = doc.getElementsByTagName("groupId").item(0)
-       // .getTextContent().trim();
-       // String artifactId = doc.getElementsByTagName("artifactId").item(0)
-       // .getTextContent().trim();
-       // String version = doc.getElementsByTagName("version").item(0)
-       // .getTextContent().trim();
-       //
-       // Artifact currDist = new DefaultArtifact(groupId, artifactId, "pom",
-       // version);
-       //
-       // return new MyModularDistribution(currDist, modules);
-       // } catch (Exception e) {
-       // throw new SlcException("Cannot process pom " + fileNode, e);
-       // } finally {
-       // IOUtils.closeQuietly(input);
-       // }
-       // }
-
-       /** The created modular distribution */
-       private static class MyCategorizedNameVersion extends DefaultNameVersion
-                       implements CategorizedNameVersion {
-               private final String category;
-
-               public MyCategorizedNameVersion(String category, String name,
-                               String version) {
-                       super(name, version);
-                       this.category = category;
-               }
-
-               public String getCategory() {
-                       return category;
-               }
-       }
-
-       /**
-        * A consistent and versioned OSGi distribution, which can be built and
-        * tested.
-        */
-       private class MyModularDistribution extends ArtifactDistribution implements
-                       ArgeoOsgiDistribution {
-
-               private List<CategorizedNameVersion> modules;
-
-               public MyModularDistribution(Artifact artifact,
-                               List<CategorizedNameVersion> modules) {
-                       super(artifact);
-                       this.modules = modules;
-               }
-
-               public Iterator<CategorizedNameVersion> nameVersions() {
-                       return modules.iterator();
-               }
-
-               // Modular distribution interface methods. Not yet used.
-               public Distribution getModuleDistribution(String moduleName,
-                               String moduleVersion) {
-                       return null;
-               }
-
-               public Object getModulesDescriptor(String descriptorType) {
-                       return null;
-               }
-       }
-
-       /** Separator used to parse the tabular file, default is "," */
-       public void setSeparator(String modulesUrlSeparator) {
-               this.separator = modulesUrlSeparator;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexer.java
deleted file mode 100644 (file)
index 77798ab..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import javax.jcr.Node;
-import javax.jcr.observation.EventListener;
-
-/**
- * Adds metadata to an existing node, ideally via observation after it has been
- * added. There is a similar concept in ModeShape with which this abstraction
- * may be merged in the future.
- */
-public interface NodeIndexer {
-       /**
-        * Whether the node at this path will be supported. This is typically use in
-        * an {@link EventListener} before the node is loaded, and would apply on
-        * information contained in the path / file name: file extension, base path,
-        * etc. If the node needs to be loaded, the recommended approach is to
-        * return <code>true</code> here and wait for index to be called, possibly
-        * returning without processing if the node should not be indexed. While
-        * not strictly a requirement, this avoids to open sessions in the indexer,
-        * centralizing such tasks in the caller.
-        */
-       public Boolean support(String path);
-
-       /**
-        * Adds the metadata. This is the responsibility of the caller to save the
-        * underlying session.
-        */
-       public void index(Node node);
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexerVisitor.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/NodeIndexerVisitor.java
deleted file mode 100644 (file)
index c0f90d1..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.argeo.slc.repo;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.ItemVisitor;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-
-/**
- * Recursively visit a sub tree and apply the list of node indexer on supported
- * nodes.
- */
-public class NodeIndexerVisitor implements ItemVisitor {
-       /** order may be important */
-       private List<NodeIndexer> nodeIndexers = new ArrayList<NodeIndexer>();
-
-       public NodeIndexerVisitor() {
-       }
-
-       /** Convenience constructor */
-       public NodeIndexerVisitor(NodeIndexer nodeIndexer) {
-               nodeIndexers.add(nodeIndexer);
-       }
-
-       public NodeIndexerVisitor(List<NodeIndexer> nodeIndexers) {
-               this.nodeIndexers = nodeIndexers;
-       }
-
-       public void visit(Node node) throws RepositoryException {
-               for (NodeIndexer nodeIndexer : nodeIndexers)
-                       if (nodeIndexer.support(node.getPath()))
-                               nodeIndexer.index(node);
-
-               for (NodeIterator it = node.getNodes(); it.hasNext();)
-                       visit(it.nextNode());
-       }
-
-       public void visit(Property property) throws RepositoryException {
-       }
-
-       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
-               this.nodeIndexers = nodeIndexers;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiBundlesProvider.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiBundlesProvider.java
deleted file mode 100644 (file)
index de5f03c..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.argeo.slc.repo;
-
-import java.util.List;
-
-/**
- * Provides OSGi bundles either by linking to them, by wrapping existing
- * archives or by building them.
- */
-public interface OsgiBundlesProvider {
-       /** The provided bundles in the order they will be retrieved/wrapped/built. */
-       public List<ArtifactDistribution> provides();
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiFactory.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/OsgiFactory.java
deleted file mode 100644 (file)
index 8178493..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.argeo.slc.repo;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-/** OSGi Factory */
-public interface OsgiFactory {
-       public Session openJavaSession() throws RepositoryException;
-
-       public Session openDistSession() throws RepositoryException;
-
-       public void indexNode(Node node);
-
-       /**
-        * Provide access to a third party archive in the 'dist' repository,
-        * downloading it if it is not available.
-        */
-       public Node getDist(Session distSession, String uri)
-                       throws RepositoryException;
-
-       /**
-        * Provide access to a cached maven ardifact identified by its coordinates
-        * the 'dist' repository, downloading it if it is not available.
-        */
-       public Node getMaven(Session distSession, String coords)
-                       throws RepositoryException;
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/PdeSourcesIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/PdeSourcesIndexer.java
deleted file mode 100644 (file)
index 97ca286..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Creates pde sources from a source {@link Artifact} with name
- * "...-sources.jar"
- */
-public class PdeSourcesIndexer implements NodeIndexer {
-       private Log log = LogFactory.getLog(PdeSourcesIndexer.class);
-
-       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-
-       // private ArtifactIndexer artifactIndexer;
-       // private JarFileIndexer jarFileIndexer;
-
-       // public PdeSourcesIndexer(){
-       // // ArtifactIndexer artifactIndexer,
-       // // JarFileIndexer jarFileIndexer) {
-       // // this.artifactIndexer = artifactIndexer;
-       // // this.jarFileIndexer = jarFileIndexer;
-       // }
-
-       public Boolean support(String path) {
-               // TODO implement clean management of same name siblings
-               String name = FilenameUtils.getBaseName(path);
-               // int lastInd = name.lastIndexOf("[");
-               // if (lastInd != -1)
-               // name = name.substring(0, lastInd);
-               return name.endsWith("-sources")
-                               && FilenameUtils.getExtension(path).equals("jar");
-       }
-
-       public void index(Node sourcesNode) {
-               try {
-                       if (!support(sourcesNode.getPath()))
-                               return;
-
-                       packageSourcesAsPdeSource(sourcesNode);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot generate pde sources for node "
-                                       + sourcesNode, e);
-               }
-       }
-
-       protected void packageSourcesAsPdeSource(Node sourcesNode) {
-               Binary origBinary = null;
-               Binary osgiBinary = null;
-               try {
-                       Session session = sourcesNode.getSession();
-                       Artifact sourcesArtifact = AetherUtils.convertPathToArtifact(
-                                       sourcesNode.getPath(), null);
-
-                       // read name version from manifest
-                       Artifact osgiArtifact = new DefaultArtifact(
-                                       sourcesArtifact.getGroupId(),
-                                       sourcesArtifact.getArtifactId(),
-                                       sourcesArtifact.getExtension(),
-                                       sourcesArtifact.getVersion());
-                       String osgiPath = MavenConventionsUtils.artifactPath(
-                                       artifactBasePath, osgiArtifact);
-                       osgiBinary = session.getNode(osgiPath).getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary();
-
-                       NameVersion nameVersion = RepoUtils.readNameVersion(osgiBinary
-                                       .getStream());
-
-                       // create PDe sources artifact
-                       Artifact pdeSourceArtifact = new DefaultArtifact(
-                                       sourcesArtifact.getGroupId(),
-                                       sourcesArtifact.getArtifactId() + ".source",
-                                       sourcesArtifact.getExtension(),
-                                       sourcesArtifact.getVersion());
-                       String targetSourceParentPath = MavenConventionsUtils
-                                       .artifactParentPath(artifactBasePath, pdeSourceArtifact);
-                       String targetSourceFileName = MavenConventionsUtils
-                                       .artifactFileName(pdeSourceArtifact);
-                       // String targetSourceJarPath = targetSourceParentPath + '/'
-                       // + targetSourceFileName;
-
-                       Node targetSourceParentNode = JcrUtils.mkfolders(session,
-                                       targetSourceParentPath);
-                       origBinary = sourcesNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary();
-                       byte[] targetJarBytes = RepoUtils.packageAsPdeSource(
-                                       origBinary.getStream(), nameVersion);
-                       JcrUtils.copyBytesAsFile(targetSourceParentNode,
-                                       targetSourceFileName, targetJarBytes);
-
-                       // reindex
-                       // Automagically done via the various listeners or manually
-                       // triggered.
-                       // Node targetSourceJarNode = session.getNode(targetSourceJarPath);
-                       // artifactIndexer.index(targetSourceJarNode);
-                       // jarFileIndexer.index(targetSourceJarNode);
-                       if (log.isTraceEnabled())
-                               log.trace("Created pde source artifact " + pdeSourceArtifact
-                                               + " from " + sourcesNode);
-
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot add PDE sources for " + sourcesNode,
-                                       e);
-               } finally {
-                       JcrUtils.closeQuietly(origBinary);
-                       JcrUtils.closeQuietly(osgiBinary);
-               }
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoConstants.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoConstants.java
deleted file mode 100644 (file)
index 4358e98..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-/** SLC repository constants */
-public interface RepoConstants {
-       public final static String DEFAULT_JAVA_REPOSITORY_ALIAS = "java";
-       public final static String DEFAULT_JAVA_REPOSITORY_LABEL = "Internal Java Repository";
-
-       public final static String DEFAULT_ARTIFACTS_BASE_PATH = "/";
-       public final static String REPO_BASEPATH = "/slc:repo";
-       public final static String PROXIED_REPOSITORIES = REPO_BASEPATH
-                       + "/slc:sources";
-       public final static String DISTRIBUTIONS_BASE_PATH = REPO_BASEPATH
-                       + "/slc:distributions";
-       public final static String REPOSITORIES_BASE_PATH = REPO_BASEPATH
-                       + "/slc:repositories";
-       public final static String BINARIES_ARTIFACT_ID = "binaries";
-       public final static String SOURCES_ARTIFACT_ID = "sources";
-       public final static String SDK_ARTIFACT_ID = "sdk";
-       
-       // TODO might exists somewhere else
-       public final static String SLC_GROUP_ID = "SLC-GroupId";
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoService.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoService.java
deleted file mode 100644 (file)
index 9b9bc66..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.argeo.slc.repo;
-
-import javax.jcr.Session;
-
-/** Start factorisation of the session management using a manager service */
-public interface RepoService {
-
-       /**
-        * Returns a corresponding session given the current context. Caller must
-        * close the session once it has been used
-        */
-       public Session getRemoteSession(String repoNodePath, String uri,
-                       String workspaceName);
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoSync.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoSync.java
deleted file mode 100644 (file)
index 7f1e1e3..0000000
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import java.io.InputStream;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-
-import javax.jcr.Binary;
-import javax.jcr.Credentials;
-import javax.jcr.NoSuchWorkspaceException;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryResult;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.xml.sax.SAXException;
-
-/**
- * Synchronise workspaces from a remote software repository to the local
- * repository (Synchronisation in the other direction does not work).
- * 
- * Workspaces are retrieved by name given a map that links the source with a
- * target name. If a target workspace does not exist, it is created. Otherwise
- * we copy the content of the source workspace into the target one.
- */
-public class RepoSync implements Runnable {
-       private final static Log log = LogFactory.getLog(RepoSync.class);
-
-       // Centralizes definition of workspaces that must be ignored by the sync.
-       private final static List<String> IGNORED_WKSP_LIST = Arrays.asList(
-                       "security", "localrepo");
-
-       private final Calendar zero;
-       private Session sourceDefaultSession = null;
-       private Session targetDefaultSession = null;
-
-       private Repository sourceRepository;
-       private Credentials sourceCredentials;
-       private Repository targetRepository;
-       private Credentials targetCredentials;
-
-       // if Repository and Credentials objects are not explicitly set
-       private String sourceRepoUri;
-       private String sourceUsername;
-       private char[] sourcePassword;
-       private String targetRepoUri;
-       private String targetUsername;
-       private char[] targetPassword;
-
-       private RepositoryFactory repositoryFactory;
-
-       private ArgeoMonitor monitor;
-       private Map<String, String> workspaceMap;
-
-       // TODO fix monitor
-       private Boolean filesOnly = false;
-
-       public RepoSync() {
-               zero = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
-               zero.setTimeInMillis(0);
-       }
-
-       /**
-        * 
-        * Shortcut to instantiate a RepoSync with already known repositories and
-        * credentials.
-        * 
-        * @param sourceRepository
-        * @param sourceCredentials
-        * @param targetRepository
-        * @param targetCredentials
-        */
-       public RepoSync(Repository sourceRepository, Credentials sourceCredentials,
-                       Repository targetRepository, Credentials targetCredentials) {
-               this();
-               this.sourceRepository = sourceRepository;
-               this.sourceCredentials = sourceCredentials;
-               this.targetRepository = targetRepository;
-               this.targetCredentials = targetCredentials;
-       }
-
-       public void run() {
-               try {
-                       long begin = System.currentTimeMillis();
-
-                       // Setup
-                       if (sourceRepository == null)
-                               sourceRepository = ArgeoJcrUtils.getRepositoryByUri(
-                                               repositoryFactory, sourceRepoUri);
-                       if (sourceCredentials == null && sourceUsername != null)
-                               sourceCredentials = new SimpleCredentials(sourceUsername,
-                                               sourcePassword);
-                       sourceDefaultSession = sourceRepository.login(sourceCredentials);
-
-                       if (targetRepository == null)
-                               targetRepository = ArgeoJcrUtils.getRepositoryByUri(
-                                               repositoryFactory, targetRepoUri);
-                       if (targetCredentials == null && targetUsername != null)
-                               targetCredentials = new SimpleCredentials(targetUsername,
-                                               targetPassword);
-                       targetDefaultSession = targetRepository.login(targetCredentials);
-
-                       Map<String, Exception> errors = new HashMap<String, Exception>();
-                       for (String sourceWorkspaceName : sourceDefaultSession
-                                       .getWorkspace().getAccessibleWorkspaceNames()) {
-                               if (monitor != null && monitor.isCanceled())
-                                       break;
-
-                               if (workspaceMap != null
-                                               && !workspaceMap.containsKey(sourceWorkspaceName))
-                                       continue;
-                               if (IGNORED_WKSP_LIST.contains(sourceWorkspaceName))
-                                       continue;
-
-                               Session sourceSession = null;
-                               Session targetSession = null;
-                               String targetWorkspaceName = workspaceMap
-                                               .get(sourceWorkspaceName);
-                               try {
-                                       try {
-                                               targetSession = targetRepository.login(
-                                                               targetCredentials, targetWorkspaceName);
-                                       } catch (NoSuchWorkspaceException e) {
-                                               targetDefaultSession.getWorkspace().createWorkspace(
-                                                               targetWorkspaceName);
-                                               targetSession = targetRepository.login(
-                                                               targetCredentials, targetWorkspaceName);
-                                       }
-                                       sourceSession = sourceRepository.login(sourceCredentials,
-                                                       sourceWorkspaceName);
-                                       syncWorkspace(sourceSession, targetSession);
-                               } catch (Exception e) {
-                                       errors.put("Could not sync workspace "
-                                                       + sourceWorkspaceName, e);
-                                       if (log.isErrorEnabled())
-                                               e.printStackTrace();
-
-                               } finally {
-                                       JcrUtils.logoutQuietly(sourceSession);
-                                       JcrUtils.logoutQuietly(targetSession);
-                               }
-                       }
-
-                       if (monitor != null && monitor.isCanceled())
-                               log.info("Sync has been canceled by user");
-
-                       long duration = (System.currentTimeMillis() - begin) / 1000;// s
-                       log.info("Sync " + sourceRepoUri + " to " + targetRepoUri + " in "
-                                       + (duration / 60)
-
-                                       + "min " + (duration % 60) + "s");
-
-                       if (errors.size() > 0) {
-                               throw new SlcException("Sync failed " + errors);
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot sync " + sourceRepoUri + " to "
-                                       + targetRepoUri, e);
-               } finally {
-                       JcrUtils.logoutQuietly(sourceDefaultSession);
-                       JcrUtils.logoutQuietly(targetDefaultSession);
-               }
-       }
-
-       private long getNodesNumber(Session session) {
-               if (IGNORED_WKSP_LIST.contains(session.getWorkspace().getName()))
-                       return 0l;
-               try {
-                       Query countQuery = session
-                                       .getWorkspace()
-                                       .getQueryManager()
-                                       .createQuery(
-                                                       "select file from ["
-                                                                       + (true ? NodeType.NT_FILE
-                                                                                       : NodeType.NT_BASE) + "] as file",
-                                                       Query.JCR_SQL2);
-
-                       QueryResult result = countQuery.execute();
-                       Long expectedCount = result.getNodes().getSize();
-                       return expectedCount;
-               } catch (RepositoryException e) {
-                       throw new SlcException("Unexpected error while computing "
-                                       + "the size of the fetch for workspace "
-                                       + session.getWorkspace().getName(), e);
-               }
-       }
-
-       protected void syncWorkspace(Session sourceSession, Session targetSession) {
-               if (monitor != null) {
-                       monitor.beginTask("Computing fetch size...", -1);
-                       Long totalAmount = getNodesNumber(sourceSession);
-                       monitor.beginTask("Fetch", totalAmount.intValue());
-               }
-
-               try {
-                       String msg = "Synchronizing workspace: "
-                                       + sourceSession.getWorkspace().getName();
-                       if (monitor != null)
-                               monitor.setTaskName(msg);
-                       if (log.isDebugEnabled())
-                               log.debug(msg);
-
-                       if (filesOnly) {
-                               JcrUtils.copyFiles(sourceSession.getRootNode(),
-                                               targetSession.getRootNode(), true, monitor);
-                       } else {
-                               for (NodeIterator it = sourceSession.getRootNode().getNodes(); it
-                                               .hasNext();) {
-                                       Node node = it.nextNode();
-                                       if (node.getName().equals("jcr:system"))
-                                               continue;
-                                       syncNode(node, targetSession);
-                               }
-                       }
-                       if (log.isDebugEnabled())
-                               log.debug("Synced " + sourceSession.getWorkspace().getName());
-               } catch (Exception e) {
-                       e.printStackTrace();
-                       throw new SlcException("Cannot sync "
-                                       + sourceSession.getWorkspace().getName() + " to "
-                                       + targetSession.getWorkspace().getName(), e);
-               }
-       }
-
-       /** factorizes monitor management */
-       private void updateMonitor(String msg) {
-               updateMonitor(msg, false);
-       }
-
-       protected void syncNode(Node sourceNode, Session targetSession)
-                       throws RepositoryException, SAXException {
-               // Boolean singleLevel = singleLevel(sourceNode);
-               try {
-                       if (monitor != null && monitor.isCanceled()) {
-                               updateMonitor("Fetched has been canceled, "
-                                               + "process is terminating");
-                               return;
-                       }
-
-                       Node targetParentNode = targetSession.getNode(sourceNode
-                                       .getParent().getPath());
-                       Node targetNode;
-                       if (monitor != null
-                                       && sourceNode.isNodeType(NodeType.NT_HIERARCHY_NODE))
-                               monitor.subTask("Process " + sourceNode.getPath());
-
-                       final Boolean isNew;
-                       if (!targetSession.itemExists(sourceNode.getPath())) {
-                               isNew = true;
-                               targetNode = targetParentNode.addNode(sourceNode.getName(),
-                                               sourceNode.getPrimaryNodeType().getName());
-                       } else {
-                               isNew = false;
-                               targetNode = targetSession.getNode(sourceNode.getPath());
-                               if (!targetNode.getPrimaryNodeType().getName()
-                                               .equals(sourceNode.getPrimaryNodeType().getName()))
-                                       targetNode.setPrimaryType(sourceNode.getPrimaryNodeType()
-                                                       .getName());
-                       }
-
-                       // export
-                       // sourceNode.getSession().exportSystemView(sourceNode.getPath(),
-                       // contentHandler, false, singleLevel);
-
-                       // if (singleLevel) {
-                       // if (targetSession.hasPendingChanges()) {
-                       // // updateMonitor(
-                       // // (isNew ? "Added " : "Updated ") + targetNode.getPath(),
-                       // // true);
-                       // if (doSave)
-                       // targetSession.save();
-                       // } else {
-                       // // updateMonitor("Checked " + targetNode.getPath(), false);
-                       // }
-                       // }
-
-                       // mixin and properties
-                       for (NodeType nt : sourceNode.getMixinNodeTypes()) {
-                               if (!targetNode.isNodeType(nt.getName())
-                                               && targetNode.canAddMixin(nt.getName()))
-                                       targetNode.addMixin(nt.getName());
-                       }
-                       copyProperties(sourceNode, targetNode);
-
-                       // next level
-                       NodeIterator ni = sourceNode.getNodes();
-                       while (ni != null && ni.hasNext()) {
-                               Node sourceChild = ni.nextNode();
-                               syncNode(sourceChild, targetSession);
-                       }
-
-                       copyTimestamps(sourceNode, targetNode);
-
-                       if (sourceNode.isNodeType(NodeType.NT_HIERARCHY_NODE)) {
-                               if (targetSession.hasPendingChanges()) {
-                                       if (sourceNode.isNodeType(NodeType.NT_FILE))
-                                               updateMonitor((isNew ? "Added " : "Updated ")
-                                                               + targetNode.getPath(), true);
-                                       // if (doSave)
-                                       targetSession.save();
-                               } else {
-                                       if (sourceNode.isNodeType(NodeType.NT_FILE))
-                                               updateMonitor("Checked " + targetNode.getPath(), false);
-                               }
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot sync source node " + sourceNode, e);
-               }
-       }
-
-       private void copyTimestamps(Node sourceNode, Node targetNode)
-                       throws RepositoryException {
-               if (sourceNode.getDefinition().isProtected())
-                       return;
-               if (targetNode.getDefinition().isProtected())
-                       return;
-               copyTimestamp(sourceNode, targetNode, Property.JCR_CREATED);
-               copyTimestamp(sourceNode, targetNode, Property.JCR_CREATED_BY);
-               copyTimestamp(sourceNode, targetNode, Property.JCR_LAST_MODIFIED);
-               copyTimestamp(sourceNode, targetNode, Property.JCR_LAST_MODIFIED_BY);
-       }
-
-       private void copyTimestamp(Node sourceNode, Node targetNode, String property)
-                       throws RepositoryException {
-               if (sourceNode.hasProperty(property)) {
-                       Property p = sourceNode.getProperty(property);
-                       if (p.getDefinition().isProtected())
-                               return;
-                       if (targetNode.hasProperty(property)
-                                       && targetNode
-                                                       .getProperty(property)
-                                                       .getValue()
-                                                       .equals(sourceNode.getProperty(property).getValue()))
-                               return;
-                       targetNode.setProperty(property, sourceNode.getProperty(property)
-                                       .getValue());
-               }
-       }
-
-       private void copyProperties(Node sourceNode, Node targetNode)
-                       throws RepositoryException {
-               properties: for (PropertyIterator pi = sourceNode.getProperties(); pi
-                               .hasNext();) {
-                       Property p = pi.nextProperty();
-                       if (p.getDefinition().isProtected())
-                               continue properties;
-                       if (p.getName().equals(Property.JCR_CREATED)
-                                       || p.getName().equals(Property.JCR_CREATED_BY)
-                                       || p.getName().equals(Property.JCR_LAST_MODIFIED)
-                                       || p.getName().equals(Property.JCR_LAST_MODIFIED_BY))
-                               continue properties;
-
-                       if (p.getType() == PropertyType.BINARY) {
-                               copyBinary(p, targetNode);
-                       } else {
-
-                               if (p.isMultiple()) {
-                                       if (!targetNode.hasProperty(p.getName())
-                                                       || !Arrays.equals(
-                                                                       targetNode.getProperty(p.getName())
-                                                                                       .getValues(), p.getValues()))
-                                               targetNode.setProperty(p.getName(), p.getValues());
-                               } else {
-                                       if (!targetNode.hasProperty(p.getName())
-                                                       || !targetNode.getProperty(p.getName()).getValue()
-                                                                       .equals(p.getValue()))
-                                               targetNode.setProperty(p.getName(), p.getValue());
-                               }
-                       }
-               }
-       }
-
-       private static void copyBinary(Property p, Node targetNode)
-                       throws RepositoryException {
-               InputStream in = null;
-               Binary sourceBinary = null;
-               Binary targetBinary = null;
-               try {
-                       sourceBinary = p.getBinary();
-                       if (targetNode.hasProperty(p.getName()))
-                               targetBinary = targetNode.getProperty(p.getName()).getBinary();
-
-                       // optim FIXME make it more configurable
-                       if (targetBinary != null)
-                               if (sourceBinary.getSize() == targetBinary.getSize()) {
-                                       if (log.isTraceEnabled())
-                                               log.trace("Skipped " + p.getPath());
-                                       return;
-                               }
-
-                       in = sourceBinary.getStream();
-                       targetBinary = targetNode.getSession().getValueFactory()
-                                       .createBinary(in);
-                       targetNode.setProperty(p.getName(), targetBinary);
-               } catch (Exception e) {
-                       throw new SlcException("Could not transfer " + p, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       JcrUtils.closeQuietly(sourceBinary);
-                       JcrUtils.closeQuietly(targetBinary);
-               }
-       }
-
-       /** factorizes monitor management */
-       private void updateMonitor(String msg, Boolean doLog) {
-               if (doLog && log.isDebugEnabled())
-                       log.debug(msg);
-               if (monitor != null) {
-                       monitor.worked(1);
-                       monitor.subTask(msg);
-               }
-       }
-
-       // private void syncNode_old(Node sourceNode, Node targetParentNode)
-       // throws RepositoryException, SAXException {
-       //
-       // // enable cancelation of the current fetch process
-       // // FIXME insure the repository stays in a stable state
-       // if (monitor != null && monitor.isCanceled()) {
-       // updateMonitor("Fetched has been canceled, "
-       // + "process is terminating");
-       // return;
-       // }
-       //
-       // Boolean noRecurse = singleLevel(sourceNode);
-       // Calendar sourceLastModified = null;
-       // if (sourceNode.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
-       // sourceLastModified = sourceNode.getProperty(
-       // Property.JCR_LAST_MODIFIED).getDate();
-       // }
-       //
-       // if (sourceNode.getDefinition().isProtected())
-       // log.warn(sourceNode + " is protected.");
-       //
-       // if (!targetParentNode.hasNode(sourceNode.getName())) {
-       // String msg = "Adding " + sourceNode.getPath();
-       // updateMonitor(msg);
-       // if (log.isDebugEnabled())
-       // log.debug(msg);
-       // ContentHandler contentHandler = targetParentNode
-       // .getSession()
-       // .getWorkspace()
-       // .getImportContentHandler(targetParentNode.getPath(),
-       // ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
-       // sourceNode.getSession().exportSystemView(sourceNode.getPath(),
-       // contentHandler, false, noRecurse);
-       // } else {
-       // Node targetNode = targetParentNode.getNode(sourceNode.getName());
-       // if (sourceLastModified != null) {
-       // Calendar targetLastModified = null;
-       // if (targetNode.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
-       // targetLastModified = targetNode.getProperty(
-       // Property.JCR_LAST_MODIFIED).getDate();
-       // }
-       //
-       // if (targetLastModified == null
-       // || targetLastModified.before(sourceLastModified)) {
-       // String msg = "Updating " + targetNode.getPath();
-       // updateMonitor(msg);
-       // if (log.isDebugEnabled())
-       // log.debug(msg);
-       // ContentHandler contentHandler = targetParentNode
-       // .getSession()
-       // .getWorkspace()
-       // .getImportContentHandler(
-       // targetParentNode.getPath(),
-       // ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
-       // sourceNode.getSession().exportSystemView(
-       // sourceNode.getPath(), contentHandler, false,
-       // noRecurse);
-       // } else {
-       // String msg = "Skipped up to date " + targetNode.getPath();
-       // updateMonitor(msg);
-       // if (log.isDebugEnabled())
-       // log.debug(msg);
-       // return;
-       // }
-       // }
-       // }
-       //
-       // if (noRecurse) {
-       // // recurse
-       // Node targetNode = targetParentNode.getNode(sourceNode.getName());
-       // if (sourceLastModified != null) {
-       // Calendar zero = new GregorianCalendar();
-       // zero.setTimeInMillis(0);
-       // targetNode.setProperty(Property.JCR_LAST_MODIFIED, zero);
-       // targetNode.getSession().save();
-       // }
-       //
-       // for (NodeIterator it = sourceNode.getNodes(); it.hasNext();) {
-       // syncNode_old(it.nextNode(), targetNode);
-       // }
-       //
-       // if (sourceLastModified != null) {
-       // targetNode.setProperty(Property.JCR_LAST_MODIFIED,
-       // sourceLastModified);
-       // targetNode.getSession().save();
-       // }
-       // }
-       // }
-
-       protected Boolean singleLevel(Node sourceNode) throws RepositoryException {
-               if (sourceNode.isNodeType(NodeType.NT_FILE))
-                       return false;
-               return true;
-       }
-
-       /**
-        * Synchronises only one workspace, retrieved by name without changing its
-        * name.
-        */
-       public void setSourceWksp(String sourceWksp) {
-               if (sourceWksp != null && !sourceWksp.trim().equals("")) {
-                       Map<String, String> map = new HashMap<String, String>();
-                       map.put(sourceWksp, sourceWksp);
-                       setWkspMap(map);
-               }
-       }
-
-       /**
-        * Synchronises a map of workspaces that will be retrieved by name. If the
-        * target name is not defined (eg null or an empty string) for a given
-        * source workspace, we use the source name as target name.
-        */
-       public void setWkspMap(Map<String, String> workspaceMap) {
-               // clean the list to ease later use
-               this.workspaceMap = new HashMap<String, String>();
-               if (workspaceMap != null) {
-                       workspaceNames: for (String srcName : workspaceMap.keySet()) {
-                               String targetName = workspaceMap.get(srcName);
-
-                               // Sanity check
-                               if (srcName.trim().equals(""))
-                                       continue workspaceNames;
-                               if (targetName == null || "".equals(targetName.trim()))
-                                       targetName = srcName;
-                               this.workspaceMap.put(srcName, targetName);
-                       }
-               }
-               // clean the map to ease later use
-               if (this.workspaceMap.size() == 0)
-                       this.workspaceMap = null;
-       }
-
-       public void setMonitor(ArgeoMonitor monitor) {
-               this.monitor = monitor;
-       }
-
-       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
-               this.repositoryFactory = repositoryFactory;
-       }
-
-       public void setSourceRepoUri(String sourceRepoUri) {
-               this.sourceRepoUri = sourceRepoUri;
-       }
-
-       public void setSourceUsername(String sourceUsername) {
-               this.sourceUsername = sourceUsername;
-       }
-
-       public void setSourcePassword(char[] sourcePassword) {
-               this.sourcePassword = sourcePassword;
-       }
-
-       public void setTargetRepoUri(String targetRepoUri) {
-               this.targetRepoUri = targetRepoUri;
-       }
-
-       public void setTargetUsername(String targetUsername) {
-               this.targetUsername = targetUsername;
-       }
-
-       public void setTargetPassword(char[] targetPassword) {
-               this.targetPassword = targetPassword;
-       }
-
-       public void setSourceRepository(Repository sourceRepository) {
-               this.sourceRepository = sourceRepository;
-       }
-
-       public void setSourceCredentials(Credentials sourceCredentials) {
-               this.sourceCredentials = sourceCredentials;
-       }
-
-       public void setTargetRepository(Repository targetRepository) {
-               this.targetRepository = targetRepository;
-       }
-
-       public void setTargetCredentials(Credentials targetCredentials) {
-               this.targetCredentials = targetCredentials;
-       }
-
-       public void setFilesOnly(Boolean filesOnly) {
-               this.filesOnly = filesOnly;
-       }
-
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoUtils.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RepoUtils.java
deleted file mode 100644 (file)
index 4a175ac..0000000
+++ /dev/null
@@ -1,652 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarInputStream;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipInputStream;
-
-import javax.jcr.Credentials;
-import javax.jcr.GuestCredentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.ArgeoTypes;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.ArtifactIdComparator;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.argeo.util.security.Keyring;
-import org.osgi.framework.Constants;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/** Utilities around repo */
-public class RepoUtils implements ArgeoNames, SlcNames {
-       private final static Log log = LogFactory.getLog(RepoUtils.class);
-
-       /** Packages a regular sources jar as PDE source. */
-       public static void packagesAsPdeSource(File sourceFile,
-                       NameVersion nameVersion, OutputStream out) throws IOException {
-               if (isAlreadyPdeSource(sourceFile)) {
-                       FileInputStream in = new FileInputStream(sourceFile);
-                       IOUtils.copy(in, out);
-                       IOUtils.closeQuietly(in);
-               } else {
-                       String sourceSymbolicName = nameVersion.getName() + ".source";
-
-                       Manifest sourceManifest = null;
-                       sourceManifest = new Manifest();
-                       sourceManifest.getMainAttributes().put(
-                                       Attributes.Name.MANIFEST_VERSION, "1.0");
-                       sourceManifest.getMainAttributes().putValue("Bundle-SymbolicName",
-                                       sourceSymbolicName);
-                       sourceManifest.getMainAttributes().putValue("Bundle-Version",
-                                       nameVersion.getVersion());
-                       sourceManifest.getMainAttributes().putValue(
-                                       "Eclipse-SourceBundle",
-                                       nameVersion.getName() + ";version="
-                                                       + nameVersion.getVersion());
-                       copyJar(sourceFile, out, sourceManifest);
-               }
-       }
-
-       public static byte[] packageAsPdeSource(InputStream sourceJar,
-                       NameVersion nameVersion) {
-               String sourceSymbolicName = nameVersion.getName() + ".source";
-
-               Manifest sourceManifest = null;
-               sourceManifest = new Manifest();
-               sourceManifest.getMainAttributes().put(
-                               Attributes.Name.MANIFEST_VERSION, "1.0");
-               sourceManifest.getMainAttributes().putValue("Bundle-SymbolicName",
-                               sourceSymbolicName);
-               sourceManifest.getMainAttributes().putValue("Bundle-Version",
-                               nameVersion.getVersion());
-               sourceManifest.getMainAttributes().putValue("Eclipse-SourceBundle",
-                               nameVersion.getName() + ";version=" + nameVersion.getVersion());
-
-               return modifyManifest(sourceJar, sourceManifest);
-       }
-
-       /**
-        * Check whether the file as already been packaged as PDE source, in order
-        * not to mess with Jar signing
-        */
-       private static boolean isAlreadyPdeSource(File sourceFile) {
-               JarInputStream jarInputStream = null;
-
-               try {
-                       jarInputStream = new JarInputStream(new FileInputStream(sourceFile));
-
-                       Manifest manifest = jarInputStream.getManifest();
-                       Iterator<?> it = manifest.getMainAttributes().keySet().iterator();
-                       boolean res = false;
-                       // containsKey() does not work, iterating...
-                       while (it.hasNext())
-                               if (it.next().toString().equals("Eclipse-SourceBundle")) {
-                                       res = true;
-                                       break;
-                               }
-                       // boolean res = manifest.getMainAttributes().get(
-                       // "Eclipse-SourceBundle") != null;
-                       if (res)
-                               log.info(sourceFile + " is already a PDE source");
-                       return res;
-               } catch (Exception e) {
-                       // probably not a jar, skipping
-                       if (log.isDebugEnabled())
-                               log.debug("Skipping " + sourceFile + " because of "
-                                               + e.getMessage());
-                       return false;
-               } finally {
-                       IOUtils.closeQuietly(jarInputStream);
-               }
-       }
-
-       /**
-        * Copy a jar, replacing its manifest with the provided one
-        * 
-        * @param manifest
-        *            can be null
-        */
-       private static void copyJar(File source, OutputStream out, Manifest manifest)
-                       throws IOException {
-               JarFile sourceJar = null;
-               JarOutputStream output = null;
-               try {
-                       output = manifest != null ? new JarOutputStream(out, manifest)
-                                       : new JarOutputStream(out);
-                       sourceJar = new JarFile(source);
-
-                       entries: for (Enumeration<?> entries = sourceJar.entries(); entries
-                                       .hasMoreElements();) {
-                               JarEntry entry = (JarEntry) entries.nextElement();
-                               if (manifest != null
-                                               && entry.getName().equals("META-INF/MANIFEST.MF"))
-                                       continue entries;
-
-                               InputStream entryStream = sourceJar.getInputStream(entry);
-                               JarEntry newEntry = new JarEntry(entry.getName());
-                               // newEntry.setMethod(JarEntry.DEFLATED);
-                               output.putNextEntry(newEntry);
-                               IOUtils.copy(entryStream, output);
-                       }
-               } finally {
-                       IOUtils.closeQuietly(output);
-                       try {
-                               if (sourceJar != null)
-                                       sourceJar.close();
-                       } catch (IOException e) {
-                               // silent
-                       }
-               }
-       }
-
-       /** Copy a jar changing onlythe manifest */
-       public static void copyJar(InputStream in, OutputStream out,
-                       Manifest manifest) {
-               JarInputStream jarIn = null;
-               JarOutputStream jarOut = null;
-               try {
-                       jarIn = new JarInputStream(in);
-                       jarOut = new JarOutputStream(out, manifest);
-                       JarEntry jarEntry = null;
-                       while ((jarEntry = jarIn.getNextJarEntry()) != null) {
-                               if (!jarEntry.getName().equals("META-INF/MANIFEST.MF")) {
-                                       JarEntry newJarEntry = new JarEntry(jarEntry.getName());
-                                       jarOut.putNextEntry(newJarEntry);
-                                       IOUtils.copy(jarIn, jarOut);
-                                       jarIn.closeEntry();
-                                       jarOut.closeEntry();
-                               }
-                       }
-               } catch (IOException e) {
-                       throw new SlcException("Could not copy jar with MANIFEST "
-                                       + manifest.getMainAttributes(), e);
-               } finally {
-                       if (!(in instanceof ZipInputStream))
-                               IOUtils.closeQuietly(jarIn);
-                       IOUtils.closeQuietly(jarOut);
-               }
-       }
-
-       /** Reads a jar file, modify its manifest */
-       public static byte[] modifyManifest(InputStream in, Manifest manifest) {
-               ByteArrayOutputStream out = new ByteArrayOutputStream(200 * 1024);
-               try {
-                       copyJar(in, out, manifest);
-                       return out.toByteArray();
-               } finally {
-                       IOUtils.closeQuietly(out);
-               }
-       }
-
-       /** Read the OSGi {@link NameVersion} */
-       public static NameVersion readNameVersion(Artifact artifact) {
-               File artifactFile = artifact.getFile();
-               if (artifact.getExtension().equals("pom")) {
-                       // hack to process jars which weirdly appear as POMs
-                       File jarFile = new File(artifactFile.getParentFile(),
-                                       FilenameUtils.getBaseName(artifactFile.getPath()) + ".jar");
-                       if (jarFile.exists()) {
-                               log.warn("Use " + jarFile + " instead of " + artifactFile
-                                               + " for " + artifact);
-                               artifactFile = jarFile;
-                       }
-               }
-               return readNameVersion(artifactFile);
-       }
-
-       /** Read the OSGi {@link NameVersion} */
-       public static NameVersion readNameVersion(File artifactFile) {
-               try {
-                       return readNameVersion(new FileInputStream(artifactFile));
-               } catch (Exception e) {
-                       // probably not a jar, skipping
-                       if (log.isDebugEnabled()) {
-                               log.debug("Skipping " + artifactFile + " because of " + e);
-                               // e.printStackTrace();
-                       }
-               }
-               return null;
-       }
-
-       /** Read the OSGi {@link NameVersion} */
-       public static NameVersion readNameVersion(InputStream in) {
-               JarInputStream jarInputStream = null;
-               try {
-                       jarInputStream = new JarInputStream(in);
-                       return readNameVersion(jarInputStream.getManifest());
-               } catch (Exception e) {
-                       // probably not a jar, skipping
-                       if (log.isDebugEnabled()) {
-                               log.debug("Skipping because of " + e);
-                               e.printStackTrace();
-                       }
-               } finally {
-                       IOUtils.closeQuietly(jarInputStream);
-               }
-               return null;
-       }
-
-       /** Read the OSGi {@link NameVersion} */
-       public static NameVersion readNameVersion(Manifest manifest) {
-               DefaultNameVersion nameVersion = new DefaultNameVersion();
-               nameVersion.setName(manifest.getMainAttributes().getValue(
-                               Constants.BUNDLE_SYMBOLICNAME));
-
-               // Skip additional specs such as
-               // ; singleton:=true
-               if (nameVersion.getName().indexOf(';') > -1) {
-                       nameVersion
-                                       .setName(new StringTokenizer(nameVersion.getName(), " ;")
-                                                       .nextToken());
-               }
-
-               nameVersion.setVersion(manifest.getMainAttributes().getValue(
-                               Constants.BUNDLE_VERSION));
-
-               return nameVersion;
-       }
-
-       /*
-        * DATA MODEL
-        */
-       /** The artifact described by this node */
-       public static Artifact asArtifact(Node node) throws RepositoryException {
-               if (node.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
-                       // FIXME update data model to store packaging at this level
-                       String extension = "jar";
-                       return new DefaultArtifact(node.getProperty(SLC_GROUP_ID)
-                                       .getString(),
-                                       node.getProperty(SLC_ARTIFACT_ID).getString(), extension,
-                                       node.getProperty(SLC_ARTIFACT_VERSION).getString());
-               } else if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
-                       return new DefaultArtifact(node.getProperty(SLC_GROUP_ID)
-                                       .getString(),
-                                       node.getProperty(SLC_ARTIFACT_ID).getString(), node
-                                                       .getProperty(SLC_ARTIFACT_CLASSIFIER).getString(),
-                                       node.getProperty(SLC_ARTIFACT_EXTENSION).getString(), node
-                                                       .getProperty(SLC_ARTIFACT_VERSION).getString());
-               } else if (node.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
-                       return new DefaultArtifact(node.getProperty(SLC_CATEGORY)
-                                       .getString(), node.getProperty(SLC_NAME).getString(),
-                                       "jar", node.getProperty(SLC_VERSION).getString());
-               } else {
-                       throw new SlcException("Unsupported node type for " + node);
-               }
-       }
-
-       /**
-        * The path to the PDE source related to this artifact (or artifact version
-        * base). There may or there may not be a node at this location (the
-        * returned path will typically be used to test whether PDE sources are
-        * attached to this artifact).
-        */
-       public static String relatedPdeSourcePath(String artifactBasePath,
-                       Node artifactNode) throws RepositoryException {
-               Artifact artifact = asArtifact(artifactNode);
-               Artifact pdeSourceArtifact = new DefaultArtifact(artifact.getGroupId(),
-                               artifact.getArtifactId() + ".source", artifact.getExtension(),
-                               artifact.getVersion());
-               return MavenConventionsUtils.artifactPath(artifactBasePath,
-                               pdeSourceArtifact);
-       }
-
-       /**
-        * Copy this bytes array as an artifact, relative to the root of the
-        * repository (typically the workspace root node)
-        */
-       public static Node copyBytesAsArtifact(Node artifactsBase,
-                       Artifact artifact, byte[] bytes) throws RepositoryException {
-               String parentPath = MavenConventionsUtils.artifactParentPath(
-                               artifactsBase.getPath(), artifact);
-               Node folderNode = JcrUtils.mkfolders(artifactsBase.getSession(),
-                               parentPath);
-               return JcrUtils.copyBytesAsFile(folderNode,
-                               MavenConventionsUtils.artifactFileName(artifact), bytes);
-       }
-
-       private RepoUtils() {
-       }
-
-       /** If a source return the base bundle name, does not change otherwise */
-       public static String extractBundleNameFromSourceName(String sourceBundleName) {
-               if (sourceBundleName.endsWith(".source"))
-                       return sourceBundleName.substring(0, sourceBundleName.length()
-                                       - ".source".length());
-               else
-                       return sourceBundleName;
-       }
-
-       /*
-        * SOFTWARE REPOSITORIES
-        */
-
-       /** Retrieve repository based on information in the repo node */
-       public static Repository getRepository(RepositoryFactory repositoryFactory,
-                       Keyring keyring, Node repoNode) {
-               try {
-                       Repository repository;
-                       if (repoNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
-                               String uri = repoNode.getProperty(ARGEO_URI).getString();
-                               if (uri.startsWith("http")) {// http, https
-                                       repository = ArgeoJcrUtils.getRepositoryByUri(
-                                                       repositoryFactory, uri);
-                               } else if (uri.startsWith("vm:")) {// alias
-                                       repository = ArgeoJcrUtils.getRepositoryByUri(
-                                                       repositoryFactory, uri);
-                               } else {
-                                       throw new SlcException("Unsupported repository uri " + uri);
-                               }
-                               return repository;
-                       } else {
-                               throw new SlcException("Unsupported node type " + repoNode);
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot connect to repository " + repoNode,
-                                       e);
-               }
-       }
-
-       /**
-        * Reads credentials from node, using keyring if there is a password. Can
-        * return null if no credentials needed (local repo) at all, but returns
-        * {@link GuestCredentials} if user id is 'anonymous' .
-        */
-       public static Credentials getRepositoryCredentials(Keyring keyring,
-                       Node repoNode) {
-               try {
-                       if (repoNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
-                               if (!repoNode.hasProperty(ARGEO_USER_ID))
-                                       return null;
-
-                               String userId = repoNode.getProperty(ARGEO_USER_ID).getString();
-                               if (userId.equals("anonymous"))// FIXME hardcoded userId
-                                       return new GuestCredentials();
-                               char[] password = keyring.getAsChars(repoNode.getPath() + '/'
-                                               + ARGEO_PASSWORD);
-                               Credentials credentials = new SimpleCredentials(userId,
-                                               password);
-                               return credentials;
-                       } else {
-                               throw new SlcException("Unsupported node type " + repoNode);
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot connect to repository " + repoNode,
-                                       e);
-               }
-       }
-
-       /**
-        * Shortcut to retrieve a session given variable information: Handle the
-        * case where we only have an URI of the repository, that we want to connect
-        * as anonymous or the case of a identified connection to a local or remote
-        * repository.
-        * 
-        * Callers must close the session once it has been used
-        */
-       public static Session getRemoteSession(RepositoryFactory repositoryFactory,
-                       Keyring keyring, Node repoNode, String uri, String workspaceName) {
-               try {
-                       if (repoNode == null && uri == null)
-                               throw new SlcException(
-                                               "At least one of repoNode and uri must be defined");
-                       Repository currRepo = null;
-                       Credentials credentials = null;
-                       // Anonymous URI only workspace
-                       if (repoNode == null)
-                               // Anonymous
-                               currRepo = ArgeoJcrUtils.getRepositoryByUri(repositoryFactory,
-                                               uri);
-                       else {
-                               currRepo = RepoUtils.getRepository(repositoryFactory, keyring,
-                                               repoNode);
-                               credentials = RepoUtils.getRepositoryCredentials(keyring,
-                                               repoNode);
-                       }
-                       return currRepo.login(credentials, workspaceName);
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot connect to workspace "
-                                       + workspaceName + " of repository " + repoNode
-                                       + " with URI " + uri, e);
-               }
-       }
-
-       /**
-        * Shortcut to retrieve a session on a remote Jrc Repository from
-        * information stored in a local argeo node or from an URI: Handle the case
-        * where we only have an URI of the repository, that we want to connect as
-        * anonymous or the case of a identified connection to a local or remote
-        * repository.
-        * 
-        * Callers must close the session once it has been used
-        */
-       public static Session getRemoteSession(RepositoryFactory repositoryFactory,
-                       Keyring keyring, Repository localRepository, String repoNodePath,
-                       String uri, String workspaceName) {
-               Session localSession = null;
-               Node repoNode = null;
-               try {
-                       localSession = localRepository.login();
-                       if (repoNodePath != null && localSession.nodeExists(repoNodePath))
-                               repoNode = localSession.getNode(repoNodePath);
-
-                       return RepoUtils.getRemoteSession(repositoryFactory, keyring,
-                                       repoNode, uri, workspaceName);
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot log to workspace " + workspaceName
-                                       + " for repo defined in " + repoNodePath, e);
-               } finally {
-                       JcrUtils.logoutQuietly(localSession);
-               }
-       }
-
-       /**
-        * Write group indexes: 'binaries' lists all bundles and their versions,
-        * 'sources' list their sources, and 'sdk' aggregates both.
-        */
-       public static void writeGroupIndexes(Session session,
-                       String artifactBasePath, String groupId, String version,
-                       Set<Artifact> binaries, Set<Artifact> sources) {
-               try {
-                       Set<Artifact> indexes = new TreeSet<Artifact>(
-                                       new ArtifactIdComparator());
-                       Artifact binariesArtifact = writeIndex(session, artifactBasePath,
-                                       groupId, RepoConstants.BINARIES_ARTIFACT_ID, version,
-                                       binaries);
-                       indexes.add(binariesArtifact);
-                       if (sources != null) {
-                               Artifact sourcesArtifact = writeIndex(session,
-                                               artifactBasePath, groupId,
-                                               RepoConstants.SOURCES_ARTIFACT_ID, version, sources);
-                               indexes.add(sourcesArtifact);
-                       }
-                       // sdk
-                       writeIndex(session, artifactBasePath, groupId,
-                                       RepoConstants.SDK_ARTIFACT_ID, version, indexes);
-                       session.save();
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot write indexes for group " + groupId,
-                                       e);
-               }
-       }
-
-       /** Write a group index. */
-       private static Artifact writeIndex(Session session,
-                       String artifactBasePath, String groupId, String artifactId,
-                       String version, Set<Artifact> artifacts) throws RepositoryException {
-               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
-                               version);
-               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
-                               artifacts, null);
-               Node node = RepoUtils.copyBytesAsArtifact(
-                               session.getNode(artifactBasePath), artifact, pom.getBytes());
-               addMavenChecksums(node);
-               return artifact;
-       }
-
-       /** Add files containing the SHA-1 and MD5 checksums. */
-       public static void addMavenChecksums(Node node) throws RepositoryException {
-               // TODO optimize
-               String sha = JcrUtils.checksumFile(node, "SHA-1");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
-                               sha.getBytes());
-               String md5 = JcrUtils.checksumFile(node, "MD5");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
-                               md5.getBytes());
-       }
-
-       /**
-        * Custom copy since the one in commons does not fit the needs when copying
-        * a workspace completely.
-        */
-       public static void copy(Node fromNode, Node toNode) {
-               copy(fromNode, toNode, null);
-       }
-
-       public static void copy(Node fromNode, Node toNode, ArgeoMonitor monitor) {
-               try {
-                       String fromPath = fromNode.getPath();
-                       if (monitor != null)
-                               monitor.subTask("copying node :" + fromPath);
-                       if (log.isDebugEnabled())
-                               log.debug("copy node :" + fromPath);
-
-                       // FIXME : small hack to enable specific workspace copy
-                       if (fromNode.isNodeType("rep:ACL")
-                                       || fromNode.isNodeType("rep:system")) {
-                               if (log.isTraceEnabled())
-                                       log.trace("node " + fromNode + " skipped");
-                               return;
-                       }
-
-                       // add mixins
-                       for (NodeType mixinType : fromNode.getMixinNodeTypes()) {
-                               toNode.addMixin(mixinType.getName());
-                       }
-
-                       // Double check
-                       for (NodeType mixinType : toNode.getMixinNodeTypes()) {
-                               if (log.isDebugEnabled())
-                                       log.debug(mixinType.getName());
-                       }
-
-                       // process properties
-                       PropertyIterator pit = fromNode.getProperties();
-                       properties: while (pit.hasNext()) {
-                               Property fromProperty = pit.nextProperty();
-                               String propName = fromProperty.getName();
-                               try {
-                                       String propertyName = fromProperty.getName();
-                                       if (toNode.hasProperty(propertyName)
-                                                       && toNode.getProperty(propertyName).getDefinition()
-                                                                       .isProtected())
-                                               continue properties;
-
-                                       if (fromProperty.getDefinition().isProtected())
-                                               continue properties;
-
-                                       if (propertyName.equals("jcr:created")
-                                                       || propertyName.equals("jcr:createdBy")
-                                                       || propertyName.equals("jcr:lastModified")
-                                                       || propertyName.equals("jcr:lastModifiedBy"))
-                                               continue properties;
-
-                                       if (fromProperty.isMultiple()) {
-                                               toNode.setProperty(propertyName,
-                                                               fromProperty.getValues());
-                                       } else {
-                                               toNode.setProperty(propertyName,
-                                                               fromProperty.getValue());
-                                       }
-                               } catch (RepositoryException e) {
-                                       throw new SlcException("Cannot property " + propName, e);
-                               }
-                       }
-
-                       // recursively process children nodes
-                       NodeIterator nit = fromNode.getNodes();
-                       while (nit.hasNext()) {
-                               Node fromChild = nit.nextNode();
-                               Integer index = fromChild.getIndex();
-                               String nodeRelPath = fromChild.getName() + "[" + index + "]";
-                               Node toChild;
-                               if (toNode.hasNode(nodeRelPath))
-                                       toChild = toNode.getNode(nodeRelPath);
-                               else
-                                       toChild = toNode.addNode(fromChild.getName(), fromChild
-                                                       .getPrimaryNodeType().getName());
-                               copy(fromChild, toChild);
-                       }
-
-                       // update jcr:lastModified and jcr:lastModifiedBy in toNode in
-                       // case
-                       // they existed
-                       if (!toNode.getDefinition().isProtected()
-                                       && toNode.isNodeType(NodeType.MIX_LAST_MODIFIED))
-                               JcrUtils.updateLastModified(toNode);
-
-                       // Workaround to reduce session size: artifact is a saveable
-                       // unity
-                       if (toNode.isNodeType(SlcTypes.SLC_ARTIFACT))
-                               toNode.getSession().save();
-
-                       if (monitor != null)
-                               monitor.worked(1);
-
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot copy " + fromNode + " to " + toNode,
-                                       e);
-               }
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmIndexer.java
deleted file mode 100644 (file)
index 57b93b8..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-package org.argeo.slc.repo;
-
-import static org.freecompany.redline.header.Header.HeaderTag.HEADERIMMUTABLE;
-import static org.freecompany.redline.header.Signature.SignatureTag.SIGNATURES;
-
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-import java.nio.channels.Channels;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.FilenameUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.freecompany.redline.ChannelWrapper.Key;
-import org.freecompany.redline.ReadableChannelWrapper;
-import org.freecompany.redline.header.AbstractHeader;
-import org.freecompany.redline.header.Format;
-import org.freecompany.redline.header.Header;
-
-/** Indexes an RPM file. */
-public class RpmIndexer implements NodeIndexer, SlcNames {
-       private Boolean force = false;
-
-       @Override
-       public Boolean support(String path) {
-               return FilenameUtils.getExtension(path).equals("rpm");
-       }
-
-       @Override
-       public void index(Node node) {
-               try {
-                       if (!support(node.getPath()))
-                               return;
-
-                       // Already indexed
-                       if (!force && node.isNodeType(SlcTypes.SLC_RPM))
-                               return;
-
-                       if (!node.isNodeType(NodeType.NT_FILE))
-                               return;
-
-                       InputStream in = node.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
-                       ReadableChannelWrapper channel = new ReadableChannelWrapper(
-                                       Channels.newChannel(in));
-                       Format format = readRpmInfo(channel);
-
-                       node.addMixin(SlcTypes.SLC_RPM);
-                       node.setProperty(SLC_NAME, readTag(format, Header.HeaderTag.NAME));
-                       String rpmVersion = readTag(format, Header.HeaderTag.VERSION);
-                       String rpmRelease = readTag(format, Header.HeaderTag.RELEASE);
-                       node.setProperty(SLC_RPM_VERSION, rpmVersion);
-                       node.setProperty(SLC_RPM_RELEASE, rpmRelease);
-                       node.setProperty(SLC_VERSION, rpmVersion + "-" + rpmRelease);
-
-                       String arch = readTag(format, Header.HeaderTag.ARCH);
-                       if (arch != null)
-                               node.setProperty(SLC_RPM_ARCH, arch);
-
-                       String archiveSize = readTag(format, Header.HeaderTag.ARCHIVESIZE);
-                       if (archiveSize != null)
-                               node.setProperty(SLC_RPM_ARCHIVE_SIZE,
-                                               Long.parseLong(archiveSize));
-
-                       node.getSession().save();
-               } catch (Exception e) {
-                       throw new SlcException("Cannot index " + node, e);
-               }
-
-       }
-
-       @SuppressWarnings("unused")
-       public Format readRpmInfo(ReadableChannelWrapper channel) throws Exception {
-               Format format = new Format();
-
-               Key<Integer> lead = channel.start();
-               format.getLead().read(channel);
-               // System.out.println( "Lead ended at '" + in.finish( lead) + "'.");
-
-               Key<Integer> signature = channel.start();
-               int count = format.getSignature().read(channel);
-               int expected = ByteBuffer
-                               .wrap((byte[]) format.getSignature().getEntry(SIGNATURES)
-                                               .getValues(), 8, 4).getInt()
-                               / -16;
-               // System.out.println( "Signature ended at '" + in.finish( signature) +
-               // "' and contained '" + count + "' headers (expected '" + expected +
-               // "').");
-
-               Key<Integer> header = channel.start();
-               count = format.getHeader().read(channel);
-               expected = ByteBuffer.wrap(
-                               (byte[]) format.getHeader().getEntry(HEADERIMMUTABLE)
-                                               .getValues(), 8, 4).getInt()
-                               / -16;
-               // System.out.println( "Header ended at '" + in.finish( header) +
-               // " and contained '" + count + "' headers (expected '" + expected +
-               // "').");
-
-               return format;
-       }
-
-       private String readTag(Format format, Header.HeaderTag tag) {
-               AbstractHeader.Entry<?> entry = format.getHeader().getEntry(tag);
-               if (entry == null)
-                       return null;
-               if (entry.getValues() == null)
-                       return null;
-               Object[] values = (Object[]) entry.getValues();
-               return values[0].toString().trim();
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmRepoManager.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/RpmRepoManager.java
deleted file mode 100644 (file)
index 7535468..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.argeo.slc.repo;
-
-public interface RpmRepoManager {
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/SlcRepoManager.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/SlcRepoManager.java
deleted file mode 100644 (file)
index a0ba8e0..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-package org.argeo.slc.repo;
-
-/** Coordinator of the various type of repository (Java, RPM, etc.) */
-public interface SlcRepoManager {
-       /** @return null if Java not supported. */
-       public JavaRepoManager getJavaRepoManager();
-
-       /** @return null if RPM not supported. */
-       public RpmRepoManager getRpmRepoManager();
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/AbstractJcrRepoManager.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/AbstractJcrRepoManager.java
deleted file mode 100644 (file)
index 4bdda83..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.argeo.slc.repo.core;
-
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import javax.jcr.NoSuchWorkspaceException;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.NodeIndexer;
-
-/** Generic operations on a JCR-based repo. */
-abstract class AbstractJcrRepoManager {
-       private final static Log log = LogFactory
-                       .getLog(AbstractJcrRepoManager.class);
-       private String securityWorkspace = "security";
-
-       private Repository jcrRepository;
-       private Session adminSession;
-       private List<NodeIndexer> nodeIndexers;
-
-       // registries
-       private Map<String, Session> workspaceSessions = new TreeMap<String, Session>();
-       private Map<String, WorkspaceIndexer> workspaceIndexers = new TreeMap<String, WorkspaceIndexer>();
-
-       public void init() {
-               try {
-                       adminSession = jcrRepository.login();
-                       String[] workspaceNames = adminSession.getWorkspace()
-                                       .getAccessibleWorkspaceNames();
-                       for (String workspaceName : workspaceNames) {
-                               if (workspaceName.equals(securityWorkspace))
-                                       continue;
-                               if (workspaceName.equals(adminSession.getWorkspace().getName()))
-                                       continue;
-                               workspaceInit(workspaceName);
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot initialize repo manager", e);
-               }
-       }
-
-       public void destroy() {
-               for (String key : workspaceIndexers.keySet()) {
-                       workspaceIndexers.get(key).close();
-               }
-
-               for (String key : workspaceSessions.keySet()) {
-                       JcrUtils.logoutQuietly(workspaceSessions.get(key));
-               }
-               JcrUtils.logoutQuietly(adminSession);
-       }
-
-       public void createWorkspace(String workspaceName) {
-               try {
-                       try {
-                               jcrRepository.login(workspaceName);
-                               throw new SlcException("Workspace " + workspaceName
-                                               + " exists already.");
-                       } catch (NoSuchWorkspaceException e) {
-                               // try to create workspace
-                               adminSession.getWorkspace().createWorkspace(workspaceName);
-                               workspaceInit(workspaceName);
-                       }
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot create workspace " + workspaceName,
-                                       e);
-               }
-       }
-
-       protected void workspaceInit(String workspaceName) {
-               Session workspaceAdminSession = null;
-               try {
-                       workspaceAdminSession = jcrRepository.login(workspaceName);
-                       workspaceSessions.put(workspaceName, adminSession);
-                       JcrUtils.addPrivilege(workspaceAdminSession, "/",
-                                       SlcConstants.ROLE_SLC, "jcr:all");
-                       WorkspaceIndexer workspaceIndexer = new WorkspaceIndexer(
-                                       workspaceAdminSession, nodeIndexers);
-                       workspaceIndexers.put(workspaceName, workspaceIndexer);
-               } catch (RepositoryException e) {
-                       log.error("Cannot initialize workspace " + workspaceName, e);
-               } finally {
-                       JcrUtils.logoutQuietly(workspaceAdminSession);
-               }
-       }
-
-       public void setJcrRepository(Repository jcrRepository) {
-               this.jcrRepository = jcrRepository;
-       }
-
-       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
-               this.nodeIndexers = nodeIndexers;
-       }
-
-       public void setSecurityWorkspace(String securityWorkspace) {
-               this.securityWorkspace = securityWorkspace;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/JavaRepoManagerImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/JavaRepoManagerImpl.java
deleted file mode 100644 (file)
index dfd0c8a..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.argeo.slc.repo.core;
-
-import org.argeo.slc.repo.JavaRepoManager;
-
-/** Java-specific operations */
-public class JavaRepoManagerImpl extends AbstractJcrRepoManager implements
-               JavaRepoManager {
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RepoServiceImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RepoServiceImpl.java
deleted file mode 100644 (file)
index 45ea83a..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.argeo.slc.repo.core;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.slc.repo.RepoService;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-
-/**
- * Work in Progress - enhance this. First implementation of a service that
- * centralizes session management in an argeo SLC context, repositories are
- * either defined using an URI and a workspace name in a anonymous context or
- * using connection information that are store in a corresponding node in the
- * local repository home
- */
-public class RepoServiceImpl implements RepoService {
-
-       /* DEPENDENCY INJECTION */
-       private Repository nodeRepository;
-       private RepositoryFactory repositoryFactory;
-       private Keyring keyring;
-
-       public Session getRemoteSession(String repoNodePath, String uri,
-                       String workspaceName) {
-               return RepoUtils.getRemoteSession(repositoryFactory, keyring,
-                               nodeRepository, repoNodePath, uri, workspaceName);
-       }
-
-       /* DEPENDENCY INJECTION */
-       public void setNodeRepository(Repository nodeRepository) {
-               this.nodeRepository = nodeRepository;
-       }
-
-       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
-               this.repositoryFactory = repositoryFactory;
-       }
-
-       public void setKeyring(Keyring keyring) {
-               this.keyring = keyring;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RpmRepoManagerImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/RpmRepoManagerImpl.java
deleted file mode 100644 (file)
index 6e83523..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.argeo.slc.repo.core;
-
-import org.argeo.slc.repo.RpmRepoManager;
-
-/** RPM-specific operations */
-public class RpmRepoManagerImpl extends AbstractJcrRepoManager implements
-               RpmRepoManager {
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/SlcRepoManagerImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/SlcRepoManagerImpl.java
deleted file mode 100644 (file)
index bce6f03..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.argeo.slc.repo.core;
-
-import org.argeo.slc.repo.JavaRepoManager;
-import org.argeo.slc.repo.RpmRepoManager;
-import org.argeo.slc.repo.SlcRepoManager;
-
-/** Coordinator of the various repositories. */
-public class SlcRepoManagerImpl implements SlcRepoManager {
-       private JavaRepoManager javaRepoManager;
-       private RpmRepoManager rpmRepoManager;
-
-       public void init() {
-
-       }
-
-       public void destroy() {
-
-       }
-
-       @Override
-       public JavaRepoManager getJavaRepoManager() {
-               return javaRepoManager;
-       }
-
-       public void setJavaRepoManager(JavaRepoManager javaRepoManager) {
-               this.javaRepoManager = javaRepoManager;
-       }
-
-       @Override
-       public RpmRepoManager getRpmRepoManager() {
-               return rpmRepoManager;
-       }
-
-       public void setRpmRepoManager(RpmRepoManager rpmRepoManager) {
-               this.rpmRepoManager = rpmRepoManager;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/WorkspaceIndexer.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/core/WorkspaceIndexer.java
deleted file mode 100644 (file)
index e5622aa..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.core;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.observation.Event;
-import javax.jcr.observation.EventIterator;
-import javax.jcr.observation.EventListener;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.NodeIndexer;
-
-/** Maintains the metadata of a workspace, using listeners */
-public class WorkspaceIndexer {
-       private final static Log log = LogFactory.getLog(WorkspaceIndexer.class);
-
-       private final Session adminSession;
-       private IndexingListener artifactListener;
-       /** order may be important */
-       private final List<NodeIndexer> nodeIndexers;
-
-       public WorkspaceIndexer(Session adminSession, List<NodeIndexer> nodeIndexers) {
-               this.adminSession = adminSession;
-               this.nodeIndexers = nodeIndexers;
-               try {
-                       artifactListener = new IndexingListener();
-                       adminSession
-                                       .getWorkspace()
-                                       .getObservationManager()
-                                       .addEventListener(artifactListener, Event.NODE_ADDED, "/",
-                                                       true, null, null, true);
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot initialize repository backend", e);
-               }
-       }
-
-       public void close() {
-               try {
-                       adminSession.getWorkspace().getObservationManager()
-                                       .removeEventListener(artifactListener);
-               } catch (RepositoryException e) {
-                       log.error("Cannot close workspace indexer "
-                                       + adminSession.getWorkspace().getName(), e);
-               }
-       }
-
-       class IndexingListener implements EventListener {
-
-               public void onEvent(EventIterator events) {
-                       while (events.hasNext()) {
-                               Event event = events.nextEvent();
-                               try {
-                                       String newNodePath = event.getPath();
-                                       Node newNode = null;
-                                       for (NodeIndexer nodeIndexer : nodeIndexers) {
-                                               try {
-                                                       if (nodeIndexer.support(newNodePath)) {
-                                                               if (newNode == null)
-                                                                       newNode = adminSession.getNode(newNodePath);
-                                                               nodeIndexer.index(newNode);
-                                                       }
-                                               } catch (RuntimeException e) {
-                                                       e.printStackTrace();
-                                                       throw e;
-                                               }
-                                       }
-                                       if (newNode != null)
-                                               adminSession.save();
-                               } catch (RepositoryException e) {
-                                       throw new SlcException("Cannot process event " + event, e);
-                               } finally {
-                                       JcrUtils.discardQuietly(adminSession);
-                               }
-                       }
-               }
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ConvertPoms_01_03.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ConvertPoms_01_03.java
deleted file mode 100644 (file)
index 12cf490..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.io.File;
-import java.util.HashMap;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/** Recursively migrate all the POMs to Argeo Distribution v1.3 */
-public class ConvertPoms_01_03 implements Runnable {
-       final String SPRING_SOURCE_PREFIX = "com.springsource";
-
-       private HashMap<String, String> artifactMapping = new HashMap<String, String>();
-
-       private File rootDir;
-
-       public ConvertPoms_01_03(String rootDirPath) {
-               this(new File(rootDirPath));
-       }
-
-       public ConvertPoms_01_03(File rootDir) {
-               this.rootDir = rootDir;
-
-               artifactMapping.put("org.argeo.dep.jacob", "com.jacob");
-               artifactMapping.put("org.argeo.dep.jacob.win32.x86",
-                               "com.jacob.win32.x86");
-               artifactMapping.put("org.argeo.dep.osgi.activemq",
-                               "org.apache.activemq");
-               artifactMapping.put("org.argeo.dep.osgi.activemq.optional",
-                               "org.apache.activemq.optional");
-               artifactMapping.put("org.argeo.dep.osgi.activemq.xmpp",
-                               "org.apache.activemq.xmpp");
-               artifactMapping.put("org.argeo.dep.osgi.aether", "org.sonatype.aether");
-               artifactMapping.put("org.argeo.dep.osgi.boilerpipe",
-                               "de.l3s.boilerpipe");
-               artifactMapping.put("org.argeo.dep.osgi.commons.cli",
-                               "org.apache.commons.cli");
-               artifactMapping.put("org.argeo.dep.osgi.commons.exec",
-                               "org.apache.commons.exec");
-               artifactMapping.put("org.argeo.dep.osgi.directory.shared.asn.codec",
-                               "org.apache.directory.shared.asn.codec");
-               artifactMapping.put("org.argeo.dep.osgi.drewnoakes.metadata_extractor",
-                               "com.drewnoakes.metadata_extractor");
-               artifactMapping.put("org.argeo.dep.osgi.geoapi", "org.opengis");
-               artifactMapping.put("org.argeo.dep.osgi.geotools", "org.geotools");
-               artifactMapping.put("org.argeo.dep.osgi.google.collections",
-                               "com.google.collections");
-               artifactMapping.put("org.argeo.dep.osgi.hibernatespatial",
-                               "org.hibernatespatial");
-               artifactMapping.put("org.argeo.dep.osgi.jackrabbit",
-                               "org.apache.jackrabbit");
-               artifactMapping.put("org.argeo.dep.osgi.jai.imageio",
-                               "com.sun.media.jai.imageio");
-               artifactMapping.put("org.argeo.dep.osgi.java3d", "javax.vecmath");
-               artifactMapping.put("org.argeo.dep.osgi.jcr", "javax.jcr");
-               artifactMapping.put("org.argeo.dep.osgi.jsr275", "javax.measure");
-               artifactMapping.put("org.argeo.dep.osgi.jts", "com.vividsolutions.jts");
-               artifactMapping.put("org.argeo.dep.osgi.mina.filter.ssl",
-                               "org.apache.mina.filter.ssl");
-               artifactMapping.put("org.argeo.dep.osgi.modeshape", "org.modeshape");
-               artifactMapping.put("org.argeo.dep.osgi.netcdf",
-                               "edu.ucar.unidata.netcdf");
-               artifactMapping.put("org.argeo.dep.osgi.pdfbox", "org.apache.pdfbox");
-               artifactMapping.put("org.argeo.dep.osgi.poi", "org.apache.poi");
-               artifactMapping.put("org.argeo.dep.osgi.postgis.jdbc",
-                               "org.postgis.jdbc");
-               artifactMapping.put("org.argeo.dep.osgi.springframework.ldap",
-                               "org.springframework.ldap");
-               artifactMapping.put("org.argeo.dep.osgi.tagsoup",
-                               "org.ccil.cowan.tagsoup");
-               artifactMapping.put("org.argeo.dep.osgi.tika", "org.apache.tika");
-       }
-
-       public void run() {
-               traverse(rootDir);
-       }
-
-       protected void traverse(File dir) {
-               for (File file : dir.listFiles()) {
-                       String fileName = file.getName();
-                       if (file.isDirectory() && !skipDirName(fileName)) {
-                               traverse(file);
-                       } else if (fileName.equals("pom.xml")) {
-                               processPom(file);
-                       }
-               }
-       }
-
-       protected Boolean skipDirName(String fileName) {
-               return fileName.equals(".svn") || fileName.equals("target")
-                               || fileName.equals("META-INF") || fileName.equals("src");
-       }
-
-       protected void processPom(File pomFile) {
-               try {
-                       Boolean wasChanged = false;
-                       DocumentBuilderFactory dbFactory = DocumentBuilderFactory
-                                       .newInstance();
-                       DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
-                       Document doc = dBuilder.parse(pomFile);
-                       doc.getDocumentElement().normalize();
-
-                       Element dependenciesElement = null;
-                       NodeList rootChildren = doc.getDocumentElement().getChildNodes();
-                       for (int temp = 0; temp < rootChildren.getLength(); temp++) {
-                               Node n = rootChildren.item(temp);
-                               if (n.getNodeName().equals("dependencies"))
-                                       dependenciesElement = (Element) n;
-                       }
-
-                       if (dependenciesElement != null) {
-                               stdOut("\n## " + pomFile);
-                               NodeList dependencyElements = dependenciesElement
-                                               .getElementsByTagName("dependency");
-
-                               for (int temp = 0; temp < dependencyElements.getLength(); temp++) {
-                                       Element eElement = (Element) dependencyElements.item(temp);
-                                       String groupId = getTagValue(eElement, "groupId");
-                                       String artifactId = getTagValue(eElement, "artifactId");
-                                       // stdOut(groupId + ":" + artifactId);
-
-                                       String newGroupId = null;
-                                       String newArtifactId = null;
-                                       if (groupId.startsWith("org.argeo.dep")) {
-                                               newGroupId = "org.argeo.tp";
-                                       } else if (!(groupId.startsWith("org.argeo")
-                                                       || groupId.startsWith("com.capco")
-                                                       || groupId.startsWith("com.agfa") || groupId
-                                                       .startsWith("org.ibboost"))) {
-                                               newGroupId = "org.argeo.tp";
-                                       }
-
-                                       if (artifactMapping.containsKey(artifactId)) {
-                                               newArtifactId = artifactMapping.get(artifactId);
-                                       } else if (artifactId.startsWith(SPRING_SOURCE_PREFIX)
-                                                       && !artifactId.equals(SPRING_SOURCE_PREFIX
-                                                                       + ".json")) {
-                                               newArtifactId = artifactId
-                                                               .substring(SPRING_SOURCE_PREFIX.length() + 1);
-                                       }
-
-                                       // modify
-                                       if (newGroupId != null || newArtifactId != null) {
-                                               if (newGroupId == null)
-                                                       newGroupId = groupId;
-                                               if (newArtifactId == null)
-                                                       newArtifactId = artifactId;
-                                               stdOut(groupId + ":" + artifactId + " => " + newGroupId
-                                                               + ":" + newArtifactId);
-                                               setTagValue(eElement, "groupId", newGroupId);
-                                               setTagValue(eElement, "artifactId", newArtifactId);
-                                               wasChanged = true;
-                                       }
-                               }
-                       }
-
-                       if (wasChanged) {
-                               // pomFile.renameTo(new File(pomFile.getParentFile(),
-                               // "pom-old.xml"));
-                               // save in place
-                               Source source = new DOMSource(doc);
-                               Result result = new StreamResult(pomFile);
-                               Transformer xformer = TransformerFactory.newInstance()
-                                               .newTransformer();
-                               xformer.transform(source, result);
-                       }
-               } catch (Exception e) {
-                       throw new RuntimeException("Cannot process " + pomFile, e);
-               }
-
-       }
-
-       private String getTagValue(Element eElement, String sTag) {
-               NodeList nList = eElement.getElementsByTagName(sTag);
-               if (nList.getLength() > 0) {
-                       NodeList nlList = nList.item(0).getChildNodes();
-                       Node nValue = (Node) nlList.item(0);
-                       return nValue.getNodeValue();
-               } else
-                       return null;
-       }
-
-       private void setTagValue(Element eElement, String sTag, String value) {
-               NodeList nList = eElement.getElementsByTagName(sTag);
-               if (nList.getLength() > 0) {
-                       NodeList nlList = nList.item(0).getChildNodes();
-                       Node nValue = (Node) nlList.item(0);
-                       nValue.setNodeValue(value);
-               }
-       }
-
-       public static void stdOut(Object obj) {
-               System.out.println(obj);
-       }
-
-       public static void main(String argv[]) {
-               new ConvertPoms_01_03(argv[0]).run();
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/GenerateBinaries.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/GenerateBinaries.java
deleted file mode 100644 (file)
index cd5283d..0000000
+++ /dev/null
@@ -1,584 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.ArtifactIdComparator;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.osgi.framework.Version;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Generates binaries-, sources- and sdk-version.pom artifacts for a given
- * group.
- */
-public class GenerateBinaries implements Runnable, SlcNames {
-       private final static Log log = LogFactory.getLog(GenerateBinaries.class);
-
-       // Connection info
-       private Repository repository;
-       private Credentials credentials;
-       private String workspace;
-
-       // Business info
-       private String groupId;
-       private String parentPomCoordinates;
-       private String version = null;
-
-       // Constants
-       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-       private List<String> excludedSuffixes = new ArrayList<String>();
-
-       // Indexes
-       private Set<Artifact> binaries = new TreeSet<Artifact>(
-                       new ArtifactIdComparator());
-       private Set<Artifact> sources = new TreeSet<Artifact>(
-                       new ArtifactIdComparator());
-
-       // local cache
-       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-       private Node allArtifactsHighestVersion;
-
-       public void run() {
-               Session session = null;
-               try {
-                       session = repository.login(credentials, workspace);
-                       Node groupNode = session.getNode(MavenConventionsUtils.groupPath(
-                                       artifactBasePath, groupId));
-                       internalPreProcessing(groupNode, null);
-                       internalProcessing(groupNode, null);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot normalize group " + groupId + " in "
-                                       + workspace, e);
-               } finally {
-                       JcrUtils.logoutQuietly(session);
-               }
-       }
-
-       /**
-        * Generates binaries-, sources- and sdk-version.pom artifacts for the given
-        * version (or the highest of all children version if none is precised).
-        * 
-        * By default, it includes each latest version of all artifact of this
-        * group.
-        * 
-        * The 3 generated artifacts are then marked as modular distributions and
-        * indexed.
-        */
-       public static void processGroupNode(Node groupNode, String version,
-                       ArgeoMonitor monitor) throws RepositoryException {
-               // TODO set artifactsBase based on group node
-               GenerateBinaries gb = new GenerateBinaries();
-               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
-                               .getString();
-               gb.setGroupId(groupId);
-               gb.setVersion(version);
-               // TODO use already done pre-processing
-               gb.internalPreProcessing(groupNode, monitor);
-               gb.internalProcessing(groupNode, monitor);
-       }
-
-       /** Only builds local indexes. Does not change anything in the local Session */
-       public static GenerateBinaries preProcessGroupNode(Node groupNode,
-                       ArgeoMonitor monitor) throws RepositoryException {
-               // TODO set artifactsBase based on group node
-               GenerateBinaries gb = new GenerateBinaries();
-               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
-                               .getString();
-               gb.setGroupId(groupId);
-               // gb.setVersion(version);
-               // gb.setOverridePoms(overridePoms);
-               gb.internalPreProcessing(groupNode, monitor);
-               return gb;
-       }
-
-       // exposes indexes. to display results of the pre-processing phase.
-       public Set<Artifact> getBinaries() {
-               return binaries;
-       }
-
-       public Artifact getHighestArtifactVersion() throws RepositoryException {
-               return allArtifactsHighestVersion == null ? null : RepoUtils
-                               .asArtifact(allArtifactsHighestVersion);
-       }
-
-       // //////////////////////////////////////
-       // INTERNAL METHODS
-
-       /**
-        * Browse all children of a Node considered as a folder that follows Aether
-        * conventions i.e that has Aether's artifact base as children.
-        * 
-        * Each of such child contains a set of Aether artifact versions. This
-        * methods build the binaries {@code Set<Artifact>} and other indexes. It
-        * does not impact the
-        */
-       protected void internalPreProcessing(Node groupNode, ArgeoMonitor monitor)
-                       throws RepositoryException {
-               if (monitor != null)
-                       monitor.subTask("Pre processing group " + groupId);
-
-               // Process all direct children nodes,
-               // gathering latest versions of each artifact
-               allArtifactsHighestVersion = null;
-
-               aBases: for (NodeIterator aBases = groupNode.getNodes(); aBases
-                               .hasNext();) {
-                       Node aBase = aBases.nextNode();
-                       if (aBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
-                               Node highestAVersion = getArtifactLatestVersion(aBase);
-                               if (highestAVersion == null)
-                                       continue aBases;
-                               else {
-                                       // retrieve relevant child node
-                                       // Information is stored on the NT_FILE child node.
-                                       for (NodeIterator files = highestAVersion.getNodes(); files
-                                                       .hasNext();) {
-                                               Node file = files.nextNode();
-                                               if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
-                                                       if (log.isDebugEnabled())
-                                                               log.debug("Pre-Processing " + file.getName());
-                                                       preProcessBundleArtifact(file);
-                                               }
-                                       }
-                               }
-                       }
-               }
-               // if (log.isDebugEnabled()) {
-               // int bundleCount = symbolicNamesToNodes.size();
-               // log.debug("" + bundleCount + " bundles have been indexed for "
-               // + groupId);
-               // }
-       }
-
-       /** Does the real job : writes JCR META-DATA and generates binaries */
-       protected void internalProcessing(Node groupNode, ArgeoMonitor monitor)
-                       throws RepositoryException {
-               if (monitor != null)
-                       monitor.subTask("Processing group " + groupId);
-
-               Session session = groupNode.getSession();
-
-               // if version not set or empty, use the highest version
-               // useful when indexing a product maven repository where
-               // all artifacts have the same version for a given release
-               // => the version can then be left empty
-               if (version == null || version.trim().equals(""))
-                       if (allArtifactsHighestVersion != null)
-                               version = allArtifactsHighestVersion.getProperty(
-                                               SLC_ARTIFACT_VERSION).getString();
-                       else
-                               throw new SlcException("Group version " + version
-                                               + " is empty.");
-
-               // int bundleCount = symbolicNamesToNodes.size();
-               // int count = 1;
-               // for (Node bundleNode : symbolicNamesToNodes.values()) {
-               // if (log.isDebugEnabled())
-               // log.debug("Processing " + bundleNode.getName() + " ( " + count
-               // + "/" + bundleCount + " )");
-               //
-               // // processBundleArtifact(bundleNode);
-               // // bundleNode.getSession().save();
-               // count++;
-               // }
-
-               // indexes
-               Set<Artifact> indexes = new TreeSet<Artifact>(
-                               new ArtifactIdComparator());
-
-               Artifact indexArtifact;
-               indexArtifact = writeIndex(session, RepoConstants.BINARIES_ARTIFACT_ID,
-                               binaries);
-               indexes.add(indexArtifact);
-
-               indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID,
-                               sources);
-               indexes.add(indexArtifact);
-
-               // sdk
-               writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
-
-               if (monitor != null)
-                       monitor.worked(1);
-       }
-
-       protected void preProcessBundleArtifact(Node bundleNode)
-                       throws RepositoryException {
-
-               String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
-               // Sanity check.
-               if (symbolicName == null)
-                       log.warn("Symbolic name is null for bundle " + bundleNode);
-
-               // Manage source bundles
-               if (symbolicName.endsWith(".source")) {
-                       // TODO make a shared node with classifier 'sources'?
-                       String bundleName = RepoUtils
-                                       .extractBundleNameFromSourceName(symbolicName);
-                       for (String excludedSuffix : excludedSuffixes) {
-                               if (bundleName.endsWith(excludedSuffix))
-                                       return;// skip adding to sources
-                       }
-                       sources.add(RepoUtils.asArtifact(bundleNode));
-                       return;
-               }
-
-               // // Build indexes
-               // NodeIterator exportPackages = bundleNode.getNodes(SLC_
-               // + Constants.EXPORT_PACKAGE);
-               // while (exportPackages.hasNext()) {
-               // Node exportPackage = exportPackages.nextNode();
-               // String pkg = JcrUtils.get(exportPackage, SLC_NAME);
-               // packagesToSymbolicNames.put(pkg, symbolicName);
-               // }
-               //
-               // symbolicNamesToNodes.put(symbolicName, bundleNode);
-               // for (String excludedSuffix : excludedSuffixes) {
-               // if (symbolicName.endsWith(excludedSuffix))
-               // return;// skip adding to binaries
-               // }
-
-               binaries.add(RepoUtils.asArtifact(bundleNode));
-
-               // Extra check. to remove
-               if (bundleNode.getSession().hasPendingChanges())
-                       throw new SlcException("Pending changes in the session, "
-                                       + "this should not be true here.");
-       }
-
-       // protected void processBundleArtifact(Node bundleNode)
-       // throws RepositoryException {
-       // Node artifactFolder = bundleNode.getParent();
-       // String baseName = FilenameUtils.getBaseName(bundleNode.getName());
-       //
-       // // pom
-       // String pomName = baseName + ".pom";
-       // if (artifactFolder.hasNode(pomName) && !overridePoms)
-       // return;// skip
-       //
-       // String pom = generatePomForBundle(bundleNode);
-       // Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
-       // pom.getBytes());
-       // // checksum
-       // String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
-       // JcrUtils.copyBytesAsFile(artifactFolder,
-       // bundleNode.getName() + ".sha1", bundleSha.getBytes());
-       // String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
-       // JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
-       // pomSha.getBytes());
-       // }
-
-       // ////////////////////
-       // LOCAL WRITERS
-       //
-
-       private Artifact writeIndex(Session session, String artifactId,
-                       Set<Artifact> artifacts) throws RepositoryException {
-               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
-                               version);
-               Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
-                               parentPomCoordinates) : null;
-               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
-                               artifacts, parentArtifact);
-               Node node = RepoUtils.copyBytesAsArtifact(
-                               session.getNode(artifactBasePath), artifact, pom.getBytes());
-               artifactIndexer.index(node);
-
-               // TODO factorize
-               String pomSha = JcrUtils.checksumFile(node, "SHA-1");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
-                               pomSha.getBytes());
-               String pomMd5 = JcrUtils.checksumFile(node, "MD5");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
-                               pomMd5.getBytes());
-               session.save();
-               return artifact;
-       }
-
-       // Helpers
-       private Node getArtifactLatestVersion(Node artifactBase) {
-               try {
-                       Node highestAVersion = null;
-                       for (NodeIterator aVersions = artifactBase.getNodes(); aVersions
-                                       .hasNext();) {
-                               Node aVersion = aVersions.nextNode();
-                               if (aVersion.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
-                                       if (highestAVersion == null) {
-                                               highestAVersion = aVersion;
-                                               if (allArtifactsHighestVersion == null)
-                                                       allArtifactsHighestVersion = aVersion;
-                                               // Correctly handle following arrival order:
-                                               // Name1 - V1, name2 - V3
-                                               else {
-                                                       Version cachedHighestVersion = extractOsgiVersion(allArtifactsHighestVersion);
-                                                       Version currVersion = extractOsgiVersion(aVersion);
-                                                       if (currVersion.compareTo(cachedHighestVersion) > 0)
-                                                               allArtifactsHighestVersion = aVersion;
-                                               }
-                                       } else {
-                                               Version currVersion = extractOsgiVersion(aVersion);
-                                               Version currentHighestVersion = extractOsgiVersion(highestAVersion);
-                                               if (currVersion.compareTo(currentHighestVersion) > 0) {
-                                                       highestAVersion = aVersion;
-                                               }
-                                               if (currVersion
-                                                               .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
-                                                       allArtifactsHighestVersion = aVersion;
-                                               }
-                                       }
-
-                               }
-                       }
-                       return highestAVersion;
-               } catch (RepositoryException re) {
-                       throw new SlcException("Unable to get latest version for node "
-                                       + artifactBase, re);
-               }
-       }
-
-       private Version extractOsgiVersion(Node artifactVersion)
-                       throws RepositoryException {
-               String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
-                               .getString();
-               String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
-               Version osgiVersion = null;
-               // log invalid version value to enable tracking them
-               try {
-                       osgiVersion = new Version(cleanVersion);
-               } catch (IllegalArgumentException e) {
-                       log.error("Version string " + cleanVersion + " is invalid ");
-                       String twickedVersion = twickInvalidVersion(cleanVersion);
-                       osgiVersion = new Version(twickedVersion);
-                       log.error("Using " + twickedVersion + " instead");
-                       // throw e;
-               }
-               return osgiVersion;
-       }
-
-       private String twickInvalidVersion(String tmpVersion) {
-               String[] tokens = tmpVersion.split("\\.");
-               if (tokens.length == 3 && tokens[2].lastIndexOf("-") > 0) {
-                       String newSuffix = tokens[2].replaceFirst("-", ".");
-                       tmpVersion = tmpVersion.replaceFirst(tokens[2], newSuffix);
-               } else if (tokens.length > 4) {
-                       // FIXME manually remove other "."
-                       StringTokenizer st = new StringTokenizer(tmpVersion, ".", true);
-                       StringBuilder builder = new StringBuilder();
-                       // Major
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Minor
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Micro
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Qualifier
-                       builder.append(st.nextToken());
-                       while (st.hasMoreTokens()) {
-                               // consume delimiter
-                               st.nextToken();
-                               if (st.hasMoreTokens())
-                                       builder.append("-").append(st.nextToken());
-                       }
-                       tmpVersion = builder.toString();
-               }
-               return tmpVersion;
-       }
-
-       // private String generatePomForBundle(Node n) throws RepositoryException {
-       // String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
-       //
-       // StringBuffer p = new StringBuffer();
-       //
-       // // XML header
-       // p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-       // p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
-       // p.append("<modelVersion>4.0.0</modelVersion>");
-       //
-       // // Artifact
-       // p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
-       // .append("</groupId>\n");
-       // p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
-       // .append("</artifactId>\n");
-       // p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
-       // .append("</version>\n");
-       // p.append("<packaging>pom</packaging>\n");
-       // if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
-       // p.append("<name>")
-       // .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
-       // .append("</name>\n");
-       // if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
-       // p.append("<description>")
-       // .append(JcrUtils
-       // .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
-       // .append("</description>\n");
-       //
-       // // Dependencies
-       // Set<String> dependenciesSymbolicNames = new TreeSet<String>();
-       // Set<String> optionalSymbolicNames = new TreeSet<String>();
-       // NodeIterator importPackages = n.getNodes(SLC_
-       // + Constants.IMPORT_PACKAGE);
-       // while (importPackages.hasNext()) {
-       // Node importPackage = importPackages.nextNode();
-       // String pkg = JcrUtils.get(importPackage, SLC_NAME);
-       // if (packagesToSymbolicNames.containsKey(pkg)) {
-       // String dependencySymbolicName = packagesToSymbolicNames
-       // .get(pkg);
-       // if (JcrUtils.check(importPackage, SLC_OPTIONAL))
-       // optionalSymbolicNames.add(dependencySymbolicName);
-       // else
-       // dependenciesSymbolicNames.add(dependencySymbolicName);
-       // } else {
-       // if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
-       // && !systemPackages.contains(pkg))
-       // log.warn("No bundle found for pkg " + pkg);
-       // }
-       // }
-       //
-       // if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
-       // String fragmentHost = JcrUtils.get(
-       // n.getNode(SLC_ + Constants.FRAGMENT_HOST),
-       // SLC_SYMBOLIC_NAME);
-       // dependenciesSymbolicNames.add(fragmentHost);
-       // }
-       //
-       // // TODO require bundles
-       //
-       // List<Node> dependencyNodes = new ArrayList<Node>();
-       // for (String depSymbName : dependenciesSymbolicNames) {
-       // if (depSymbName.equals(ownSymbolicName))
-       // continue;// skip self
-       //
-       // if (symbolicNamesToNodes.containsKey(depSymbName))
-       // dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
-       // else
-       // log.warn("Could not find node for " + depSymbName);
-       // }
-       // List<Node> optionalDependencyNodes = new ArrayList<Node>();
-       // for (String depSymbName : optionalSymbolicNames) {
-       // if (symbolicNamesToNodes.containsKey(depSymbName))
-       // optionalDependencyNodes.add(symbolicNamesToNodes
-       // .get(depSymbName));
-       // else
-       // log.warn("Could not find node for " + depSymbName);
-       // }
-       //
-       // p.append("<dependencies>\n");
-       // for (Node dependencyNode : dependencyNodes) {
-       // p.append("<dependency>\n");
-       // p.append("\t<groupId>")
-       // .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
-       // .append("</groupId>\n");
-       // p.append("\t<artifactId>")
-       // .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
-       // .append("</artifactId>\n");
-       // p.append("</dependency>\n");
-       // }
-       //
-       // if (optionalDependencyNodes.size() > 0)
-       // p.append("<!-- OPTIONAL -->\n");
-       // for (Node dependencyNode : optionalDependencyNodes) {
-       // p.append("<dependency>\n");
-       // p.append("\t<groupId>")
-       // .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
-       // .append("</groupId>\n");
-       // p.append("\t<artifactId>")
-       // .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
-       // .append("</artifactId>\n");
-       // p.append("\t<optional>true</optional>\n");
-       // p.append("</dependency>\n");
-       // }
-       // p.append("</dependencies>\n");
-       //
-       // // Dependency management
-       // p.append("<dependencyManagement>\n");
-       // p.append("<dependencies>\n");
-       // p.append("<dependency>\n");
-       // p.append("\t<groupId>").append(groupId).append("</groupId>\n");
-       // p.append("\t<artifactId>")
-       // .append(ownSymbolicName.endsWith(".source") ?
-       // RepoConstants.SOURCES_ARTIFACT_ID
-       // : RepoConstants.BINARIES_ARTIFACT_ID)
-       // .append("</artifactId>\n");
-       // p.append("\t<version>").append(version).append("</version>\n");
-       // p.append("\t<type>pom</type>\n");
-       // p.append("\t<scope>import</scope>\n");
-       // p.append("</dependency>\n");
-       // p.append("</dependencies>\n");
-       // p.append("</dependencyManagement>\n");
-       //
-       // p.append("</project>\n");
-       // return p.toString();
-       // }
-
-       /* SETTERS */
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setCredentials(Credentials credentials) {
-               this.credentials = credentials;
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-       public void setGroupId(String groupId) {
-               this.groupId = groupId;
-       }
-
-       public void setParentPomCoordinates(String parentPomCoordinates) {
-               this.parentPomCoordinates = parentPomCoordinates;
-       }
-
-       public void setArtifactBasePath(String artifactBasePath) {
-               this.artifactBasePath = artifactBasePath;
-       }
-
-       public void setVersion(String version) {
-               this.version = version;
-       }
-
-       public void setExcludedSuffixes(List<String> excludedSuffixes) {
-               this.excludedSuffixes = excludedSuffixes;
-       }
-
-       public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
-               this.artifactIndexer = artifactIndexer;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ImportMavenDependencies.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/ImportMavenDependencies.java
deleted file mode 100644 (file)
index d1245ff..0000000
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherTemplate;
-import org.argeo.slc.aether.ArtifactIdComparator;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.JarFileIndexer;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.graph.DependencyNode;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Import all the dependencies listed in a POM and their dependency graphs to a
- * workspace.
- */
-public class ImportMavenDependencies implements Runnable {
-       private final static Log log = LogFactory
-                       .getLog(ImportMavenDependencies.class);
-
-       private AetherTemplate aetherTemplate;
-       private String rootCoordinates = "org.argeo.dep:versions-all:pom:1.2.0";
-       private String distCoordinates = "org.argeo.tp:dist:pom:1.3.0";
-       private String parentPomCoordinates = "org.argeo:parent:1.2.0";
-       private Set<String> excludedArtifacts = new HashSet<String>();
-
-       private Repository repository;
-       private String workspace;
-
-       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-
-       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
-       private Comparator<Artifact> artifactComparator = new ArtifactIdComparator();
-
-       public void run() {
-               // resolve
-               Set<Artifact> artifacts = resolveDistribution();
-
-               // sync
-               sync(artifacts);
-       }
-
-       void sync(Set<Artifact> artifacts) {
-               Session session = null;
-               try {
-                       session = JcrUtils.loginOrCreateWorkspace(repository, workspace);
-                       // clear
-                       NodeIterator nit = session.getNode(artifactBasePath).getNodes();
-                       while (nit.hasNext()) {
-                               Node node = nit.nextNode();
-                               if (node.isNodeType(NodeType.NT_FOLDER)
-                                               || node.isNodeType(NodeType.NT_UNSTRUCTURED))
-                                       node.remove();
-                       }
-                       session.save();
-
-                       // sync
-                       syncDistribution(session, artifacts);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot import distribution", e);
-               } finally {
-                       JcrUtils.logoutQuietly(session);
-               }
-       }
-
-       /**
-        * Generate a POM with all the artifacts declared in root coordinates as
-        * dependencies AND in dependency management.
-        */
-       void createDistPom() {
-               try {
-                       Artifact pomArtifact = new DefaultArtifact(rootCoordinates);
-
-                       Set<Artifact> registeredArtifacts = new TreeSet<Artifact>(
-                                       artifactComparator);
-                       MavenConventionsUtils.gatherPomDependencies(aetherTemplate,
-                                       registeredArtifacts, pomArtifact);
-                       Artifact sdkArtifact = new DefaultArtifact(distCoordinates);
-                       String sdkPom = MavenConventionsUtils.artifactsAsDependencyPom(
-                                       sdkArtifact, registeredArtifacts, new DefaultArtifact(
-                                                       parentPomCoordinates));
-                       if (log.isDebugEnabled())
-                               log.debug("Gathered " + registeredArtifacts.size()
-                                               + " artifacts:\n" + sdkPom);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot resolve distribution", e);
-               }
-       }
-
-       /** Returns all transitive dependencies of dist POM */
-       private Set<Artifact> resolveDistribution() {
-               try {
-                       Artifact distArtifact = new DefaultArtifact(distCoordinates);
-                       Set<Artifact> artifacts = new TreeSet<Artifact>(artifactComparator);
-
-                       DependencyNode node = aetherTemplate
-                                       .resolveDependencies(distArtifact);
-                       addDependencies(artifacts, node, null);
-
-                       if (log.isDebugEnabled()) {
-                               log.debug("Resolved " + artifacts.size() + " artifacts");
-
-                               // Properties distributionDescriptor =
-                               // generateDistributionDescriptor(artifacts);
-                               // ByteArrayOutputStream out = new ByteArrayOutputStream();
-                               // distributionDescriptor.store(out, "");
-                               // log.debug(new String(out.toByteArray()));
-                               // out.close();
-                       }
-
-                       /*
-                        * for (Artifact artifact : registeredArtifacts) { try { Boolean
-                        * wasAdded = addArtifact(artifacts, artifact); if (wasAdded) {
-                        * DependencyNode node = aetherTemplate
-                        * .resolveDependencies(artifact); addDependencies(artifacts, node,
-                        * null); } } catch (Exception e) {
-                        * log.error("Could not resolve dependencies of " + artifact + ": "
-                        * + e.getCause().getMessage()); }
-                        * 
-                        * }
-                        * 
-                        * if (log.isDebugEnabled()) log.debug("Resolved " +
-                        * artifacts.size() + " artifacts");
-                        * 
-                        * // distribution descriptor // Properties distributionDescriptor =
-                        * // generateDistributionDescriptor(artifacts); //
-                        * ByteArrayOutputStream out = new ByteArrayOutputStream(); //
-                        * distributionDescriptor.store(out, ""); // log.debug(new
-                        * String(out.toByteArray())); // out.close();
-                        */
-                       return artifacts;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot resolve distribution", e);
-               }
-       }
-
-       protected Properties generateDistributionDescriptor(Set<Artifact> artifacts) {
-               Properties distributionDescriptor = new Properties();
-               for (Artifact artifact : artifacts) {
-                       log.debug(artifact.getArtifactId() + " [" + artifact.getVersion()
-                                       + "]\t(" + artifact + ")");
-                       distributionDescriptor.setProperty(artifact.getArtifactId() + ":"
-                                       + artifact.getVersion(), artifact.toString());
-               }
-               return distributionDescriptor;
-       }
-
-       /** Write artifacts to the target workspace, skipping excluded ones */
-       protected void syncDistribution(Session jcrSession, Set<Artifact> artifacts) {
-               Set<Artifact> artifactsWithoutSources = new TreeSet<Artifact>(
-                               artifactComparator);
-               Long begin = System.currentTimeMillis();
-               try {
-                       JcrUtils.mkfolders(jcrSession, artifactBasePath);
-                       artifacts: for (Artifact artifact : artifacts) {
-                               // skip excluded
-                               if (excludedArtifacts.contains(artifact.getGroupId() + ":"
-                                               + artifact.getArtifactId())) {
-                                       if (log.isDebugEnabled())
-                                               log.debug("Exclude " + artifact);
-                                       continue artifacts;
-                               }
-
-                               File jarFile = MavenConventionsUtils.artifactToFile(artifact);
-                               if (!jarFile.exists()) {
-                                       log.warn("Generated file " + jarFile + " for " + artifact
-                                                       + " does not exist");
-                                       continue artifacts;
-                               }
-                               artifact.setFile(jarFile);
-
-                               try {
-                                       String parentPath = MavenConventionsUtils
-                                                       .artifactParentPath(artifactBasePath, artifact);
-                                       Node parentNode;
-                                       if (!jcrSession.itemExists(parentPath))
-                                               parentNode = JcrUtils.mkfolders(jcrSession, parentPath);
-                                       else
-                                               parentNode = jcrSession.getNode(parentPath);
-
-                                       Node fileNode;
-                                       if (!parentNode.hasNode(jarFile.getName())) {
-                                               fileNode = createFileNode(parentNode, jarFile);
-                                       } else {
-                                               fileNode = parentNode.getNode(jarFile.getName());
-                                       }
-
-                                       if (artifactIndexer.support(fileNode.getPath()))
-                                               artifactIndexer.index(fileNode);
-                                       if (jarFileIndexer.support(fileNode.getPath()))
-                                               jarFileIndexer.index(fileNode);
-                                       jcrSession.save();
-
-                                       addPdeSource(jcrSession, artifact, jarFile,
-                                                       artifactsWithoutSources);
-                                       jcrSession.save();
-
-                                       if (log.isDebugEnabled())
-                                               log.debug("Synchronized " + fileNode);
-                               } catch (Exception e) {
-                                       log.error("Could not synchronize " + artifact, e);
-                                       jcrSession.refresh(false);
-                                       throw e;
-                               }
-                       }
-
-                       Long duration = (System.currentTimeMillis() - begin) / 1000;
-                       if (log.isDebugEnabled()) {
-                               log.debug("Synchronized distribution in " + duration + "s");
-                               log.debug("The following artifacts have no sources:");
-                               for (Artifact artifact : artifactsWithoutSources) {
-                                       log.debug(artifact);
-                               }
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot synchronize distribution", e);
-               }
-       }
-
-       /** Try to add PDE sources */
-       private void addPdeSource(Session session, Artifact artifact,
-                       File artifactFile, Set<Artifact> artifactsWithoutSources) {
-               ByteArrayOutputStream out = new ByteArrayOutputStream();
-               try {
-                       File origSourceFile = null;
-                       Artifact origSourceArtifact = new DefaultArtifact(
-                                       artifact.getGroupId(), artifact.getArtifactId(), "sources",
-                                       artifact.getExtension(), artifact.getVersion());
-                       Artifact newSourceArtifact = new DefaultArtifact(
-                                       artifact.getGroupId(),
-                                       artifact.getArtifactId() + ".source",
-                                       artifact.getExtension(), artifact.getVersion());
-                       try {
-                               origSourceFile = aetherTemplate
-                                               .getResolvedFile(origSourceArtifact);
-                       } catch (Exception e) {
-                               // also try artifact following the conventions
-                               origSourceArtifact = newSourceArtifact;
-                               origSourceFile = aetherTemplate
-                                               .getResolvedFile(origSourceArtifact);
-                       }
-
-                       String newSourceParentPath = MavenConventionsUtils
-                                       .artifactParentPath(artifactBasePath, newSourceArtifact);
-                       Node newSourceParentNode = JcrUtils.mkfolders(session,
-                                       newSourceParentPath);
-                       NameVersion bundleNameVersion = RepoUtils
-                                       .readNameVersion(artifactFile);
-                       RepoUtils.packagesAsPdeSource(origSourceFile, bundleNameVersion,
-                                       out);
-                       String newSourceFileName = MavenConventionsUtils
-                                       .artifactFileName(newSourceArtifact);
-                       JcrUtils.copyBytesAsFile(newSourceParentNode, newSourceFileName,
-                                       out.toByteArray());
-               } catch (Exception e) {
-                       log.error("Cannot add PDE source for " + artifact + ": " + e);
-                       artifactsWithoutSources.add(artifact);
-               } finally {
-                       IOUtils.closeQuietly(out);
-               }
-       }
-
-       private Node createFileNode(Node parentNode, File file) {
-               return JcrUtils.copyFile(parentNode, file);
-       }
-
-       /** Recursively adds non optional dependencies */
-       private void addDependencies(Set<Artifact> artifacts, DependencyNode node,
-                       String ancestors) {
-               // if (artifacts.contains(node.getDependency().getArtifact()))
-               // return;
-               String currentArtifactId = node.getDependency().getArtifact()
-                               .getArtifactId();
-               if (log.isDebugEnabled()) {
-                       log.debug("# Add dependency for " + currentArtifactId);
-                       if (ancestors != null)
-                               log.debug(ancestors);
-               }
-               for (DependencyNode child : node.getChildren()) {
-                       if (!child.getDependency().isOptional()) {
-                               if (willAdd(child.getDependency().getArtifact())) {
-                                       addArtifact(artifacts, child.getDependency().getArtifact());
-                                       addDependencies(artifacts, child, currentArtifactId + "\n"
-                                                       + (ancestors != null ? ancestors : ""));
-                               }
-                       }
-               }
-       }
-
-       /** @return whether it was added */
-       private Boolean addArtifact(Set<Artifact> artifacts, Artifact artifact) {
-               Boolean willAdd = willAdd(artifact);
-               if (willAdd)
-                       artifacts.add(artifact);
-               else
-                       log.info("Skip " + artifact);
-               return willAdd;
-       }
-
-       private Boolean willAdd(Artifact artifact) {
-               Boolean willAdd = true;
-               if (excludedArtifacts.contains(artifact.getGroupId() + ":"
-                               + artifact.getArtifactId()))
-                       willAdd = false;
-               else if (excludedArtifacts.contains(artifact.getGroupId() + ":*"))
-                       willAdd = false;
-               return willAdd;
-       }
-
-       public void setAetherTemplate(AetherTemplate aetherTemplate) {
-               this.aetherTemplate = aetherTemplate;
-       }
-
-       public void setExcludedArtifacts(Set<String> excludedArtifactIds) {
-               this.excludedArtifacts = excludedArtifactIds;
-       }
-
-       public void setRootCoordinates(String rootCoordinates) {
-               this.rootCoordinates = rootCoordinates;
-       }
-
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-       public void setDistCoordinates(String distCoordinates) {
-               this.distCoordinates = distCoordinates;
-       }
-
-       public void setArtifactBasePath(String artifactBasePath) {
-               this.artifactBasePath = artifactBasePath;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/IndexDistribution.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/IndexDistribution.java
deleted file mode 100644 (file)
index 758316d..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.io.File;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.RepoConstants;
-import org.sonatype.aether.artifact.Artifact;
-
-/** Create a distribution node from a set of artifacts */
-public class IndexDistribution implements Runnable {
-       private final static Log log = LogFactory.getLog(IndexDistribution.class);
-       private Repository repository;
-       private String workspace;
-
-       private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-       private String distributionsBasePath = RepoConstants.DISTRIBUTIONS_BASE_PATH;
-       private String distributionName;
-
-       public void run() {
-               // TODO populate
-               Set<Artifact> artifacts = new HashSet<Artifact>();
-
-               // sync
-               Session session = null;
-               try {
-                       session = repository.login(workspace);
-                       syncDistribution(session, artifacts);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot import distribution", e);
-               } finally {
-                       JcrUtils.logoutQuietly(session);
-               }
-       }
-
-       protected void syncDistribution(Session jcrSession, Set<Artifact> artifacts) {
-               Long begin = System.currentTimeMillis();
-               try {
-                       JcrUtils.mkdirs(jcrSession, distributionsBasePath + '/'
-                                       + distributionName);
-                       artifacts: for (Artifact artifact : artifacts) {
-                               File file = artifact.getFile();
-                               if (file == null) {
-                                       file = MavenConventionsUtils.artifactToFile(artifact);
-                                       if (!file.exists()) {
-                                               log.warn("Generated file " + file + " for " + artifact
-                                                               + " does not exist");
-                                               continue artifacts;
-                                       }
-                               }
-
-                               try {
-                                       String parentPath = artifactBasePath
-                                                       + (artifactBasePath.endsWith("/") ? "" : "/")
-                                                       + artifactParentPath(artifact);
-                                       Node parentNode = jcrSession.getNode(parentPath);
-                                       Node fileNode = parentNode.getNode(file.getName());
-
-                                       if (fileNode.hasProperty(SlcNames.SLC_SYMBOLIC_NAME)) {
-                                               String distPath = bundleDistributionPath(fileNode);
-                                               if (!jcrSession.itemExists(distPath)
-                                                               && fileNode
-                                                                               .isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT))
-                                                       jcrSession.getWorkspace().clone(
-                                                                       jcrSession.getWorkspace().getName(),
-                                                                       fileNode.getPath(), distPath, false);
-                                               if (log.isDebugEnabled())
-                                                       log.debug("Indexed " + fileNode);
-                                       }
-                               } catch (Exception e) {
-                                       log.error("Could not index " + artifact, e);
-                                       jcrSession.refresh(false);
-                                       throw e;
-                               }
-                       }
-
-                       Long duration = (System.currentTimeMillis() - begin) / 1000;
-                       if (log.isDebugEnabled())
-                               log.debug("Indexed distribution in " + duration + "s");
-               } catch (Exception e) {
-                       throw new SlcException("Cannot synchronize distribution", e);
-               }
-       }
-
-       private String artifactParentPath(Artifact artifact) {
-               return artifact.getGroupId().replace('.', '/') + '/'
-                               + artifact.getArtifactId() + '/' + artifact.getVersion();
-       }
-
-       private String bundleDistributionPath(Node fileNode) {
-               try {
-                       return distributionsBasePath
-                                       + '/'
-                                       + distributionName
-                                       + '/'
-                                       + fileNode.getProperty(SlcNames.SLC_SYMBOLIC_NAME)
-                                                       .getString()
-                                       + '_'
-                                       + fileNode.getProperty(SlcNames.SLC_BUNDLE_VERSION)
-                                                       .getString();
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot create distribution path for "
-                                       + fileNode, e);
-               }
-       }
-
-       public void setDistributionName(String distributionName) {
-               this.distributionName = distributionName;
-       }
-
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenConventionsUtils.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenConventionsUtils.java
deleted file mode 100644 (file)
index 4e8d3fb..0000000
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.io.File;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherTemplate;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-/**
- * Static utilities around Maven which are NOT using the Maven APIs (conventions
- * based).
- */
-public class MavenConventionsUtils {
-       private final static Log log = LogFactory
-                       .getLog(MavenConventionsUtils.class);
-
-       /**
-        * Path to the file identified by this artifact <b>without</b> using Maven
-        * APIs (convention based). Default location of repository
-        * (~/.m2/repository) is used here.
-        * 
-        * @see MavenConventionsUtils#artifactToFile(String, Artifact)
-        */
-       public static File artifactToFile(Artifact artifact) {
-               return artifactToFile(System.getProperty("user.home") + File.separator
-                               + ".m2" + File.separator + "repository", artifact);
-       }
-
-       /**
-        * Path to the file identified by this artifact <b>without</b> using Maven
-        * APIs (convention based).
-        * 
-        * @param repositoryPath
-        *            path to the related local repository location
-        * @param artifact
-        *            the artifact
-        */
-       public static File artifactToFile(String repositoryPath, Artifact artifact) {
-               return new File(repositoryPath + File.separator
-                               + artifact.getGroupId().replace('.', File.separatorChar)
-                               + File.separator + artifact.getArtifactId() + File.separator
-                               + artifact.getVersion() + File.separator
-                               + artifactFileName(artifact)).getAbsoluteFile();
-       }
-
-       /** The file name of this artifact when stored */
-       public static String artifactFileName(Artifact artifact) {
-               return artifact.getArtifactId()
-                               + '-'
-                               + artifact.getVersion()
-                               + (artifact.getClassifier().equals("") ? "" : '-' + artifact
-                                               .getClassifier()) + '.' + artifact.getExtension();
-       }
-
-       /** Absolute path to the file */
-       public static String artifactPath(String artifactBasePath, Artifact artifact) {
-               return artifactParentPath(artifactBasePath, artifact) + '/'
-                               + artifactFileName(artifact);
-       }
-
-       /** Absolute path to the directories where the files will be stored */
-       public static String artifactParentPath(String artifactBasePath,
-                       Artifact artifact) {
-               return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/")
-                               + artifactParentPath(artifact);
-       }
-
-       /** Absolute path to the directory of this group */
-       public static String groupPath(String artifactBasePath, String groupId) {
-               return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/")
-                               + groupId.replace('.', '/');
-       }
-
-       /** Relative path to the directories where the files will be stored */
-       public static String artifactParentPath(Artifact artifact) {
-               return artifact.getGroupId().replace('.', '/') + '/'
-                               + artifact.getArtifactId() + '/' + artifact.getBaseVersion();
-       }
-
-       public static String artifactsAsDependencyPom(Artifact pomArtifact,
-                       Set<Artifact> artifacts, Artifact parent) {
-               StringBuffer p = new StringBuffer();
-
-               // XML header
-               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
-               p.append("<modelVersion>4.0.0</modelVersion>\n");
-
-               // Artifact
-               if (parent != null) {
-                       p.append("<parent>\n");
-                       p.append("<groupId>").append(parent.getGroupId())
-                                       .append("</groupId>\n");
-                       p.append("<artifactId>").append(parent.getArtifactId())
-                                       .append("</artifactId>\n");
-                       p.append("<version>").append(parent.getVersion())
-                                       .append("</version>\n");
-                       p.append("</parent>\n");
-               }
-               p.append("<groupId>").append(pomArtifact.getGroupId())
-                               .append("</groupId>\n");
-               p.append("<artifactId>").append(pomArtifact.getArtifactId())
-                               .append("</artifactId>\n");
-               p.append("<version>").append(pomArtifact.getVersion())
-                               .append("</version>\n");
-               p.append("<packaging>pom</packaging>\n");
-
-               // Dependencies
-               p.append("<dependencies>\n");
-               for (Artifact a : artifacts) {
-                       p.append("\t<dependency>");
-                       p.append("<artifactId>").append(a.getArtifactId())
-                                       .append("</artifactId>");
-                       p.append("<groupId>").append(a.getGroupId()).append("</groupId>");
-                       if (!a.getExtension().equals("jar"))
-                               p.append("<type>").append(a.getExtension()).append("</type>");
-                       p.append("</dependency>\n");
-               }
-               p.append("</dependencies>\n");
-
-               // Dependency management
-               p.append("<dependencyManagement>\n");
-               p.append("<dependencies>\n");
-               for (Artifact a : artifacts) {
-                       p.append("\t<dependency>");
-                       p.append("<artifactId>").append(a.getArtifactId())
-                                       .append("</artifactId>");
-                       p.append("<version>").append(a.getVersion()).append("</version>");
-                       p.append("<groupId>").append(a.getGroupId()).append("</groupId>");
-                       if (a.getExtension().equals("pom")) {
-                               p.append("<type>").append(a.getExtension()).append("</type>");
-                               p.append("<scope>import</scope>");
-                       }
-                       p.append("</dependency>\n");
-               }
-               p.append("</dependencies>\n");
-               p.append("</dependencyManagement>\n");
-
-               // Repositories
-               // p.append("<repositories>\n");
-               // p.append("<repository><id>argeo</id><url>http://maven.argeo.org/argeo</url></repository>\n");
-               // p.append("</repositories>\n");
-
-               p.append("</project>\n");
-               return p.toString();
-       }
-
-       /**
-        * Directly parses Maven POM XML format in order to find all artifacts
-        * references under the dependency and dependencyManagement tags. This is
-        * meant to migrate existing pom registering a lot of artifacts, not to
-        * replace Maven resolving.
-        */
-       public static void gatherPomDependencies(AetherTemplate aetherTemplate,
-                       Set<Artifact> artifacts, Artifact pomArtifact) {
-               if (log.isDebugEnabled())
-                       log.debug("Gather dependencies for " + pomArtifact);
-
-               try {
-                       File file = aetherTemplate.getResolvedFile(pomArtifact);
-                       DocumentBuilder documentBuilder = DocumentBuilderFactory
-                                       .newInstance().newDocumentBuilder();
-                       Document doc = documentBuilder.parse(file);
-
-                       // properties
-                       Properties props = new Properties();
-                       props.setProperty("project.version", pomArtifact.getBaseVersion());
-                       NodeList properties = doc.getElementsByTagName("properties");
-                       if (properties.getLength() > 0) {
-                               NodeList propertiesElems = properties.item(0).getChildNodes();
-                               for (int i = 0; i < propertiesElems.getLength(); i++) {
-                                       if (propertiesElems.item(i) instanceof Element) {
-                                               Element property = (Element) propertiesElems.item(i);
-                                               props.put(property.getNodeName(),
-                                                               property.getTextContent());
-                                       }
-                               }
-                       }
-
-                       // dependencies (direct and dependencyManagement)
-                       NodeList dependencies = doc.getElementsByTagName("dependency");
-                       for (int i = 0; i < dependencies.getLength(); i++) {
-                               Element dependency = (Element) dependencies.item(i);
-                               String groupId = dependency.getElementsByTagName("groupId")
-                                               .item(0).getTextContent().trim();
-                               String artifactId = dependency
-                                               .getElementsByTagName("artifactId").item(0)
-                                               .getTextContent().trim();
-                               String version = dependency.getElementsByTagName("version")
-                                               .item(0).getTextContent().trim();
-                               if (version.startsWith("${")) {
-                                       String versionKey = version.substring(0,
-                                                       version.length() - 1).substring(2);
-                                       if (!props.containsKey(versionKey))
-                                               throw new SlcException("Cannot interpret version "
-                                                               + version);
-                                       version = props.getProperty(versionKey);
-                               }
-                               NodeList scopes = dependency.getElementsByTagName("scope");
-                               if (scopes.getLength() > 0
-                                               && scopes.item(0).getTextContent().equals("import")) {
-                                       // recurse
-                                       gatherPomDependencies(aetherTemplate, artifacts,
-                                                       new DefaultArtifact(groupId, artifactId, "pom",
-                                                                       version));
-                               } else {
-                                       // TODO: deal with scope?
-                                       // TODO: deal with type
-                                       String type = "jar";
-                                       Artifact artifact = new DefaultArtifact(groupId,
-                                                       artifactId, type, version);
-                                       artifacts.add(artifact);
-                               }
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot process " + pomArtifact, e);
-               }
-       }
-
-       /** Prevent instantiation */
-       private MavenConventionsUtils() {
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/MavenProxyServiceImpl.java
deleted file mode 100644 (file)
index fcd65d9..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.security.AccessControlException;
-import javax.jcr.security.Privilege;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.proxy.AbstractUrlProxy;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.MavenProxyService;
-import org.argeo.slc.repo.RepoConstants;
-import org.sonatype.aether.repository.RemoteRepository;
-
-/** Synchronises the node repository with remote Maven repositories */
-public class MavenProxyServiceImpl extends AbstractUrlProxy implements
-               MavenProxyService, ArgeoNames, SlcNames {
-       private final static Log log = LogFactory
-                       .getLog(MavenProxyServiceImpl.class);
-
-       private List<RemoteRepository> defaultRepositories = new ArrayList<RemoteRepository>();
-
-       /** Initialises the artifacts area. */
-       @Override
-       protected void beforeInitSessionSave(Session session)
-                       throws RepositoryException {
-               JcrUtils.addPrivilege(session, "/", SlcConstants.USER_ANONYMOUS, Privilege.JCR_READ);
-               try {
-                       JcrUtils.addPrivilege(session, "/", SlcConstants.ROLE_SLC,
-                                       Privilege.JCR_ALL);
-               } catch (AccessControlException e) {
-                       if (log.isTraceEnabled())
-                               log.trace("Cannot give jcr:all privileges to "
-                                               + SlcConstants.ROLE_SLC);
-               }
-
-               JcrUtils.mkdirsSafe(session, RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH);
-               Node proxiedRepositories = JcrUtils.mkdirsSafe(session,
-                               RepoConstants.PROXIED_REPOSITORIES);
-               for (RemoteRepository repository : defaultRepositories) {
-                       if (!proxiedRepositories.hasNode(repository.getId())) {
-                               Node proxiedRepository = proxiedRepositories.addNode(repository
-                                               .getId());
-                               proxiedRepository.addMixin(NodeType.MIX_REFERENCEABLE);
-                               JcrUtils.urlToAddressProperties(proxiedRepository,
-                                               repository.getUrl());
-                               // proxiedRepository.setProperty(SLC_URL, repository.getUrl());
-                               proxiedRepository.setProperty(SLC_TYPE,
-                                               repository.getContentType());
-                       }
-               }
-       }
-
-       /**
-        * Retrieve and add this file to the repository
-        */
-       @Override
-       protected Node retrieve(Session session, String path) {
-               try {
-                       if (session.hasPendingChanges())
-                               throw new SlcException("Session has pending changed");
-                       Node node = null;
-                       for (Node proxiedRepository : getBaseUrls(session)) {
-                               String baseUrl = JcrUtils
-                                               .urlFromAddressProperties(proxiedRepository);
-                               node = proxyUrl(session, baseUrl, path);
-                               if (node != null) {
-                                       node.addMixin(SlcTypes.SLC_KNOWN_ORIGIN);
-                                       Node origin = node
-                                                       .addNode(SLC_ORIGIN, SlcTypes.SLC_PROXIED);
-                                       origin.setProperty(SLC_PROXY, proxiedRepository);
-                                       JcrUtils.urlToAddressProperties(origin, baseUrl + path);
-                                       if (log.isDebugEnabled())
-                                               log.debug("Imported " + baseUrl + path + " to " + node);
-                                       return node;
-                               }
-                       }
-                       if (log.isDebugEnabled())
-                               log.warn("No proxy found for " + path);
-                       return null;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot proxy " + path, e);
-               }
-       }
-
-       protected synchronized List<Node> getBaseUrls(Session session)
-                       throws RepositoryException {
-               List<Node> baseUrls = new ArrayList<Node>();
-               for (NodeIterator nit = session.getNode(
-                               RepoConstants.PROXIED_REPOSITORIES).getNodes(); nit.hasNext();) {
-                       Node proxiedRepository = nit.nextNode();
-                       baseUrls.add(proxiedRepository);
-               }
-               return baseUrls;
-       }
-
-       public void setDefaultRepositories(
-                       List<RemoteRepository> defaultRepositories) {
-               this.defaultRepositories = defaultRepositories;
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/Migration_01_03.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/maven/Migration_01_03.java
deleted file mode 100644 (file)
index baf6ec7..0000000
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.maven;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.jar.Attributes.Name;
-import java.util.jar.Manifest;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.qom.Ordering;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.JarFileIndexer;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.osgi.OsgiProfile;
-import org.osgi.framework.Constants;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Migrate the distribution from 1.2 to 1.4 by cleaning naming and dependencies.
- * The dependency to the SpringSource Enterprise Bundle repository is removed as
- * well as their naming conventions. All third party are move to org.argeo.tp
- * group IDs. Maven dependency for Eclipse artifacts don't use version ranges
- * anymore. Verison constraints on javax.* packages are removed (since they lead
- * to "use package conflicts" when Eclipse and Spring Security are used
- * together).
- */
-public class Migration_01_03 implements Runnable, SlcNames {
-       final String SPRING_SOURCE_PREFIX = "com.springsource";
-       private final static Log log = LogFactory.getLog(Migration_01_03.class);
-
-       private Repository repository;
-       private String sourceWorkspace;
-       private String targetWorkspace;
-
-       private List<String> excludedBundles = new ArrayList<String>();
-       private Map<String, String> symbolicNamesMapping = new HashMap<String, String>();
-
-       private Session origSession;
-       private Session targetSession;
-
-       private List<String> systemPackages = OsgiProfile.PROFILE_JAVA_SE_1_6
-                       .getSystemPackages();
-
-       private String artifactBasePath = "/";
-
-       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
-
-       public void init() throws RepositoryException {
-               origSession = JcrUtils.loginOrCreateWorkspace(repository,
-                               sourceWorkspace);
-               targetSession = JcrUtils.loginOrCreateWorkspace(repository,
-                               targetWorkspace);
-
-               // works only in OSGi!!
-               // systemPackages = Arrays.asList(System.getProperty(
-               // "org.osgi.framework.system.packages").split(","));
-       }
-
-       public void destroy() {
-               JcrUtils.logoutQuietly(origSession);
-               JcrUtils.logoutQuietly(targetSession);
-       }
-
-       public void run() {
-
-               try {
-                       // clear target
-                       NodeIterator nit = targetSession.getNode(artifactBasePath)
-                                       .getNodes();
-                       while (nit.hasNext()) {
-                               Node node = nit.nextNode();
-                               if (node.isNodeType(NodeType.NT_FOLDER)
-                                               || node.isNodeType(NodeType.NT_UNSTRUCTURED)) {
-                                       node.remove();
-                                       node.getSession().save();
-                                       if (log.isDebugEnabled())
-                                               log.debug("Cleared " + node);
-                               }
-                       }
-
-                       NodeIterator origArtifacts = listArtifactVersions(origSession);
-                       // process
-                       while (origArtifacts.hasNext()) {
-                               Node origArtifactNode = origArtifacts.nextNode();
-                               if (log.isTraceEnabled())
-                                       log.trace(origArtifactNode);
-
-                               processOrigArtifactVersion(origArtifactNode);
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot perform v1.3 migration from "
-                                       + sourceWorkspace + " to " + targetWorkspace, e);
-               } finally {
-                       JcrUtils.discardQuietly(targetSession);
-               }
-       }
-
-       protected void processOrigArtifactVersion(Node origArtifactNode)
-                       throws RepositoryException, IOException {
-               Artifact origArtifact = RepoUtils.asArtifact(origArtifactNode);
-
-               // skip eclipse artifacts
-               if ((origArtifact.getGroupId().startsWith("org.eclipse") && !(origArtifact
-                               .getArtifactId().equals("org.eclipse.osgi")
-                               || origArtifact.getArtifactId().equals(
-                                               "org.eclipse.osgi.source") || origArtifact
-                               .getArtifactId().startsWith("org.eclipse.rwt.widgets.upload")))
-                               || origArtifact.getArtifactId().startsWith("com.ibm.icu")) {
-                       if (log.isDebugEnabled())
-                               log.debug("Skip " + origArtifact);
-                       return;
-               }
-
-               // skip SpringSource ActiveMQ
-               if (origArtifact.getArtifactId().startsWith(
-                               "com.springsource.org.apache.activemq"))
-                       return;
-
-               String origJarNodeName = MavenConventionsUtils
-                               .artifactFileName(origArtifact);
-               if (!origArtifactNode.hasNode(origJarNodeName))
-                       throw new SlcException("Cannot find jar node for "
-                                       + origArtifactNode);
-               Node origJarNode = origArtifactNode.getNode(origJarNodeName);
-
-               // read MANIFEST
-               Binary manifestBinary = origJarNode.getProperty(SLC_MANIFEST)
-                               .getBinary();
-               Manifest origManifest = new Manifest(manifestBinary.getStream());
-               JcrUtils.closeQuietly(manifestBinary);
-
-               Boolean manifestModified = false;
-               Manifest targetManifest = new Manifest(origManifest);
-
-               // transform symbolic name
-               String origSymbolicName = origManifest.getMainAttributes().getValue(
-                               Constants.BUNDLE_SYMBOLICNAME);
-               final String targetSymbolicName;
-               if (symbolicNamesMapping.containsKey(origSymbolicName)) {
-                       targetSymbolicName = symbolicNamesMapping.get(origSymbolicName);
-               } else if (origSymbolicName.startsWith(SPRING_SOURCE_PREFIX)
-                               && !origSymbolicName.equals(SPRING_SOURCE_PREFIX + ".json")) {
-                       targetSymbolicName = origSymbolicName
-                                       .substring(SPRING_SOURCE_PREFIX.length() + 1);
-               } else {
-                       targetSymbolicName = origSymbolicName;
-               }
-
-               if (!targetSymbolicName.equals(origSymbolicName)) {
-                       targetManifest.getMainAttributes().putValue(
-                                       Constants.BUNDLE_SYMBOLICNAME, targetSymbolicName);
-                       manifestModified = true;
-                       if (log.isDebugEnabled())
-                               log.debug(Constants.BUNDLE_SYMBOLICNAME + " to "
-                                               + targetSymbolicName + " \t\tfrom " + origSymbolicName);
-               }
-
-               // skip excluded bundles
-               if (excludedBundles.contains(targetSymbolicName))
-                       return;
-
-               // check fragment host
-               if (origManifest.getMainAttributes().containsKey(
-                               new Name(Constants.FRAGMENT_HOST))) {
-                       String origFragmentHost = origManifest.getMainAttributes()
-                                       .getValue(Constants.FRAGMENT_HOST);
-                       String targetFragmentHost;
-                       if (symbolicNamesMapping.containsKey(origFragmentHost)) {
-                               targetFragmentHost = symbolicNamesMapping.get(origFragmentHost);
-                       } else if (origFragmentHost.startsWith(SPRING_SOURCE_PREFIX)
-                                       && !origFragmentHost.equals(SPRING_SOURCE_PREFIX + ".json")) {
-                               targetFragmentHost = origFragmentHost
-                                               .substring(SPRING_SOURCE_PREFIX.length() + 1);
-                       } else if (origFragmentHost
-                                       .equals("org.argeo.dep.jacob;bundle-version=\"[1.14.3,1.14.4)\"")) {
-                               // this one for those who think I cannot be pragmatic - mbaudier
-                               targetFragmentHost = "com.jacob;bundle-version=\"[1.14.3,1.14.4)\"";
-                       } else {
-                               targetFragmentHost = origFragmentHost;
-                       }
-
-                       if (!targetFragmentHost.equals(origFragmentHost)) {
-                               targetManifest.getMainAttributes().putValue(
-                                               Constants.FRAGMENT_HOST, targetFragmentHost);
-                               manifestModified = true;
-                               if (log.isDebugEnabled())
-                                       log.debug(Constants.FRAGMENT_HOST + " to "
-                                                       + targetFragmentHost + " from " + origFragmentHost);
-                       }
-               }
-
-               // we assume there is no Require-Bundle in com.springsource.* bundles
-
-               // javax with versions
-               StringBuffer targetImportPackages = new StringBuffer("");
-               NodeIterator origImportPackages = origJarNode.getNodes(SLC_
-                               + Constants.IMPORT_PACKAGE);
-               Boolean importPackagesModified = false;
-               while (origImportPackages.hasNext()) {
-                       Node importPackage = origImportPackages.nextNode();
-                       String pkg = importPackage.getProperty(SLC_NAME).getString();
-                       targetImportPackages.append(pkg);
-                       if (importPackage.hasProperty(SLC_VERSION)) {
-                               String sourceVersion = importPackage.getProperty(SLC_VERSION)
-                                               .getString();
-                               String targetVersion = sourceVersion;
-                               if (systemPackages.contains(pkg)) {
-                                       if (!(sourceVersion.trim().equals("0") || sourceVersion
-                                                       .trim().equals("0.0.0"))) {
-                                               targetVersion = null;
-                                               importPackagesModified = true;
-                                               if (log.isDebugEnabled())
-                                                       log.debug(origSymbolicName
-                                                                       + ": Nullify version of " + pkg + " from "
-                                                                       + sourceVersion);
-                                       }
-                               }
-                               if (targetVersion != null)
-                                       targetImportPackages.append(";version=\"")
-                                                       .append(targetVersion).append("\"");
-                       }
-                       if (importPackage.hasProperty(SLC_OPTIONAL)) {
-                               Boolean optional = importPackage.getProperty(SLC_OPTIONAL)
-                                               .getBoolean();
-                               if (optional)
-                                       targetImportPackages.append(";resolution:=\"optional\"");
-
-                       }
-                       if (origImportPackages.hasNext())
-                               targetImportPackages.append(",");
-               }
-
-               if (importPackagesModified) {
-                       targetManifest.getMainAttributes().putValue(
-                                       Constants.IMPORT_PACKAGE, targetImportPackages.toString());
-                       manifestModified = true;
-               }
-
-               if (!manifestModified && log.isTraceEnabled()) {
-                       log.trace("MANIFEST of " + origSymbolicName + " was not modified");
-               }
-
-               // target coordinates
-               final String targetGroupId;
-               if (origArtifact.getArtifactId().startsWith(
-                               "org.eclipse.rwt.widgets.upload"))
-                       targetGroupId = "org.argeo.tp.rap";
-               else if (origArtifact.getArtifactId().startsWith("org.polymap"))
-                       targetGroupId = "org.argeo.tp.rap";
-               else if (origArtifact.getGroupId().startsWith("org.eclipse")
-                               && !origArtifact.getArtifactId().equals("org.eclipse.osgi"))
-                       throw new SlcException(origArtifact + " should have been excluded");// targetGroupId
-                                                                                                                                                               // =
-                                                                                                                                                               // "org.argeo.tp.eclipse";
-               else
-                       targetGroupId = "org.argeo.tp";
-
-               String targetArtifactId = targetSymbolicName.split(";")[0];
-               Artifact targetArtifact = new DefaultArtifact(targetGroupId,
-                               targetArtifactId, "jar", origArtifact.getVersion());
-               String targetParentPath = MavenConventionsUtils.artifactParentPath(
-                               artifactBasePath, targetArtifact);
-               String targetFileName = MavenConventionsUtils
-                               .artifactFileName(targetArtifact);
-               String targetJarPath = targetParentPath + '/' + targetFileName;
-
-               // copy
-               Node targetParentNode = JcrUtils.mkfolders(targetSession,
-                               targetParentPath);
-               targetSession.save();
-               if (manifestModified) {
-                       Binary origBinary = origJarNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary();
-                       byte[] targetJarBytes = RepoUtils.modifyManifest(
-                                       origBinary.getStream(), targetManifest);
-                       JcrUtils.copyBytesAsFile(targetParentNode, targetFileName,
-                                       targetJarBytes);
-                       JcrUtils.closeQuietly(origBinary);
-               } else {// just copy
-                       targetSession.getWorkspace().copy(sourceWorkspace,
-                                       origJarNode.getPath(), targetJarPath);
-               }
-               targetSession.save();
-
-               // reindex
-               Node targetJarNode = targetSession.getNode(targetJarPath);
-               artifactIndexer.index(targetJarNode);
-               jarFileIndexer.index(targetJarNode);
-
-               targetSession.save();
-
-               // sources
-               Artifact origSourceArtifact = new DefaultArtifact(
-                               origArtifact.getGroupId(), origArtifact.getArtifactId()
-                                               + ".source", "jar", origArtifact.getVersion());
-               String origSourcePath = MavenConventionsUtils.artifactPath(
-                               artifactBasePath, origSourceArtifact);
-               if (origSession.itemExists(origSourcePath)) {
-                       Node origSourceJarNode = origSession.getNode(origSourcePath);
-
-                       Artifact targetSourceArtifact = new DefaultArtifact(targetGroupId,
-                                       targetArtifactId + ".source", "jar",
-                                       origArtifact.getVersion());
-                       String targetSourceParentPath = MavenConventionsUtils
-                                       .artifactParentPath(artifactBasePath, targetSourceArtifact);
-                       String targetSourceFileName = MavenConventionsUtils
-                                       .artifactFileName(targetSourceArtifact);
-                       String targetSourceJarPath = targetSourceParentPath + '/'
-                                       + targetSourceFileName;
-
-                       Node targetSourceParentNode = JcrUtils.mkfolders(targetSession,
-                                       targetSourceParentPath);
-                       targetSession.save();
-
-                       if (!targetSymbolicName.equals(origSymbolicName)) {
-                               Binary origBinary = origSourceJarNode.getNode(Node.JCR_CONTENT)
-                                               .getProperty(Property.JCR_DATA).getBinary();
-                               NameVersion targetNameVersion = RepoUtils
-                                               .readNameVersion(targetManifest);
-                               byte[] targetJarBytes = RepoUtils.packageAsPdeSource(
-                                               origBinary.getStream(), targetNameVersion);
-                               JcrUtils.copyBytesAsFile(targetSourceParentNode,
-                                               targetSourceFileName, targetJarBytes);
-                               JcrUtils.closeQuietly(origBinary);
-                       } else {// just copy
-                               targetSession.getWorkspace().copy(sourceWorkspace,
-                                               origSourceJarNode.getPath(), targetSourceJarPath);
-                       }
-                       targetSession.save();
-
-                       // reindex
-                       Node targetSourceJarNode = targetSession
-                                       .getNode(targetSourceJarPath);
-                       artifactIndexer.index(targetSourceJarNode);
-                       jarFileIndexer.index(targetSourceJarNode);
-
-                       targetSession.save();
-               }
-       }
-
-       /*
-        * UTILITIES
-        */
-
-       static NodeIterator listArtifactVersions(Session session)
-                       throws RepositoryException {
-               QueryManager queryManager = session.getWorkspace().getQueryManager();
-               QueryObjectModelFactory factory = queryManager.getQOMFactory();
-
-               final String artifactVersionsSelector = "artifactVersions";
-               Selector source = factory.selector(SlcTypes.SLC_ARTIFACT_VERSION_BASE,
-                               artifactVersionsSelector);
-
-               Ordering orderByArtifactId = factory.ascending(factory.propertyValue(
-                               artifactVersionsSelector, SlcNames.SLC_ARTIFACT_ID));
-               Ordering[] orderings = { orderByArtifactId };
-
-               QueryObjectModel query = factory.createQuery(source, null, orderings,
-                               null);
-
-               QueryResult result = query.execute();
-               return result.getNodes();
-       }
-
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setSourceWorkspace(String sourceWorkspace) {
-               this.sourceWorkspace = sourceWorkspace;
-       }
-
-       public void setTargetWorkspace(String targetWorkspace) {
-               this.targetWorkspace = targetWorkspace;
-       }
-
-       public void setExcludedBundles(List<String> excludedBundles) {
-               this.excludedBundles = excludedBundles;
-       }
-
-       public void setSymbolicNamesMapping(Map<String, String> symbolicNamesMapping) {
-               this.symbolicNamesMapping = symbolicNamesMapping;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveSourcesProvider.java
deleted file mode 100644 (file)
index ab52c70..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.jar.JarEntry;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.OsgiFactory;
-
-public class ArchiveSourcesProvider implements SourcesProvider {
-       private final static Log log = LogFactory
-                       .getLog(ArchiveSourcesProvider.class);
-
-       private OsgiFactory osgiFactory;
-       private String uri;
-       private String base = "";
-
-       @Override
-       public void writeSources(List<String> packages, ZipOutputStream zout) {
-               Session distSession = null;
-               ZipInputStream zin = null;
-               try {
-                       distSession = osgiFactory.openDistSession();
-
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapping " + uri);
-
-                       Node distNode = osgiFactory.getDist(distSession, uri);
-                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
-
-                       // prepare
-                       Set<String> directories = new TreeSet<String>();
-                       for (String pkg : packages)
-                               if (!pkg.equals("META-INF"))
-                                       directories.add(base + pkg.replace('.', '/') + '/');
-
-                       ZipEntry zentry = null;
-                       entries: while ((zentry = zin.getNextEntry()) != null) {
-                               String name = zentry.getName();
-                               if (!name.startsWith(base))
-                                       continue entries;
-
-                               String dirPath = FilenameUtils.getPath(name);
-                               if (name.equals(dirPath))// directory
-                                       continue entries;
-
-                               if (directories.contains(dirPath)) {
-                                       String path = name.substring(base.length());
-                                       zout.putNextEntry(new JarEntry(path));
-                                       IOUtils.copy(zin, zout);
-                                       zin.closeEntry();
-                                       zout.closeEntry();
-                                       continue entries;
-                               }
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot retrieve sources from " + uri, e);
-               } finally {
-                       IOUtils.closeQuietly(zin);
-                       JcrUtils.logoutQuietly(distSession);
-               }
-
-       }
-
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-
-       public void setUri(String uri) {
-               this.uri = uri;
-       }
-
-       public void setBase(String base) {
-               this.base = base;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveWrapper.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArchiveWrapper.java
deleted file mode 100644 (file)
index 29fa8f1..0000000
+++ /dev/null
@@ -1,439 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.jar.JarInputStream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.ModuleSet;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.ArtifactIdComparator;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.build.License;
-import org.argeo.slc.repo.OsgiFactory;
-import org.argeo.slc.repo.RepoUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-import org.springframework.util.AntPathMatcher;
-import org.springframework.util.PathMatcher;
-
-import aQute.lib.osgi.Jar;
-
-/**
- * Download a software distribution and generates the related OSGi bundles from
- * the jars, or import them directly if they are already OSGi bundles and don't
- * need further modification.
- */
-public class ArchiveWrapper implements Runnable, ModuleSet, Distribution {
-       private final static Log log = LogFactory.getLog(ArchiveWrapper.class);
-
-       private OsgiFactory osgiFactory;
-       private String version;
-       private License license;
-
-       private String uri;
-
-       /** Jars to wrap as OSGi bundles */
-       private Map<String, BndWrapper> wrappers = new HashMap<String, BndWrapper>();
-
-       private SourcesProvider sourcesProvider;
-
-       // pattern of OSGi bundles to import
-       private PathMatcher pathMatcher = new AntPathMatcher();
-       private Map<String, String> includes = new HashMap<String, String>();
-       private List<String> excludes = new ArrayList<String>();
-
-       private Boolean mavenGroupIndexes = false;
-
-       public void init() {
-               for (BndWrapper wrapper : wrappers.values()) {
-                       wrapper.setFactory(this);
-                       if (version != null && wrapper.getVersion() == null)
-                               wrapper.setVersion(version);
-                       if (license != null && wrapper.getLicense() == null)
-                               wrapper.setLicense(license);
-               }
-       }
-
-       public void destroy() {
-
-       }
-
-       public String getDistributionId() {
-               return uri;
-       }
-
-       public Iterator<? extends NameVersion> nameVersions() {
-               if (wrappers.size() > 0)
-                       return wrappers.values().iterator();
-               else
-                       return osgiNameVersions();
-       }
-
-       @SuppressWarnings("resource")
-       protected Iterator<? extends NameVersion> osgiNameVersions() {
-               List<CategorizedNameVersion> nvs = new ArrayList<CategorizedNameVersion>();
-
-               Session distSession = null;
-               ZipInputStream zin = null;
-               try {
-                       distSession = osgiFactory.openDistSession();
-
-                       Node distNode = osgiFactory.getDist(distSession, uri);
-                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
-
-                       ZipEntry zentry = null;
-                       entries: while ((zentry = zin.getNextEntry()) != null) {
-                               String name = zentry.getName();
-                               if (log.isTraceEnabled())
-                                       log.trace("Zip entry " + name);
-                               for (String exclude : excludes)
-                                       if (pathMatcher.match(exclude, name))
-                                               continue entries;
-
-                               for (String include : includes.keySet()) {
-                                       if (pathMatcher.match(include, name)) {
-                                               String groupId = includes.get(include);
-                                               JarInputStream jis = new JarInputStream(zin);
-                                               if (jis.getManifest() == null) {
-                                                       log.warn("No MANIFEST in entry " + name
-                                                                       + ", skipping...");
-                                                       continue entries;
-                                               }
-                                               NameVersion nv = RepoUtils.readNameVersion(jis
-                                                               .getManifest());
-                                               if (nv != null) {
-                                                       if (nv.getName().endsWith(".source"))
-                                                               continue entries;
-                                                       CategorizedNameVersion cnv = new OsgiCategorizedNV(
-                                                                       groupId, nv.getName(), nv.getVersion(),
-                                                                       this);
-                                                       nvs.add(cnv);
-                                                       // no need to process further includes
-                                                       continue entries;
-                                               }
-                                       }
-                               }
-                       }
-                       return nvs.iterator();
-               } catch (Exception e) {
-                       throw new SlcException("Cannot wrap distribution " + uri, e);
-               } finally {
-                       IOUtils.closeQuietly(zin);
-                       JcrUtils.logoutQuietly(distSession);
-               }
-       }
-
-       public void run() {
-               if (mavenGroupIndexes && (version == null))
-                       throw new SlcException(
-                                       "'mavenGroupIndexes' requires 'version' to be set");
-
-               Map<String, Set<Artifact>> binaries = new HashMap<String, Set<Artifact>>();
-               Map<String, Set<Artifact>> sources = new HashMap<String, Set<Artifact>>();
-
-               Session distSession = null;
-               Session javaSession = null;
-               ZipInputStream zin = null;
-               try {
-                       javaSession = osgiFactory.openJavaSession();
-                       distSession = osgiFactory.openDistSession();
-
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapping " + uri);
-                       boolean nothingWasDone = true;
-
-                       Node distNode = osgiFactory.getDist(distSession, uri);
-                       zin = new ZipInputStream(distNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream());
-
-                       ZipEntry zentry = null;
-                       entries: while ((zentry = zin.getNextEntry()) != null) {
-                               String name = zentry.getName();
-
-                               // sources autodetect
-                               String baseName = FilenameUtils.getBaseName(name);
-                               if (baseName.endsWith("-sources")) {
-                                       String bundle = baseName.substring(0, baseName.length()
-                                                       - "-sources".length());
-                                       // log.debug(name + "," + baseName + ", " + bundle);
-                                       String bundlePath = FilenameUtils.getPath(name) + bundle
-                                                       + ".jar";
-                                       if (wrappers.containsKey(bundlePath)) {
-                                               BndWrapper wrapper = wrappers.get(bundlePath);
-                                               NameVersion bundleNv = new DefaultNameVersion(
-                                                               wrapper.getName(), wrapper.getVersion());
-                                               byte[] pdeSource = RepoUtils.packageAsPdeSource(zin,
-                                                               bundleNv);
-                                               Artifact sourcesArtifact = new DefaultArtifact(
-                                                               wrapper.getCategory(), wrapper.getName()
-                                                                               + ".source", "jar",
-                                                               wrapper.getVersion());
-                                               Node pdeSourceNode = RepoUtils.copyBytesAsArtifact(
-                                                               javaSession.getRootNode(), sourcesArtifact,
-                                                               pdeSource);
-                                               osgiFactory.indexNode(pdeSourceNode);
-                                               pdeSourceNode.getSession().save();
-                                               if (log.isDebugEnabled())
-                                                       log.debug("Added sources " + sourcesArtifact
-                                                                       + " for bundle " + wrapper.getArtifact()
-                                                                       + "from " + name + " in binary archive.");
-                                       }
-
-                               }
-                               // else if (baseName.endsWith(".source")) {
-                               // }
-
-                               // binaries
-                               if (wrappers.containsKey(name)) {
-                                       BndWrapper wrapper = (BndWrapper) wrappers.get(name);
-                                       // we must copy since the stream is closed by BND
-                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
-                                       Artifact artifact = wrapZipEntry(javaSession, zentry,
-                                                       origJarBytes, wrapper);
-                                       nothingWasDone = false;
-                                       addArtifactToIndex(binaries, wrapper.getGroupId(), artifact);
-                               } else {
-                                       for (String wrapperKey : wrappers.keySet())
-                                               if (pathMatcher.match(wrapperKey, name)) {
-                                                       // first matched is taken
-                                                       BndWrapper wrapper = (BndWrapper) wrappers
-                                                                       .get(wrapperKey);
-                                                       // we must copy since the stream is closed by BND
-                                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
-                                                       Artifact artifact = wrapZipEntry(javaSession,
-                                                                       zentry, origJarBytes, wrapper);
-                                                       nothingWasDone = false;
-                                                       addArtifactToIndex(binaries, wrapper.getGroupId(),
-                                                                       artifact);
-                                                       continue entries;
-                                               } else {
-                                                       if (log.isTraceEnabled())
-                                                               log.trace(name + " not matched by "
-                                                                               + wrapperKey);
-                                               }
-
-                                       for (String exclude : excludes)
-                                               if (pathMatcher.match(exclude, name))
-                                                       continue entries;
-
-                                       for (String include : includes.keySet()) {
-                                               if (pathMatcher.match(include, name)) {
-                                                       String groupId = includes.get(include);
-                                                       byte[] origJarBytes = IOUtils.toByteArray(zin);
-                                                       Artifact artifact = importZipEntry(javaSession,
-                                                                       zentry, origJarBytes, groupId);
-                                                       if (artifact == null) {
-                                                               log.warn("Skipped non identified " + zentry);
-                                                               continue entries;
-                                                       }
-                                                       nothingWasDone = false;
-                                                       if (artifact.getArtifactId().endsWith(".source"))
-                                                               addArtifactToIndex(sources, groupId, artifact);
-                                                       else
-                                                               addArtifactToIndex(binaries, groupId, artifact);
-                                                       // no need to process this entry further
-                                                       continue entries;
-                                               }
-                                       }
-                               }
-                       }
-
-                       // indexes
-                       if (mavenGroupIndexes && version != null) {
-                               for (String groupId : binaries.keySet()) {
-                                       RepoUtils.writeGroupIndexes(javaSession, "/", groupId,
-                                                       version, binaries.get(groupId),
-                                                       sources.containsKey(groupId) ? sources.get(groupId)
-                                                                       : null);
-                               }
-                       }
-
-                       if (nothingWasDone)
-                               throw new SlcException("Nothing was done");
-
-                       // FIXME Fail if not all wrappers matched
-               } catch (Exception e) {
-                       throw new SlcException("Cannot wrap distribution " + uri, e);
-               } finally {
-                       IOUtils.closeQuietly(zin);
-                       JcrUtils.logoutQuietly(distSession);
-                       JcrUtils.logoutQuietly(javaSession);
-               }
-       }
-
-       protected Artifact wrapZipEntry(Session javaSession, ZipEntry zentry,
-                       byte[] origJarBytes, BndWrapper wrapper) throws RepositoryException {
-               ByteArrayOutputStream out = null;
-               ByteArrayInputStream in = null;
-               Node newJarNode;
-               Jar jar = null;
-               try {
-                       out = new ByteArrayOutputStream((int) zentry.getSize());
-                       in = new ByteArrayInputStream(origJarBytes);
-                       wrapper.wrapJar(in, out);
-
-                       Artifact artifact = wrapper.getArtifact();
-                       newJarNode = RepoUtils.copyBytesAsArtifact(
-                                       javaSession.getRootNode(), artifact, out.toByteArray());
-                       osgiFactory.indexNode(newJarNode);
-                       newJarNode.getSession().save();
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapped jar " + zentry.getName() + " to "
-                                               + newJarNode.getPath());
-
-                       if (sourcesProvider != null)
-                               addSource(javaSession, artifact, out.toByteArray());
-
-                       return artifact;
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-                       if (jar != null)
-                               jar.close();
-               }
-       }
-
-       protected void addSource(Session javaSession, Artifact artifact,
-                       byte[] binaryJarBytes) {
-               InputStream in = null;
-               ByteArrayOutputStream out = null;
-               Jar jar = null;
-               try {
-                       in = new ByteArrayInputStream(binaryJarBytes);
-                       jar = new Jar(null, in);
-                       List<String> packages = jar.getPackages();
-
-                       out = new ByteArrayOutputStream();
-                       sourcesProvider.writeSources(packages, new ZipOutputStream(out));
-
-                       IOUtils.closeQuietly(in);
-                       in = new ByteArrayInputStream(out.toByteArray());
-                       byte[] sourcesJar = RepoUtils.packageAsPdeSource(
-                                       in,
-                                       new DefaultNameVersion(artifact.getArtifactId(), artifact
-                                                       .getVersion()));
-                       Artifact sourcesArtifact = new DefaultArtifact(
-                                       artifact.getGroupId(),
-                                       artifact.getArtifactId() + ".source", "jar",
-                                       artifact.getVersion());
-                       Node sourcesJarNode = RepoUtils.copyBytesAsArtifact(
-                                       javaSession.getRootNode(), sourcesArtifact, sourcesJar);
-                       sourcesJarNode.getSession().save();
-
-                       if (log.isDebugEnabled())
-                               log.debug("Added sources " + sourcesArtifact + " for bundle "
-                                               + artifact + "from source provider " + sourcesProvider);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot get sources for " + artifact, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-                       if (jar != null)
-                               jar.close();
-               }
-       }
-
-       protected Artifact importZipEntry(Session javaSession, ZipEntry zentry,
-                       byte[] binaryJarBytes, String groupId) throws RepositoryException {
-               ByteArrayInputStream in = null;
-               Node newJarNode;
-               try {
-                       in = new ByteArrayInputStream(binaryJarBytes);
-                       NameVersion nameVersion = RepoUtils.readNameVersion(in);
-                       if (nameVersion == null) {
-                               log.warn("Cannot identify " + zentry.getName());
-                               return null;
-                       }
-                       Artifact artifact = new DefaultArtifact(groupId,
-                                       nameVersion.getName(), "jar", nameVersion.getVersion());
-                       newJarNode = RepoUtils.copyBytesAsArtifact(
-                                       javaSession.getRootNode(), artifact, binaryJarBytes);
-                       osgiFactory.indexNode(newJarNode);
-                       newJarNode.getSession().save();
-                       if (log.isDebugEnabled())
-                               log.debug("Imported OSGi bundle " + zentry.getName() + " to "
-                                               + newJarNode.getPath());
-
-                       if (sourcesProvider != null)
-                               addSource(javaSession, artifact, binaryJarBytes);
-
-                       return artifact;
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       private void addArtifactToIndex(Map<String, Set<Artifact>> index,
-                       String groupId, Artifact artifact) {
-               if (!index.containsKey(groupId))
-                       index.put(groupId,
-                                       new TreeSet<Artifact>(new ArtifactIdComparator()));
-               index.get(groupId).add(artifact);
-       }
-
-       public void setUri(String uri) {
-               this.uri = uri;
-       }
-
-       public void setWrappers(Map<String, BndWrapper> wrappers) {
-               this.wrappers = wrappers;
-       }
-
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-
-       public void setVersion(String version) {
-               this.version = version;
-       }
-
-       public void setLicense(License license) {
-               this.license = license;
-       }
-
-       public void setPathMatcher(PathMatcher pathMatcher) {
-               this.pathMatcher = pathMatcher;
-       }
-
-       public void setIncludes(Map<String, String> includes) {
-               this.includes = includes;
-       }
-
-       public void setExcludes(List<String> excludes) {
-               this.excludes = excludes;
-       }
-
-       public void setMavenGroupIndexes(Boolean mavenGroupIndexes) {
-               this.mavenGroupIndexes = mavenGroupIndexes;
-       }
-
-       public void setSourcesProvider(SourcesProvider sourcesProvider) {
-               this.sourcesProvider = sourcesProvider;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ArgeoOsgiDistributionImpl.java
deleted file mode 100644 (file)
index b47da8b..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.ModuleSet;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.repo.ArgeoOsgiDistribution;
-import org.argeo.slc.repo.ArtifactDistribution;
-
-/** A consistent and versioned OSGi distribution, which can be built and tested. */
-public class ArgeoOsgiDistributionImpl extends ArtifactDistribution implements
-               ArgeoOsgiDistribution {
-       private final static Log log = LogFactory
-                       .getLog(ArgeoOsgiDistributionImpl.class);
-
-       private List<Object> modules = new ArrayList<Object>();
-
-       public ArgeoOsgiDistributionImpl(String coords) {
-               super(coords);
-       }
-
-       public void init() {
-               if (log.isDebugEnabled()) {
-                       SortedSet<String> sort = new TreeSet<String>();
-                       Iterator<? extends NameVersion> nvIt = nameVersions();
-                       while (nvIt.hasNext()) {
-                               NameVersion nv = nvIt.next();
-                               sort.add(nv.getName() + ":" + nv.getVersion());
-                       }
-
-                       StringBuffer buf = new StringBuffer(
-                                       "## OSGi FACTORY MANAGED MODULES : \n");
-                       for (String str : sort) {
-                               buf.append(str).append('\n');
-                       }
-
-                       log.debug(buf);
-               }
-       }
-
-       // private static void print(ModuleSet moduleSet, Integer depth) {
-       // StringBuilder prefix = new StringBuilder();
-       // for (int i = 0; i < depth; i++) {
-       // prefix.append(' ');
-       // }
-       // String p = prefix.toString();
-       // prefix.setLength(0);
-       // log.debug(p + "## " + moduleSet.toString());
-       // Iterator<? extends NameVersion> nvIt = moduleSet.nameVersions();
-       // while (nvIt.hasNext()) {
-       // NameVersion nv = nvIt.next();
-       // if (nv instanceof ModuleSet)
-       // print((ModuleSet) nv, depth + 1);
-       // else
-       // log.debug(p + nv);
-       //
-       // }
-       // }
-
-       public void destroy() {
-
-       }
-
-       public Iterator<NameVersion> nameVersions() {
-               List<NameVersion> nameVersions = new ArrayList<NameVersion>();
-               for (Object module : modules) {
-                       // extract runnable from execution flow
-                       if (module instanceof ExecutionFlow) {
-                               for (Iterator<Runnable> it = ((ExecutionFlow) module)
-                                               .runnables(); it.hasNext();) {
-                                       processModule(nameVersions, it.next());
-                               }
-                       }
-                       // module = ((ExecutionFlow) module).getRunnable();
-                       else {
-                               processModule(nameVersions, module);
-                       }
-                       // if (module instanceof ModuleSet)
-                       // addNameVersions(nameVersions, (ModuleSet) module);
-                       // else if (module instanceof NameVersion) {
-                       // NameVersion nv = (NameVersion) module;
-                       // if (!nameVersions.contains(nv))
-                       // nameVersions.add(nv);
-                       // } else
-                       // log.warn("Ignored " + module);
-               }
-               return nameVersions.iterator();
-       }
-
-       private void processModule(List<NameVersion> nameVersions, Object module) {
-               if (module instanceof ModuleSet)
-                       addNameVersions(nameVersions, (ModuleSet) module);
-               else if (module instanceof NameVersion) {
-                       NameVersion nv = (NameVersion) module;
-                       if (!nameVersions.contains(nv))
-                               nameVersions.add(nv);
-               } else
-                       log.warn("Ignored " + module);
-       }
-
-       private void addNameVersions(List<NameVersion> nameVersions,
-                       ModuleSet moduleSet) {
-               Iterator<? extends NameVersion> it = moduleSet.nameVersions();
-               while (it.hasNext()) {
-                       NameVersion nv = it.next();
-                       if (!nameVersions.contains(nv))
-                               nameVersions.add(nv);
-               }
-       }
-
-       // Modular distribution interface methods. Not yet used.
-       public Distribution getModuleDistribution(String moduleName,
-                       String moduleVersion) {
-               // NameVersion searched = new DefaultNameVersion(moduleName,
-               // moduleVersion);
-               // for (Distribution ad : modules) {
-               // if (ad.equals(searched))
-               // return ad;
-               // }
-               return null;
-       }
-
-       public Object getModulesDescriptor(String descriptorType) {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       /* DEPENDENCY INJECTION */
-       public void setModules(List<Object> modules) {
-               this.modules = modules;
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/BndWrapper.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/BndWrapper.java
deleted file mode 100644 (file)
index fce5211..0000000
+++ /dev/null
@@ -1,235 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Properties;
-import java.util.jar.Manifest;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.build.License;
-import org.osgi.framework.Version;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-import org.springframework.beans.factory.BeanNameAware;
-
-import aQute.lib.osgi.Builder;
-import aQute.lib.osgi.Constants;
-import aQute.lib.osgi.Jar;
-
-/** Utilities around the BND library, which manipulates OSGi metadata. */
-public class BndWrapper implements Constants, CategorizedNameVersion,
-               Distribution, BeanNameAware {
-       private final static Log log = LogFactory.getLog(BndWrapper.class);
-
-       private String groupId;
-       private String name;
-       private Properties bndProperties = new Properties();
-
-       private String version;
-       private License license;
-
-       private Boolean doNotModify = false;
-
-       private Runnable factory = null;
-
-       public void wrapJar(InputStream in, OutputStream out) {
-               Builder b = new Builder();
-               Jar jar = null;
-               try {
-                       byte[] jarBytes = IOUtils.toByteArray(in);
-
-                       jar = new Jar(null, new ByteArrayInputStream(jarBytes));
-                       Manifest sourceManifest = jar.getManifest();
-
-                       Version versionToUse;
-                       if (sourceManifest != null) {
-                               // Symbolic name
-                               String sourceSymbolicName = sourceManifest.getMainAttributes()
-                                               .getValue(BUNDLE_SYMBOLICNAME);
-                               if (sourceSymbolicName != null
-                                               && !sourceSymbolicName.equals(name))
-                                       log.info("The new symbolic name ("
-                                                       + name
-                                                       + ") is not consistant with the wrapped bundle symbolic name ("
-                                                       + sourceSymbolicName + ")");
-
-                               // Version
-                               String sourceVersion = sourceManifest.getMainAttributes()
-                                               .getValue(BUNDLE_VERSION);
-                               if (getVersion() == null && sourceVersion == null) {
-                                       throw new SlcException("A bundle version must be defined.");
-                               } else if (getVersion() == null && sourceVersion != null) {
-                                       versionToUse = new Version(sourceVersion);
-                                       version = sourceVersion; // set wrapper version
-                               } else if (getVersion() != null && sourceVersion == null) {
-                                       versionToUse = new Version(getVersion());
-                               } else {// both set
-                                       versionToUse = new Version(getVersion());
-                                       Version sv = new Version(sourceVersion);
-                                       if (versionToUse.getMajor() != sv.getMajor()
-                                                       || versionToUse.getMinor() != sv.getMinor()
-                                                       || versionToUse.getMicro() != sv.getMicro()) {
-                                               log.warn("The new version ("
-                                                               + versionToUse
-                                                               + ") is not consistant with the wrapped bundle version ("
-                                                               + sv + ")");
-                                       }
-                               }
-                       } else {
-                               versionToUse = new Version(getVersion());
-                       }
-
-                       if (doNotModify) {
-                               IOUtils.write(jarBytes, out);
-                               // jar.write(out);
-                       } else {
-
-                               Properties properties = new Properties();
-                               properties.putAll(bndProperties);
-                               properties.setProperty(BUNDLE_SYMBOLICNAME, name);
-                               properties.setProperty(BUNDLE_VERSION, versionToUse.toString());
-
-                               // License
-                               if (license != null) {
-                                       StringBuilder sb = new StringBuilder(license.getUri());
-                                       if (license.getName() != null)
-                                               sb.append(';').append("description=")
-                                                               .append(license.getName());
-                                       if (license.getLink() != null)
-                                               sb.append(';').append("link=")
-                                                               .append(license.getLink());
-                                       properties.setProperty(BUNDLE_LICENSE, sb.toString());
-                                       // TODO add LICENSE.TXT
-                               } else {
-                                       log.warn("No license set for " + toString());
-                               }
-
-                               // b.addIncluded(jarFile);
-                               b.addClasspath(jar);
-
-                               if (log.isDebugEnabled())
-                                       log.debug(properties);
-                               b.setProperties(properties);
-
-                               Jar newJar = b.build();
-                               newJar.write(out);
-                               newJar.close();
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot wrap jar", e);
-               } finally {
-                       b.close();
-                       if (jar != null)
-                               jar.close();
-               }
-
-       }
-
-       public Runnable getFactory() {
-               return factory;
-       }
-
-       public void setFactory(Runnable factory) {
-               if (this.factory != null)
-                       throw new SlcException("Factory already set on " + name);
-               this.factory = factory;
-       }
-
-       public void setName(String bsn) {
-               this.name = bsn;
-       }
-
-       public String getName() {
-               return name;
-       }
-
-       public void setVersion(String version) {
-               if (this.version != null)
-                       throw new SlcException("Version already set on " + name + " ("
-                                       + this.version + ")");
-               this.version = version;
-       }
-
-       public String getVersion() {
-               return version;
-       }
-
-       public License getLicense() {
-               return license;
-       }
-
-       public void setLicense(License license) {
-               if (this.license != null)
-                       throw new SlcException("License already set on " + name);
-               this.license = license;
-       }
-
-       public Properties getBndProperties() {
-               return bndProperties;
-       }
-
-       public void setBndProperties(Properties bndProperties) {
-               this.bndProperties = bndProperties;
-       }
-
-       public void setBeanName(String name) {
-               if (this.name == null) {
-                       this.name = name;
-               } else {
-                       log.warn("Using explicitely set name " + this.name
-                                       + " and not bean name " + name);
-               }
-       }
-
-       public String getGroupId() {
-               return groupId;
-       }
-
-       public String getCategory() {
-               return getGroupId();
-       }
-
-       public void setGroupId(String groupId) {
-               this.groupId = groupId;
-       }
-
-       public String getDistributionId() {
-               return getArtifact().toString();
-       }
-
-       public Artifact getArtifact() {
-               return new DefaultArtifact(groupId, name, "jar", getVersion());
-       }
-
-       @Override
-       public String toString() {
-               return getArtifact().toString();
-       }
-
-       @Override
-       public int hashCode() {
-               return getArtifact().hashCode();
-       }
-
-       @Override
-       public boolean equals(Object obj) {
-               if (obj instanceof CategorizedNameVersion) {
-                       CategorizedNameVersion cnv = (CategorizedNameVersion) obj;
-                       return getCategory().equals(cnv.getCategory())
-                                       && getName().equals(cnv.getName())
-                                       && getVersion().equals(cnv.getVersion());
-               } else
-                       return false;
-       }
-
-       public void setDoNotModify(Boolean doNotModify) {
-               this.doNotModify = doNotModify;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ImportBundlesZip.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ImportBundlesZip.java
deleted file mode 100644 (file)
index 80574f8..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.osgi;
-
-import java.io.ByteArrayInputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.jar.JarInputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.Session;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.JarFileIndexer;
-import org.argeo.slc.repo.RepoUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Import all bundles in a zip file (typically an Eclipse distribution) into the
- * workspace.
- * 
- * @deprecated Use {@link ArchiveWrapper} instead.
- */
-@Deprecated
-public class ImportBundlesZip implements Runnable {
-       private final static Log log = LogFactory.getLog(ImportBundlesZip.class);
-       private Repository repository;
-       private String workspace;
-       private String groupId;
-       private String artifactBasePath = "/";
-
-       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-       private JarFileIndexer jarFileIndexer = new JarFileIndexer();
-
-       private String zipFile;
-
-       private List<String> excludedBundles = new ArrayList<String>();
-
-       public void run() {
-               ZipInputStream zipIn = null;
-               JarInputStream jarIn = null;
-               Session session = null;
-               try {
-                       URL url = new URL(zipFile);
-                       session = repository.login(workspace);
-
-                       // clear
-                       // String groupPath = MavenConventionsUtils.groupPath(
-                       // artifactBasePath, groupId);
-                       // if (session.itemExists(groupPath)) {
-                       // session.getNode(groupPath).remove();
-                       // session.save();
-                       // if (log.isDebugEnabled())
-                       // log.debug("Cleared " + groupPath);
-                       // }
-
-                       zipIn = new ZipInputStream(url.openStream());
-                       ZipEntry zipEntry = null;
-                       entries: while ((zipEntry = zipIn.getNextEntry()) != null) {
-                               String entryName = zipEntry.getName();
-                               if (!entryName.endsWith(".jar")
-                                               || entryName.contains("feature"))
-                                       continue entries;// skip
-                               byte[] jarBytes = IOUtils.toByteArray(zipIn);
-                               zipIn.closeEntry();
-                               jarIn = new JarInputStream(new ByteArrayInputStream(jarBytes));
-                               Manifest manifest = jarIn.getManifest();
-                               IOUtils.closeQuietly(jarIn);
-                               if (manifest == null) {
-                                       log.warn(entryName + " has no MANIFEST");
-                                       continue entries;
-                               }
-                               NameVersion nv;
-                               try {
-                                       nv = RepoUtils.readNameVersion(manifest);
-                               } catch (Exception e) {
-                                       log.warn("Cannot read name version from " + entryName, e);
-                                       continue entries;
-                               }
-
-                               String bundleName = RepoUtils
-                                               .extractBundleNameFromSourceName(nv.getName());
-                               // skip excluded bundles and their sources
-                               if (excludedBundles.contains(bundleName))
-                                       continue entries;
-                               // for(String excludedBundle:excludedBundles){
-                               // if(bundleName.contains(excludedBundle))
-                               // continue entries;
-                               // }
-
-                               Artifact artifact = new DefaultArtifact(groupId, nv.getName(),
-                                               "jar", nv.getVersion());
-                               Node artifactNode = RepoUtils.copyBytesAsArtifact(
-                                               session.getNode(artifactBasePath), artifact, jarBytes);
-                               jarBytes = null;// superstition, in order to free memory
-
-                               // indexes
-                               artifactIndexer.index(artifactNode);
-                               jarFileIndexer.index(artifactNode);
-                               session.save();
-                               if (log.isDebugEnabled())
-                                       log.debug("Imported " + entryName + " to " + artifactNode);
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot import zip " + zipFile + " to "
-                                       + workspace, e);
-               } finally {
-                       IOUtils.closeQuietly(zipIn);
-                       IOUtils.closeQuietly(jarIn);
-                       JcrUtils.logoutQuietly(session);
-               }
-
-       }
-
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-       public void setGroupId(String groupId) {
-               this.groupId = groupId;
-       }
-
-       public void setArtifactBasePath(String artifactBasePath) {
-               this.artifactBasePath = artifactBasePath;
-       }
-
-       public void setZipFile(String zipFile) {
-               this.zipFile = zipFile;
-       }
-
-       public void setExcludedBundles(List<String> excludedBundles) {
-               this.excludedBundles = excludedBundles;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/MavenWrapper.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/MavenWrapper.java
deleted file mode 100644 (file)
index ab7daeb..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.OsgiFactory;
-import org.argeo.slc.repo.RepoUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-import org.sonatype.aether.util.artifact.SubArtifact;
-
-/**
- * BND wrapper based on a Maven artifact available from one of the configured
- * repositories.
- */
-public class MavenWrapper extends BndWrapper implements Runnable {
-       private final static Log log = LogFactory.getLog(MavenWrapper.class);
-
-       private String sourceCoords;
-
-       private OsgiFactory osgiFactory;
-
-       private Boolean doNotModifySources = false;
-
-       public MavenWrapper() {
-               setFactory(this);
-       }
-
-       @Override
-       public String getVersion() {
-               String version = super.getVersion();
-               if (version != null)
-                       return version;
-               return new DefaultArtifact(sourceCoords).getVersion();
-       }
-
-       public void run() {
-               Session distSession = null;
-               Session javaSession = null;
-               InputStream in = null;
-               ByteArrayOutputStream out = null;
-               try {
-                       distSession = osgiFactory.openDistSession();
-                       javaSession = osgiFactory.openJavaSession();
-                       Node origArtifact;
-                       try {
-                               origArtifact = osgiFactory.getMaven(distSession, sourceCoords);
-                       } catch (Exception e1) {
-                               origArtifact = osgiFactory.getMaven(distSession, sourceCoords
-                                               + ":" + getVersion());
-                       }
-
-                       in = origArtifact.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
-                       out = new ByteArrayOutputStream();
-                       wrapJar(in, out);
-                       Node newJarNode = RepoUtils
-                                       .copyBytesAsArtifact(javaSession.getRootNode(),
-                                                       getArtifact(), out.toByteArray());
-                       osgiFactory.indexNode(newJarNode);
-                       newJarNode.getSession().save();
-
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapped Maven " + sourceCoords + " to "
-                                               + newJarNode.getPath());
-
-                       // sources
-                       Artifact sourcesArtifact = new SubArtifact(new DefaultArtifact(
-                                       sourceCoords), "sources", null);
-                       Node sourcesArtifactNode;
-                       try {
-
-                               sourcesArtifactNode = osgiFactory.getMaven(distSession,
-                                               sourcesArtifact.toString());
-                       } catch (SlcException e) {
-                               // no sources available
-                               return;
-                       }
-
-                       IOUtils.closeQuietly(in);
-                       in = sourcesArtifactNode.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
-                       byte[] pdeSource;
-                       if (doNotModifySources)
-                               pdeSource = IOUtils.toByteArray(in);
-                       else
-                               pdeSource = RepoUtils.packageAsPdeSource(in,
-                                               new DefaultNameVersion(getName(), getVersion()));
-                       Node pdeSourceNode = RepoUtils.copyBytesAsArtifact(javaSession
-                                       .getRootNode(), new DefaultArtifact(getCategory(),
-                                       getName() + ".source", "jar", getVersion()), pdeSource);
-                       osgiFactory.indexNode(pdeSourceNode);
-                       pdeSourceNode.getSession().save();
-
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapped Maven " + sourcesArtifact
-                                               + " to PDE sources " + pdeSourceNode.getPath());
-               } catch (Exception e) {
-                       throw new SlcException("Cannot wrap Maven " + sourceCoords, e);
-               } finally {
-                       JcrUtils.logoutQuietly(distSession);
-                       JcrUtils.logoutQuietly(javaSession);
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-               }
-       }
-
-       public void setSourceCoords(String sourceCoords) {
-               this.sourceCoords = sourceCoords;
-       }
-
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-
-       public void setDoNotModifySources(Boolean doNotModifySources) {
-               this.doNotModifySources = doNotModifySources;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/NormalizeGroup.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/NormalizeGroup.java
deleted file mode 100644 (file)
index 99f31bb..0000000
+++ /dev/null
@@ -1,507 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.osgi;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.ArtifactIdComparator;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Version;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Make sure that all JCR metadata and Maven metadata are consistent for this
- * group of OSGi bundles.
- * 
- * The job is now done via the various {@code NodeIndexer} of the
- * WorkspaceManager. TODO import dependencies in the workspace.
- */
-@Deprecated
-public class NormalizeGroup implements Runnable, SlcNames {
-       private final static Log log = LogFactory.getLog(NormalizeGroup.class);
-
-       private Repository repository;
-       private String workspace;
-       private String groupId;
-       private Boolean overridePoms = false;
-       private String artifactBasePath = "/";
-       private String version = null;
-       private String parentPomCoordinates;
-
-       private List<String> excludedSuffixes = new ArrayList<String>();
-
-       private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-       // private JarFileIndexer jarFileIndexer = new JarFileIndexer();
-
-       /** TODO make it more generic */
-       private List<String> systemPackages = OsgiProfile.PROFILE_JAVA_SE_1_6
-                       .getSystemPackages();
-
-       // indexes
-       private Map<String, String> packagesToSymbolicNames = new HashMap<String, String>();
-       private Map<String, Node> symbolicNamesToNodes = new HashMap<String, Node>();
-
-       private Set<Artifact> binaries = new TreeSet<Artifact>(
-                       new ArtifactIdComparator());
-       private Set<Artifact> sources = new TreeSet<Artifact>(
-                       new ArtifactIdComparator());
-
-       public void run() {
-               Session session = null;
-               try {
-                       session = repository.login(workspace);
-                       Node groupNode = session.getNode(MavenConventionsUtils.groupPath(
-                                       artifactBasePath, groupId));
-                       processGroupNode(groupNode, null);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot normalize group " + groupId + " in "
-                                       + workspace, e);
-               } finally {
-                       JcrUtils.logoutQuietly(session);
-               }
-       }
-
-       public static void processGroupNode(Node groupNode, String version,
-                       Boolean overridePoms, ArgeoMonitor monitor)
-                       throws RepositoryException {
-               // TODO set artifactsBase based on group node
-               NormalizeGroup ng = new NormalizeGroup();
-               String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
-                               .getString();
-               ng.setGroupId(groupId);
-               ng.setVersion(version);
-               ng.setOverridePoms(overridePoms);
-               ng.processGroupNode(groupNode, monitor);
-       }
-
-       protected void processGroupNode(Node groupNode, ArgeoMonitor monitor)
-                       throws RepositoryException {
-               if (monitor != null)
-                       monitor.subTask("Group " + groupId);
-               Node allArtifactsHighestVersion = null;
-               Session session = groupNode.getSession();
-               aBases: for (NodeIterator aBases = groupNode.getNodes(); aBases
-                               .hasNext();) {
-                       Node aBase = aBases.nextNode();
-                       if (aBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
-                               Node highestAVersion = null;
-                               for (NodeIterator aVersions = aBase.getNodes(); aVersions
-                                               .hasNext();) {
-                                       Node aVersion = aVersions.nextNode();
-                                       if (aVersion.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
-                                               if (highestAVersion == null) {
-                                                       highestAVersion = aVersion;
-                                                       if (allArtifactsHighestVersion == null)
-                                                               allArtifactsHighestVersion = aVersion;
-
-                                                       // BS will fail if artifacts arrive in this order
-                                                       // Name1 - V1, name2 - V3, V1 will remain the
-                                                       // allArtifactsHighestVersion
-                                                       // Fixed below
-                                                       else {
-                                                               Version currVersion = extractOsgiVersion(aVersion);
-                                                               Version highestVersion = extractOsgiVersion(allArtifactsHighestVersion);
-                                                               if (currVersion.compareTo(highestVersion) > 0)
-                                                                       allArtifactsHighestVersion = aVersion;
-                                                       }
-
-                                               } else {
-                                                       Version currVersion = extractOsgiVersion(aVersion);
-                                                       Version currentHighestVersion = extractOsgiVersion(highestAVersion);
-                                                       if (currVersion.compareTo(currentHighestVersion) > 0) {
-                                                               highestAVersion = aVersion;
-                                                       }
-                                                       if (currVersion
-                                                                       .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
-                                                               allArtifactsHighestVersion = aVersion;
-                                                       }
-                                               }
-
-                                       }
-
-                               }
-                               if (highestAVersion == null)
-                                       continue aBases;
-                               for (NodeIterator files = highestAVersion.getNodes(); files
-                                               .hasNext();) {
-                                       Node file = files.nextNode();
-                                       if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
-                                               preProcessBundleArtifact(file);
-                                               file.getSession().save();
-                                               if (log.isDebugEnabled())
-                                                       log.debug("Pre-processed " + file.getName());
-                                       }
-
-                               }
-                       }
-               }
-
-               // if version not set or empty, use the highest version
-               // useful when indexing a product maven repository where
-               // all artifacts have the same version for a given release
-               // => the version can then be left empty
-               if (version == null || version.trim().equals(""))
-                       if (allArtifactsHighestVersion != null)
-                               version = allArtifactsHighestVersion.getProperty(
-                                               SLC_ARTIFACT_VERSION).getString();
-                       else
-                               version = "0.0";
-               // throw new SlcException("Group version " + version
-               // + " is empty.");
-
-               int bundleCount = symbolicNamesToNodes.size();
-               if (log.isDebugEnabled())
-                       log.debug("Indexed " + bundleCount + " bundles");
-
-               int count = 1;
-               for (Node bundleNode : symbolicNamesToNodes.values()) {
-                       processBundleArtifact(bundleNode);
-                       bundleNode.getSession().save();
-                       if (log.isDebugEnabled())
-                               log.debug(count + "/" + bundleCount + " Processed "
-                                               + bundleNode.getName());
-                       count++;
-               }
-
-               // indexes
-               Set<Artifact> indexes = new TreeSet<Artifact>(
-                               new ArtifactIdComparator());
-               Artifact indexArtifact = writeIndex(session,
-                               RepoConstants.BINARIES_ARTIFACT_ID, binaries);
-               indexes.add(indexArtifact);
-               indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID,
-                               sources);
-               indexes.add(indexArtifact);
-               // sdk
-               writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
-               if (monitor != null)
-                       monitor.worked(1);
-       }
-
-       private Version extractOsgiVersion(Node artifactVersion)
-                       throws RepositoryException {
-               String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
-                               .getString();
-               String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
-               Version osgiVersion = null;
-               // log invalid version value to enable tracking them
-               try {
-                       osgiVersion = new Version(cleanVersion);
-               } catch (IllegalArgumentException e) {
-                       log.error("Version string " + cleanVersion + " is invalid ");
-                       String twickedVersion = twickInvalidVersion(cleanVersion);
-                       osgiVersion = new Version(twickedVersion);
-                       log.error("Using " + twickedVersion + " instead");
-                       // throw e;
-               }
-               return osgiVersion;
-       }
-
-       private String twickInvalidVersion(String tmpVersion) {
-               String[] tokens = tmpVersion.split("\\.");
-               if (tokens.length == 3 && tokens[2].lastIndexOf("-") > 0) {
-                       String newSuffix = tokens[2].replaceFirst("-", ".");
-                       tmpVersion = tmpVersion.replaceFirst(tokens[2], newSuffix);
-               } else if (tokens.length > 4) {
-                       // FIXME manually remove other "."
-                       StringTokenizer st = new StringTokenizer(tmpVersion, ".", true);
-                       StringBuilder builder = new StringBuilder();
-                       // Major
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Minor
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Micro
-                       builder.append(st.nextToken()).append(st.nextToken());
-                       // Qualifier
-                       builder.append(st.nextToken());
-                       while (st.hasMoreTokens()) {
-                               // consume delimiter
-                               st.nextToken();
-                               if (st.hasMoreTokens())
-                                       builder.append("-").append(st.nextToken());
-                       }
-                       tmpVersion = builder.toString();
-               }
-               return tmpVersion;
-       }
-
-       private Artifact writeIndex(Session session, String artifactId,
-                       Set<Artifact> artifacts) throws RepositoryException {
-               Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
-                               version);
-               Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
-                               parentPomCoordinates) : null;
-               String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
-                               artifacts, parentArtifact);
-               Node node = RepoUtils.copyBytesAsArtifact(
-                               session.getNode(artifactBasePath), artifact, pom.getBytes());
-               artifactIndexer.index(node);
-
-               // TODO factorize
-               String pomSha = JcrUtils.checksumFile(node, "SHA-1");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
-                               pomSha.getBytes());
-               String pomMd5 = JcrUtils.checksumFile(node, "MD5");
-               JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
-                               pomMd5.getBytes());
-               session.save();
-               return artifact;
-       }
-
-       protected void preProcessBundleArtifact(Node bundleNode)
-                       throws RepositoryException {
-
-               String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
-               if (symbolicName.endsWith(".source")) {
-                       // TODO make a shared node with classifier 'sources'?
-                       String bundleName = RepoUtils
-                                       .extractBundleNameFromSourceName(symbolicName);
-                       for (String excludedSuffix : excludedSuffixes) {
-                               if (bundleName.endsWith(excludedSuffix))
-                                       return;// skip adding to sources
-                       }
-                       sources.add(RepoUtils.asArtifact(bundleNode));
-                       return;
-               }
-
-               NodeIterator exportPackages = bundleNode.getNodes(SLC_
-                               + Constants.EXPORT_PACKAGE);
-               while (exportPackages.hasNext()) {
-                       Node exportPackage = exportPackages.nextNode();
-                       String pkg = JcrUtils.get(exportPackage, SLC_NAME);
-                       packagesToSymbolicNames.put(pkg, symbolicName);
-               }
-
-               symbolicNamesToNodes.put(symbolicName, bundleNode);
-               for (String excludedSuffix : excludedSuffixes) {
-                       if (symbolicName.endsWith(excludedSuffix))
-                               return;// skip adding to binaries
-               }
-               binaries.add(RepoUtils.asArtifact(bundleNode));
-
-               if (bundleNode.getSession().hasPendingChanges())
-                       bundleNode.getSession().save();
-       }
-
-       protected void processBundleArtifact(Node bundleNode)
-                       throws RepositoryException {
-               Node artifactFolder = bundleNode.getParent();
-               String baseName = FilenameUtils.getBaseName(bundleNode.getName());
-
-               // pom
-               String pomName = baseName + ".pom";
-               if (artifactFolder.hasNode(pomName) && !overridePoms)
-                       return;// skip
-
-               String pom = generatePomForBundle(bundleNode);
-               Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
-                               pom.getBytes());
-               // checksum
-               String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
-               JcrUtils.copyBytesAsFile(artifactFolder,
-                               bundleNode.getName() + ".sha1", bundleSha.getBytes());
-               String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
-               JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
-                               pomSha.getBytes());
-       }
-
-       private String generatePomForBundle(Node n) throws RepositoryException {
-               String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
-
-               StringBuffer p = new StringBuffer();
-
-               // XML header
-               p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
-               p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
-               p.append("<modelVersion>4.0.0</modelVersion>");
-
-               // Artifact
-               p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
-                               .append("</groupId>\n");
-               p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
-                               .append("</artifactId>\n");
-               p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
-                               .append("</version>\n");
-               p.append("<packaging>pom</packaging>\n");
-               if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
-                       p.append("<name>")
-                                       .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
-                                       .append("</name>\n");
-               if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
-                       p.append("<description>")
-                                       .append(JcrUtils
-                                                       .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
-                                       .append("</description>\n");
-
-               // Dependencies
-               Set<String> dependenciesSymbolicNames = new TreeSet<String>();
-               Set<String> optionalSymbolicNames = new TreeSet<String>();
-               NodeIterator importPackages = n.getNodes(SLC_
-                               + Constants.IMPORT_PACKAGE);
-               while (importPackages.hasNext()) {
-                       Node importPackage = importPackages.nextNode();
-                       String pkg = JcrUtils.get(importPackage, SLC_NAME);
-                       if (packagesToSymbolicNames.containsKey(pkg)) {
-                               String dependencySymbolicName = packagesToSymbolicNames
-                                               .get(pkg);
-                               if (JcrUtils.check(importPackage, SLC_OPTIONAL))
-                                       optionalSymbolicNames.add(dependencySymbolicName);
-                               else
-                                       dependenciesSymbolicNames.add(dependencySymbolicName);
-                       } else {
-                               if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
-                                               && !systemPackages.contains(pkg))
-                                       log.warn("No bundle found for pkg " + pkg);
-                       }
-               }
-
-               if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
-                       String fragmentHost = JcrUtils.get(
-                                       n.getNode(SLC_ + Constants.FRAGMENT_HOST),
-                                       SLC_SYMBOLIC_NAME);
-                       dependenciesSymbolicNames.add(fragmentHost);
-               }
-
-               // TODO require bundles
-
-               List<Node> dependencyNodes = new ArrayList<Node>();
-               for (String depSymbName : dependenciesSymbolicNames) {
-                       if (depSymbName.equals(ownSymbolicName))
-                               continue;// skip self
-
-                       if (symbolicNamesToNodes.containsKey(depSymbName))
-                               dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
-                       else
-                               log.warn("Could not find node for " + depSymbName);
-               }
-               List<Node> optionalDependencyNodes = new ArrayList<Node>();
-               for (String depSymbName : optionalSymbolicNames) {
-                       if (symbolicNamesToNodes.containsKey(depSymbName))
-                               optionalDependencyNodes.add(symbolicNamesToNodes
-                                               .get(depSymbName));
-                       else
-                               log.warn("Could not find node for " + depSymbName);
-               }
-
-               p.append("<dependencies>\n");
-               for (Node dependencyNode : dependencyNodes) {
-                       p.append("<dependency>\n");
-                       p.append("\t<groupId>")
-                                       .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
-                                       .append("</groupId>\n");
-                       p.append("\t<artifactId>")
-                                       .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
-                                       .append("</artifactId>\n");
-                       p.append("</dependency>\n");
-               }
-
-               if (optionalDependencyNodes.size() > 0)
-                       p.append("<!-- OPTIONAL -->\n");
-               for (Node dependencyNode : optionalDependencyNodes) {
-                       p.append("<dependency>\n");
-                       p.append("\t<groupId>")
-                                       .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
-                                       .append("</groupId>\n");
-                       p.append("\t<artifactId>")
-                                       .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
-                                       .append("</artifactId>\n");
-                       p.append("\t<optional>true</optional>\n");
-                       p.append("</dependency>\n");
-               }
-               p.append("</dependencies>\n");
-
-               // Dependency management
-               p.append("<dependencyManagement>\n");
-               p.append("<dependencies>\n");
-               p.append("<dependency>\n");
-               p.append("\t<groupId>").append(groupId).append("</groupId>\n");
-               p.append("\t<artifactId>")
-                               .append(ownSymbolicName.endsWith(".source") ? RepoConstants.SOURCES_ARTIFACT_ID
-                                               : RepoConstants.BINARIES_ARTIFACT_ID)
-                               .append("</artifactId>\n");
-               p.append("\t<version>").append(version).append("</version>\n");
-               p.append("\t<type>pom</type>\n");
-               p.append("\t<scope>import</scope>\n");
-               p.append("</dependency>\n");
-               p.append("</dependencies>\n");
-               p.append("</dependencyManagement>\n");
-
-               p.append("</project>\n");
-               return p.toString();
-       }
-
-       /* DEPENDENCY INJECTION */
-       public void setRepository(Repository repository) {
-               this.repository = repository;
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-       public void setGroupId(String groupId) {
-               this.groupId = groupId;
-       }
-
-       public void setParentPomCoordinates(String parentPomCoordinates) {
-               this.parentPomCoordinates = parentPomCoordinates;
-       }
-
-       public void setArtifactBasePath(String artifactBasePath) {
-               this.artifactBasePath = artifactBasePath;
-       }
-
-       public void setVersion(String version) {
-               this.version = version;
-       }
-
-       public void setExcludedSuffixes(List<String> excludedSuffixes) {
-               this.excludedSuffixes = excludedSuffixes;
-       }
-
-       public void setOverridePoms(Boolean overridePoms) {
-               this.overridePoms = overridePoms;
-       }
-
-       public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
-               this.artifactIndexer = artifactIndexer;
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ObrWrapper.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ObrWrapper.java
deleted file mode 100644 (file)
index d44593b..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.osgi;
-
-public class ObrWrapper {
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiCategorizedNV.java
deleted file mode 100644 (file)
index 0d75d25..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.DefaultNameVersion;
-
-class OsgiCategorizedNV extends DefaultNameVersion implements
-               CategorizedNameVersion, Runnable {
-       private String category;
-       /** Build runnable */
-       private Runnable build;
-
-       public OsgiCategorizedNV(String category, String name, String version,
-                       Runnable build) {
-               super(name, version);
-               this.category = category;
-               this.build = build;
-       }
-
-       public String getCategory() {
-               return category;
-       }
-
-       @Override
-       public void run() {
-               if (build != null)
-                       build.run();
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiFactoryImpl.java
deleted file mode 100644 (file)
index bd4f431..0000000
+++ /dev/null
@@ -1,250 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.io.BufferedInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.NodeIndexer;
-import org.argeo.slc.repo.OsgiFactory;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/** Default implementation of {@link OsgiFactory}. */
-public class OsgiFactoryImpl implements OsgiFactory, SlcNames {
-       private final static Log log = LogFactory.getLog(OsgiFactoryImpl.class);
-
-       private String workspace;
-       private Repository distRepository;
-       private Repository javaRepository;
-
-       private List<NodeIndexer> nodeIndexers = new ArrayList<NodeIndexer>();
-
-       /** key is URI prefix, value list of base URLs */
-       private Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
-
-       private List<String> mavenRepositories = new ArrayList<String>();
-       private String mavenProxyBase = "/mavenProxy";
-
-       public void init() {
-               if (workspace == null)
-                       throw new SlcException("A workspace must be specified");
-
-               // default Maven repo
-               if (mavenRepositories.size() == 0) {
-                       // mavenRepositories
-                       // .add("http://search.maven.org/remotecontent?filepath=");
-                       mavenRepositories.add("http://repo1.maven.org/maven2");
-               }
-
-               Session javaSession = null;
-               Session distSession = null;
-               try {
-                       // TODO rather user a JavaRepoManager that will also implicitely
-                       // manage the indexing of newly created nodes.
-                       javaSession = JcrUtils.loginOrCreateWorkspace(javaRepository,
-                                       workspace);
-                       distSession = JcrUtils.loginOrCreateWorkspace(distRepository,
-                                       workspace);
-
-                       // Privileges
-                       JcrUtils.addPrivilege(javaSession, "/", SlcConstants.ROLE_SLC,
-                                       "jcr:all");
-                       JcrUtils.addPrivilege(distSession, "/", SlcConstants.ROLE_SLC,
-                                       "jcr:all");
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot initialize OSGi Factory "
-                                       + workspace, e);
-               } finally {
-                       JcrUtils.logoutQuietly(javaSession);
-                       JcrUtils.logoutQuietly(distSession);
-               }
-       }
-
-       public void destroy() {
-
-       }
-
-       public Session openJavaSession() throws RepositoryException {
-               return javaRepository.login(workspace);
-       }
-
-       public Session openDistSession() throws RepositoryException {
-               return distRepository.login(workspace);
-       }
-
-       public void indexNode(Node node) {
-               for (NodeIndexer nodeIndexer : nodeIndexers) {
-                       nodeIndexer.index(node);
-               }
-       }
-
-       public Node getMaven(Session distSession, String coords)
-                       throws RepositoryException {
-               Artifact artifact = new DefaultArtifact(coords);
-               String path = MavenConventionsUtils.artifactPath(mavenProxyBase,
-                               artifact);
-
-               // exists
-               if (distSession.itemExists(path))
-                       return distSession.getNode(path);
-
-               for (String mavenRepo : mavenRepositories) {
-                       String url = mavenRepo
-                                       + MavenConventionsUtils.artifactPath("/", artifact);
-                       try {
-                               Node node = loadUrlToPath(url, distSession, path);
-                               if (node != null) {
-                                       // checksums
-                                       try {
-                                               loadUrlToPath(url + ".md5", distSession, path + ".md5");
-                                       } catch (FileNotFoundException e) {
-                                               // silent
-                                       }
-                                       try {
-                                               loadUrlToPath(url + ".sha1", distSession, path
-                                                               + ".sha1");
-                                       } catch (FileNotFoundException e) {
-                                               // silent
-                                       }
-                                       return node;
-                               }
-                       } catch (FileNotFoundException e) {
-                               if (log.isDebugEnabled())
-                                       log.debug("Maven " + coords
-                                                       + " could not be downloaded from " + url);
-                       }
-               }
-               throw new SlcException("Could not download Maven " + coords);
-       }
-
-       public Node getDist(Session distSession, String uri)
-                       throws RepositoryException {
-               String distPath = '/' + JcrUtils.urlAsPath(uri);
-
-               // already retrieved
-               if (distSession.itemExists(distPath))
-                       return distSession.getNode(distPath);
-
-               // find mirror
-               List<String> urlBases = null;
-               String uriPrefix = null;
-               uriPrefixes: for (String uriPref : mirrors.keySet()) {
-                       if (uri.startsWith(uriPref)) {
-                               if (mirrors.get(uriPref).size() > 0) {
-                                       urlBases = mirrors.get(uriPref);
-                                       uriPrefix = uriPref;
-                                       break uriPrefixes;
-                               }
-                       }
-               }
-               if (urlBases == null)
-                       try {
-                               return loadUrlToPath(uri, distSession, distPath);
-                       } catch (FileNotFoundException e) {
-                               throw new SlcException("Cannot download " + uri, e);
-                       }
-
-               // try to download
-               for (String urlBase : urlBases) {
-                       String relativePath = uri.substring(uriPrefix.length());
-                       String url = urlBase + relativePath;
-                       try {
-                               return loadUrlToPath(url, distSession, distPath);
-                       } catch (FileNotFoundException e) {
-                               if (log.isDebugEnabled())
-                                       log.debug("Cannot download " + url
-                                                       + ", trying another mirror");
-                       }
-               }
-
-               throw new SlcException("Could not download " + uri);
-       }
-
-       /** Actually downloads a file to an internal location */
-       protected Node loadUrlToPath(String url, Session distSession, String path)
-                       throws RepositoryException, FileNotFoundException {
-               if (log.isDebugEnabled())
-                       log.debug("Downloading " + url + "...");
-
-               InputStream in = null;
-               URLConnection conn = null;
-               Node folderNode = JcrUtils.mkfolders(distSession,
-                               JcrUtils.parentPath(path));
-               try {
-                       URL u = new URL(url);
-                       conn = u.openConnection();
-                       conn.connect();
-                       in = new BufferedInputStream(conn.getInputStream());
-                       // byte[] arr = IOUtils.toByteArray(in);
-                       // Node fileNode = JcrUtils.copyBytesAsFile(folderNode,
-                       // JcrUtils.nodeNameFromPath(path), arr);
-                       Node fileNode = JcrUtils.copyStreamAsFile(folderNode,
-                                       JcrUtils.nodeNameFromPath(path), in);
-                       fileNode.addMixin(SlcTypes.SLC_KNOWN_ORIGIN);
-                       Node origin = fileNode.addNode(SLC_ORIGIN, SlcTypes.SLC_PROXIED);
-                       JcrUtils.urlToAddressProperties(origin, url);
-                       distSession.save();
-                       return fileNode;
-               } catch (MalformedURLException e) {
-                       throw new SlcException("URL " + url + " not valid.", e);
-               } catch (FileNotFoundException e) {
-                       throw e;
-               } catch (IOException e) {
-                       throw new SlcException("Cannot load " + url + " to " + path, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-
-       }
-
-       public void setWorkspace(String workspace) {
-               this.workspace = workspace;
-       }
-
-       public void setDistRepository(Repository distRepository) {
-               this.distRepository = distRepository;
-       }
-
-       public void setJavaRepository(Repository javaRepository) {
-               this.javaRepository = javaRepository;
-       }
-
-       public void setNodeIndexers(List<NodeIndexer> nodeIndexers) {
-               this.nodeIndexers = nodeIndexers;
-       }
-
-       public void setMirrors(Map<String, List<String>> mirrors) {
-               this.mirrors = mirrors;
-       }
-
-       public void setMavenRepositories(List<String> mavenRepositories) {
-               this.mavenRepositories = mavenRepositories;
-       }
-
-       public void setMavenProxyBase(String mavenProxyBase) {
-               this.mavenProxyBase = mavenProxyBase;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiProfile.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/OsgiProfile.java
deleted file mode 100644 (file)
index 50f87be..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.repo.osgi;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-
-/**
- * Wraps an OSGi profile, simplifying access to its values such as system
- * packages, etc.
- */
-public class OsgiProfile {
-       public final static String PROP_SYSTEM_PACKAGES = "org.osgi.framework.system.packages";
-
-       public final static OsgiProfile PROFILE_JAVA_SE_1_6 = new OsgiProfile(
-                       "JavaSE-1.6.profile");
-
-       private final URL url;
-       private final Properties properties;
-
-       public OsgiProfile(URL url) {
-               this.url = url;
-               properties = new Properties();
-               InputStream in = null;
-               try {
-                       properties.load(this.url.openStream());
-               } catch (Exception e) {
-                       throw new SlcException("Cannot initalize OSGi profile " + url, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       public OsgiProfile(String name) {
-               this(OsgiProfile.class.getClassLoader().getResource(
-                               '/'
-                                               + OsgiProfile.class.getPackage().getName()
-                                                               .replace('.', '/') + '/' + name));
-       }
-
-       public List<String> getSystemPackages() {
-               String[] splitted = properties.getProperty(PROP_SYSTEM_PACKAGES).split(
-                               ",");
-               List<String> res = new ArrayList<String>();
-               for (String pkg : splitted) {
-                       res.add(pkg.trim());
-               }
-               return Collections.unmodifiableList(res);
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ProcessDistribution.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/ProcessDistribution.java
deleted file mode 100644 (file)
index d16a797..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.util.Iterator;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.CategorizedNameVersion;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.ArgeoOsgiDistribution;
-import org.argeo.slc.repo.ModularDistributionFactory;
-import org.argeo.slc.repo.OsgiFactory;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/** Executes the processes required so that all managed bundles are available. */
-public class ProcessDistribution implements Runnable {
-       private final static Log log = LogFactory.getLog(ProcessDistribution.class);
-
-       private ArgeoOsgiDistribution osgiDistribution;
-       private OsgiFactory osgiFactory;
-
-       public void run() {
-               Session javaSession = null;
-               try {
-                       javaSession = osgiFactory.openJavaSession();
-                       for (Iterator<? extends NameVersion> it = osgiDistribution
-                                       .nameVersions(); it.hasNext();)
-                               processNameVersion(javaSession, it.next());
-
-                       // Check sources
-                       for (Iterator<? extends NameVersion> it = osgiDistribution
-                                       .nameVersions(); it.hasNext();) {
-                               CategorizedNameVersion nv = (CategorizedNameVersion) it.next();
-                               Artifact artifact = new DefaultArtifact(nv.getCategory(),
-                                               nv.getName() + ".source", "jar", nv.getVersion());
-                               String path = MavenConventionsUtils.artifactPath("/", artifact);
-                               if (!javaSession.itemExists(path))
-                                       log.warn("No source available for " + nv);
-                       }
-
-                       // explicitly create the corresponding modular distribution as we
-                       // have here all necessary info.
-                       ModularDistributionFactory mdf = new ModularDistributionFactory(
-                                       osgiFactory, osgiDistribution);
-                       mdf.run();
-
-               } catch (RepositoryException e) {
-                       throw new SlcException("Cannot process distribution "
-                                       + osgiDistribution, e);
-               } finally {
-                       JcrUtils.logoutQuietly(javaSession);
-               }
-       }
-
-       protected void processNameVersion(Session javaSession,
-                       NameVersion nameVersion) throws RepositoryException {
-               if (log.isTraceEnabled())
-                       log.trace("Check " + nameVersion + "...");
-               if (!(nameVersion instanceof CategorizedNameVersion))
-                       throw new SlcException("Unsupported type " + nameVersion.getClass());
-               CategorizedNameVersion nv = (CategorizedNameVersion) nameVersion;
-               Artifact artifact = new DefaultArtifact(nv.getCategory(), nv.getName(),
-                               "jar", nv.getVersion());
-               String path = MavenConventionsUtils.artifactPath("/", artifact);
-               if (!javaSession.itemExists(path)) {
-                       if (nv instanceof BndWrapper) {
-                               if (log.isDebugEnabled())
-                                       log.debug("Run factory for   : " + nv + "...");
-                               ((BndWrapper) nv).getFactory().run();
-                       } else if (nv instanceof Runnable) {
-                               ((Runnable) nv).run();
-                       } else {
-                               log.warn("Skip unsupported   : " + nv);
-                       }
-               } else {
-                       if (log.isTraceEnabled())
-                               log.trace("Already available : " + nv);
-               }
-       }
-
-       /* DEPENDENCY INJECTION */
-       public void setOsgiDistribution(ArgeoOsgiDistribution osgiDistribution) {
-               this.osgiDistribution = osgiDistribution;
-       }
-
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-}
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/SourcesProvider.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/SourcesProvider.java
deleted file mode 100644 (file)
index a0a20f6..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.util.List;
-import java.util.zip.ZipOutputStream;
-
-/** Provides access to Java sources */
-public interface SourcesProvider {
-       /**
-        * Writes sources into a ZIP (or a JAR), under the same sirectory structure.
-        * 
-        * @param packages
-        *            the packages to import
-        * @param out
-        *            the ZIP or JAR to write to
-        */
-       public void writeSources(List<String> packages, ZipOutputStream zout);
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/UriWrapper.java b/runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/UriWrapper.java
deleted file mode 100644 (file)
index cf0422e..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-package org.argeo.slc.repo.osgi;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.util.List;
-import java.util.zip.ZipOutputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.Session;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.OsgiFactory;
-import org.argeo.slc.repo.RepoUtils;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-import aQute.lib.osgi.Jar;
-
-public class UriWrapper extends BndWrapper implements Runnable {
-       private final static Log log = LogFactory.getLog(UriWrapper.class);
-
-       private String uri;
-       private String baseUri;
-       private String versionSeparator = "-";
-       private String extension = "jar";
-
-       private OsgiFactory osgiFactory;
-
-       private SourcesProvider sourcesProvider;
-
-       public UriWrapper() {
-               setFactory(this);
-       }
-
-       public void run() {
-               Session distSession = null;
-               Session javaSession = null;
-               InputStream in = null;
-               ByteArrayOutputStream out = null;
-               Jar jar = null;
-               try {
-                       distSession = osgiFactory.openDistSession();
-                       javaSession = osgiFactory.openJavaSession();
-                       if (uri == null) {
-                               uri = baseUri + '/' + getName() + versionSeparator
-                                               + getVersion() + "." + extension;
-                       }
-                       Node sourceArtifact = osgiFactory.getDist(distSession, uri);
-
-                       // TODO factorize with Maven
-                       in = sourceArtifact.getNode(Node.JCR_CONTENT)
-                                       .getProperty(Property.JCR_DATA).getBinary().getStream();
-                       out = new ByteArrayOutputStream();
-                       wrapJar(in, out);
-                       Node newJarNode = RepoUtils
-                                       .copyBytesAsArtifact(javaSession.getRootNode(),
-                                                       getArtifact(), out.toByteArray());
-                       osgiFactory.indexNode(newJarNode);
-                       newJarNode.getSession().save();
-                       if (log.isDebugEnabled())
-                               log.debug("Wrapped " + uri + " to " + newJarNode.getPath());
-
-                       // sources
-                       if (sourcesProvider != null) {
-                               IOUtils.closeQuietly(in);
-                               in = new ByteArrayInputStream(out.toByteArray());
-                               jar = new Jar(null, in);
-                               List<String> packages = jar.getPackages();
-
-                               IOUtils.closeQuietly(out);
-                               out = new ByteArrayOutputStream();
-                               sourcesProvider
-                                               .writeSources(packages, new ZipOutputStream(out));
-
-                               IOUtils.closeQuietly(in);
-                               in = new ByteArrayInputStream(out.toByteArray());
-                               byte[] sourcesJar = RepoUtils.packageAsPdeSource(in,
-                                               new DefaultNameVersion(this));
-                               Artifact sourcesArtifact = new DefaultArtifact(getArtifact()
-                                               .getGroupId(), getArtifact().getArtifactId()
-                                               + ".source", "jar", getArtifact().getVersion());
-                               Node sourcesJarNode = RepoUtils.copyBytesAsArtifact(
-                                               javaSession.getRootNode(), sourcesArtifact, sourcesJar);
-                               sourcesJarNode.getSession().save();
-
-                               if (log.isDebugEnabled())
-                                       log.debug("Added sources " + sourcesArtifact
-                                                       + " for bundle " + getArtifact());
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot wrap URI " + uri, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-                       JcrUtils.logoutQuietly(distSession);
-                       JcrUtils.logoutQuietly(javaSession);
-                       if (jar != null)
-                               jar.close();
-               }
-       }
-
-       public void setUri(String sourceCoords) {
-               this.uri = sourceCoords;
-       }
-
-       public void setOsgiFactory(OsgiFactory osgiFactory) {
-               this.osgiFactory = osgiFactory;
-       }
-
-       public void setBaseUri(String baseUri) {
-               this.baseUri = baseUri;
-       }
-
-       public void setVersionSeparator(String versionSeparator) {
-               this.versionSeparator = versionSeparator;
-       }
-
-       public void setSourcesProvider(SourcesProvider sourcesProvider) {
-               this.sourcesProvider = sourcesProvider;
-       }
-}
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/apache-2.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/apache-2.0.txt
deleted file mode 100644 (file)
index d645695..0000000
+++ /dev/null
@@ -1,202 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [yyyy] [name of copyright owner]
-
-   Licensed 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.
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/bsd-3-clause.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/bsd-3-clause.txt
deleted file mode 100644 (file)
index ed0116e..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-Copyright (c) <YEAR>, <OWNER>
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/cddl-1.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/cddl-1.0.txt
deleted file mode 100644 (file)
index 9dc4442..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
- COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 1.
-
-Definitions.
-
-1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications.
-
-1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
-
-1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
-
-1.4. Executable means the Covered Software in any form other than Source Code.
-
-1.5. Initial Developer means the individual or entity that first makes Original Software available under this License.
-
-1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
-
-1.7. License means this document.
-
-1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
-
-1.9. Modifications means the Source Code and Executable form of any of the following: A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; B. Any new file that contains any part of the Original Software or previous Modification; or C. Any new file that is contributed or otherwise made available under the terms of this License.
-
-1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License.
-
-1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
-
-1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
-
-1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
-
-2. License Grants.
-
- 2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
-
-(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof);
-
- (c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License;
-
- (d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices.
-
-2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
-
-(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
-
-(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
-
-(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
-
-3. Distribution Obligations.
-
-3.1. Availability of Source Code. Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
-
-3.2. Modifications. The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
-
-3.3. Required Notices. You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
-
-3.4. Application of Additional Terms. You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
-
-3.5. Distribution of Executable Versions. You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
-
-3.6. Larger Works. You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
-
-4. Versions of the License.
-
-4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
-
-4.2. Effect of New Versions. You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
-
-4.3. Modified Versions. When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License.
-
-5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
-
-6. TERMINATION.
-
-6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
-
-6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
-
-6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
-
-7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
-
-8. U.S. GOVERNMENT END USERS. The Covered Software is a commercial item, as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R.  252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
-
-9. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
-
-10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
-
-NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) The code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California. 
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/epl-1.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/epl-1.0.txt
deleted file mode 100644 (file)
index 795c0c3..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
- THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-"Contribution" means:
-
-    a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-    b) in the case of each subsequent Contributor:
-    i) changes to the Program, and
-    ii) additions to the Program; 
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-    a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-    b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-    c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
-    d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-    a) it complies with the terms and conditions of this Agreement; and
-    b) its license agreement:
-    i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-    ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-    iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-    iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 
-
-When the Program is made available in source code form:
-
-    a) it must be made available under this Agreement; and
-    b) a copy of this Agreement must be included with each copy of the Program. 
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-2.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-2.0.txt
deleted file mode 100644 (file)
index d159169..0000000
+++ /dev/null
@@ -1,339 +0,0 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-3.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/gpl-3.0.txt
deleted file mode 100644 (file)
index 94a9ed0..0000000
+++ /dev/null
@@ -1,674 +0,0 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
-  The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works.  By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.  We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors.  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
-  To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights.  Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received.  You must make sure that they, too, receive
-or can get the source code.  And you must show them these terms so they
-know their rights.
-
-  Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
-  For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software.  For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
-  Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so.  This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software.  The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable.  Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products.  If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
-  Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary.  To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                       TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
-  "The Program" refers to any copyrightable work licensed under this
-License.  Each licensee is addressed as "you".  "Licensees" and
-"recipients" may be individuals or organizations.
-
-  To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy.  The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
-  A "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy.  Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
-  To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies.  Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
-  An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License.  If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
-  1. Source Code.
-
-  The "source code" for a work means the preferred form of the work
-for making modifications to it.  "Object code" means any non-source
-form of a work.
-
-  A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
-  The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form.  A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
-  The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities.  However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work.  For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met.  This License explicitly affirms your unlimited
-permission to run the unmodified Program.  The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work.  This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
-  You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force.  You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright.  Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
-  Conveying under any other circumstances is permitted solely under
-the conditions stated below.  Sublicensing is not allowed; section 10
-makes it unnecessary.
-
-  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-  No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
-  When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
-  4. Conveying Verbatim Copies.
-
-  You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
-  You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
-  5. Conveying Modified Source Versions.
-
-  You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
-    a) The work must carry prominent notices stating that you modified
-    it, and giving a relevant date.
-
-    b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under section
-    7.  This requirement modifies the requirement in section 4 to
-    "keep intact all notices".
-
-    c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy.  This
-    License will therefore apply, along with any applicable section 7
-    additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged.  This License gives no
-    permission to license the work in any other way, but it does not
-    invalidate such permission if you have separately received it.
-
-    d) If the work has interactive user interfaces, each must display
-    Appropriate Legal Notices; however, if the Program has interactive
-    interfaces that do not display Appropriate Legal Notices, your
-    work need not make them do so.
-
-  A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit.  Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
-  6. Conveying Non-Source Forms.
-
-  You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
-    a) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by the
-    Corresponding Source fixed on a durable physical medium
-    customarily used for software interchange.
-
-    b) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by a
-    written offer, valid for at least three years and valid for as
-    long as you offer spare parts or customer support for that product
-    model, to give anyone who possesses the object code either (1) a
-    copy of the Corresponding Source for all the software in the
-    product that is covered by this License, on a durable physical
-    medium customarily used for software interchange, for a price no
-    more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the
-    Corresponding Source from a network server at no charge.
-
-    c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source.  This
-    alternative is allowed only occasionally and noncommercially, and
-    only if you received the object code with such an offer, in accord
-    with subsection 6b.
-
-    d) Convey the object code by offering access from a designated
-    place (gratis or for a charge), and offer equivalent access to the
-    Corresponding Source in the same way through the same place at no
-    further charge.  You need not require recipients to copy the
-    Corresponding Source along with the object code.  If the place to
-    copy the object code is a network server, the Corresponding Source
-    may be on a different server (operated by you or a third party)
-    that supports equivalent copying facilities, provided you maintain
-    clear directions next to the object code saying where to find the
-    Corresponding Source.  Regardless of what server hosts the
-    Corresponding Source, you remain obligated to ensure that it is
-    available for as long as needed to satisfy these requirements.
-
-    e) Convey the object code using peer-to-peer transmission, provided
-    you inform other peers where the object code and Corresponding
-    Source of the work are being offered to the general public at no
-    charge under subsection 6d.
-
-  A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
-  A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling.  In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage.  For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product.  A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
-  "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source.  The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
-  If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information.  But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
-  The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed.  Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
-  Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
-  7. Additional Terms.
-
-  "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law.  If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
-  When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it.  (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.)  You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
-  Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
-    a) Disclaiming warranty or limiting liability differently from the
-    terms of sections 15 and 16 of this License; or
-
-    b) Requiring preservation of specified reasonable legal notices or
-    author attributions in that material or in the Appropriate Legal
-    Notices displayed by works containing it; or
-
-    c) Prohibiting misrepresentation of the origin of that material, or
-    requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
-
-    d) Limiting the use for publicity purposes of names of licensors or
-    authors of the material; or
-
-    e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
-
-    f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions of
-    it) with contractual assumptions of liability to the recipient, for
-    any liability that these contractual assumptions directly impose on
-    those licensors and authors.
-
-  All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10.  If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term.  If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
-  If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
-  Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
-  8. Termination.
-
-  You may not propagate or modify a covered work except as expressly
-provided under this License.  Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
-  However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
-  Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
-  Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License.  If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
-  9. Acceptance Not Required for Having Copies.
-
-  You are not required to accept this License in order to receive or
-run a copy of the Program.  Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance.  However,
-nothing other than this License grants you permission to propagate or
-modify any covered work.  These actions infringe copyright if you do
-not accept this License.  Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
-  10. Automatic Licensing of Downstream Recipients.
-
-  Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License.  You are not responsible
-for enforcing compliance by third parties with this License.
-
-  An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations.  If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
-  You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License.  For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
-  11. Patents.
-
-  A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based.  The
-work thus licensed is called the contributor's "contributor version".
-
-  A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version.  For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
-  Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
-  In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement).  To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
-  If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients.  "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
-  If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
-  A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License.  You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
-  Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
-  12. No Surrender of Others' Freedom.
-
-  If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all.  For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
-  13. Use with the GNU Affero General Public License.
-
-  Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work.  The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
-  14. Revised Versions of this License.
-
-  The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-  Each version is given a distinguishing version number.  If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation.  If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
-  If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
-  Later license versions may give you additional or different
-permissions.  However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
-  15. Disclaimer of Warranty.
-
-  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. Limitation of Liability.
-
-  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
-  17. Interpretation of Sections 15 and 16.
-
-  If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation, either version 3 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
-    <program>  Copyright (C) <year>  <name of author>
-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
-  You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
-  The GNU General Public License does not permit incorporating your program
-into proprietary programs.  If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.  But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-2.1.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-2.1.txt
deleted file mode 100644 (file)
index 4362b49..0000000
+++ /dev/null
@@ -1,502 +0,0 @@
-                  GNU LESSER GENERAL PUBLIC LICENSE
-                       Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL.  It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
-                            Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
-  This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it.  You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
-  When we speak of free software, we are referring to freedom of use,
-not price.  Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
-  To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights.  These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
-  For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you.  You must make sure that they, too, receive or can get the source
-code.  If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it.  And you must show them these terms so they know their rights.
-
-  We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
-  To protect each distributor, we want to make it very clear that
-there is no warranty for the free library.  Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-\f
-  Finally, software patents pose a constant threat to the existence of
-any free program.  We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder.  Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
-  Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License.  This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License.  We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
-  When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library.  The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom.  The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
-  We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License.  It also provides other free software developers Less
-of an advantage over competing non-free programs.  These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries.  However, the Lesser license provides advantages in certain
-special circumstances.
-
-  For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard.  To achieve this, non-free programs must be
-allowed to use the library.  A more frequent case is that a free
-library does the same job as widely used non-free libraries.  In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
-  In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software.  For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
-  Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.  Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library".  The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-\f
-                  GNU LESSER GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
-  A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
-  The "Library", below, refers to any such software library or work
-which has been distributed under these terms.  A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language.  (Hereinafter, translation is
-included without limitation in the term "modification".)
-
-  "Source code" for a work means the preferred form of the work for
-making modifications to it.  For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
-  Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it).  Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
-  1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
-  You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-\f
-  2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) The modified work must itself be a software library.
-
-    b) You must cause the files modified to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    c) You must cause the whole of the work to be licensed at no
-    charge to all third parties under the terms of this License.
-
-    d) If a facility in the modified Library refers to a function or a
-    table of data to be supplied by an application program that uses
-    the facility, other than as an argument passed when the facility
-    is invoked, then you must make a good faith effort to ensure that,
-    in the event an application does not supply such function or
-    table, the facility still operates, and performs whatever part of
-    its purpose remains meaningful.
-
-    (For example, a function in a library to compute square roots has
-    a purpose that is entirely well-defined independent of the
-    application.  Therefore, Subsection 2d requires that any
-    application-supplied function or table used by this function must
-    be optional: if the application does not supply it, the square
-    root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library.  To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License.  (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.)  Do not make any other change in
-these notices.
-\f
-  Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
-  This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
-  4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
-  If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library".  Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
-  However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library".  The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
-  When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library.  The
-threshold for this to be true is not precisely defined by law.
-
-  If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work.  (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
-  Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-\f
-  6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
-  You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License.  You must supply a copy of this License.  If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License.  Also, you must do one
-of these things:
-
-    a) Accompany the work with the complete corresponding
-    machine-readable source code for the Library including whatever
-    changes were used in the work (which must be distributed under
-    Sections 1 and 2 above); and, if the work is an executable linked
-    with the Library, with the complete machine-readable "work that
-    uses the Library", as object code and/or source code, so that the
-    user can modify the Library and then relink to produce a modified
-    executable containing the modified Library.  (It is understood
-    that the user who changes the contents of definitions files in the
-    Library will not necessarily be able to recompile the application
-    to use the modified definitions.)
-
-    b) Use a suitable shared library mechanism for linking with the
-    Library.  A suitable mechanism is one that (1) uses at run time a
-    copy of the library already present on the user's computer system,
-    rather than copying library functions into the executable, and (2)
-    will operate properly with a modified version of the library, if
-    the user installs one, as long as the modified version is
-    interface-compatible with the version that the work was made with.
-
-    c) Accompany the work with a written offer, valid for at
-    least three years, to give the same user the materials
-    specified in Subsection 6a, above, for a charge no more
-    than the cost of performing this distribution.
-
-    d) If distribution of the work is made by offering access to copy
-    from a designated place, offer equivalent access to copy the above
-    specified materials from the same place.
-
-    e) Verify that the user has already received a copy of these
-    materials or that you have already sent this user a copy.
-
-  For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it.  However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
-  It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system.  Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-\f
-  7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
-    a) Accompany the combined library with a copy of the same work
-    based on the Library, uncombined with any other library
-    facilities.  This must be distributed under the terms of the
-    Sections above.
-
-    b) Give prominent notice with the combined library of the fact
-    that part of it is a work based on the Library, and explaining
-    where to find the accompanying uncombined form of the same work.
-
-  8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License.  Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License.  However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
-  9. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Library or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
-  10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-\f
-  11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded.  In such case, this License incorporates the limitation as if
-written in the body of this License.
-
-  13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation.  If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-\f
-  14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission.  For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this.  Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
-                            NO WARRANTY
-
-  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-\f
-           How to Apply These Terms to Your New Libraries
-
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
-  To apply these terms, attach the following notices to the library.  It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the library's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
-  <signature of Ty Coon>, 1 April 1990
-  Ty Coon, President of Vice
-
-That's all there is to it!
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-3.0.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/lgpl-3.0.txt
deleted file mode 100644 (file)
index 65c5ca8..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-                   GNU LESSER GENERAL PUBLIC LICENSE
-                       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-
-  This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
-  0. Additional Definitions.
-
-  As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
-  "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
-  An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
-  A "Combined Work" is a work produced by combining or linking an
-Application with the Library.  The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
-  The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
-  The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
-  1. Exception to Section 3 of the GNU GPL.
-
-  You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
-  2. Conveying Modified Versions.
-
-  If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
-   a) under this License, provided that you make a good faith effort to
-   ensure that, in the event an Application does not supply the
-   function or data, the facility still operates, and performs
-   whatever part of its purpose remains meaningful, or
-
-   b) under the GNU GPL, with none of the additional permissions of
-   this License applicable to that copy.
-
-  3. Object Code Incorporating Material from Library Header Files.
-
-  The object code form of an Application may incorporate material from
-a header file that is part of the Library.  You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
-   a) Give prominent notice with each copy of the object code that the
-   Library is used in it and that the Library and its use are
-   covered by this License.
-
-   b) Accompany the object code with a copy of the GNU GPL and this license
-   document.
-
-  4. Combined Works.
-
-  You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
-   a) Give prominent notice with each copy of the Combined Work that
-   the Library is used in it and that the Library and its use are
-   covered by this License.
-
-   b) Accompany the Combined Work with a copy of the GNU GPL and this license
-   document.
-
-   c) For a Combined Work that displays copyright notices during
-   execution, include the copyright notice for the Library among
-   these notices, as well as a reference directing the user to the
-   copies of the GNU GPL and this license document.
-
-   d) Do one of the following:
-
-       0) Convey the Minimal Corresponding Source under the terms of this
-       License, and the Corresponding Application Code in a form
-       suitable for, and under terms that permit, the user to
-       recombine or relink the Application with a modified version of
-       the Linked Version to produce a modified Combined Work, in the
-       manner specified by section 6 of the GNU GPL for conveying
-       Corresponding Source.
-
-       1) Use a suitable shared library mechanism for linking with the
-       Library.  A suitable mechanism is one that (a) uses at run time
-       a copy of the Library already present on the user's computer
-       system, and (b) will operate properly with a modified version
-       of the Library that is interface-compatible with the Linked
-       Version.
-
-   e) Provide Installation Information, but only if you would otherwise
-   be required to provide such information under section 6 of the
-   GNU GPL, and only to the extent that such information is
-   necessary to install and execute a modified version of the
-   Combined Work produced by recombining or relinking the
-   Application with a modified version of the Linked Version. (If
-   you use option 4d0, the Installation Information must accompany
-   the Minimal Corresponding Source and Corresponding Application
-   Code. If you use option 4d1, you must provide the Installation
-   Information in the manner specified by section 6 of the GNU GPL
-   for conveying Corresponding Source.)
-
-  5. Combined Libraries.
-
-  You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
-   a) Accompany the combined library with a copy of the same work based
-   on the Library, uncombined with any other library facilities,
-   conveyed under the terms of this License.
-
-   b) Give prominent notice with the combined library that part of it
-   is a work based on the Library, and explaining where to find the
-   accompanying uncombined form of the same work.
-
-  6. Revised Versions of the GNU Lesser General Public License.
-
-  The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
-  Each version is given a distinguishing version number. If the
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
-  If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
-Library.
diff --git a/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/mit.txt b/runtime/org.argeo.slc.repo/src/main/resources/org/argeo/slc/repo/license/mit.txt
deleted file mode 100644 (file)
index e14c371..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DataInterpreter.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DataInterpreter.java
deleted file mode 100644 (file)
index 9255c76..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/**\r
- * Converts data into a format better adapted for comparison. It is typically\r
- * used to convert <code>String</code> into typed format such as\r
- * <code>BigDecimal</code>\r
- */\r
-public interface DataInterpreter {\r
-       /**\r
-        * Converts data\r
-        * \r
-        * @param key\r
-        *            any object used to differentiate the type of data (e.g.\r
-        *            column, path)\r
-        * @param value\r
-        *            the data to convert\r
-        * @return the converted object\r
-        */\r
-       public Object convert(Object key, Object value);\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Diff.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Diff.java
deleted file mode 100644 (file)
index 79dd7c4..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-import org.springframework.core.io.Resource;\r
-\r
-/** A comparator providing structured information about the differences found. */\r
-public interface Diff {\r
-       /** Performs the comparison. */\r
-       public void compare(Resource expected, Resource reached,\r
-                       DiffResult diffResult);\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssue.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssue.java
deleted file mode 100644 (file)
index eda08e5..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/** The root class for issues which happened during a diff. */\r
-public abstract class DiffIssue implements Comparable<DiffIssue> {\r
-       /** The position of this issue. */\r
-       // Was final and is not anymore in order to persist in hibernate\r
-       protected DiffPosition position;\r
-\r
-       // hibernate\r
-       private long id;\r
-\r
-       /** Constructor */\r
-       public DiffIssue(DiffPosition position) {\r
-               super();\r
-               this.position = position;\r
-       }\r
-\r
-       public int compareTo(DiffIssue o) {\r
-               return position.compareTo(o.position);\r
-       }\r
-\r
-       /** The position of this issue within the test file */\r
-       public DiffPosition getPosition() {\r
-               return position;\r
-       }\r
-\r
-       // Hibernate\r
-       @SuppressWarnings("unused")\r
-       private void setId(long id) {\r
-               this.id = id;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private long getId() {\r
-               return id;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setPosition(DiffPosition position) {\r
-               this.position = position;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssueKey.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffIssueKey.java
deleted file mode 100644 (file)
index 0be73a5..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/** Intermediate class that can hold the key to be displayed. */\r
-public abstract class DiffIssueKey extends DiffIssue {\r
-       /** The position of this issue. */\r
-       protected DiffKey key;\r
-\r
-       /** Constructor without key */\r
-       public DiffIssueKey(DiffPosition position) {\r
-               super(position);\r
-       }\r
-\r
-       /** Constructor with key */\r
-       public DiffIssueKey(DiffPosition position, DiffKey key) {\r
-               super(position);\r
-               this.key = key;\r
-       }\r
-\r
-       public Object getKey() {\r
-               return key;\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               if (key != null) {\r
-                       return key.toString();\r
-               } else {\r
-                       return "";\r
-               }\r
-       }\r
-\r
-       // Hibernate\r
-       @SuppressWarnings("unused")\r
-       private void setKey(DiffKey key) {\r
-               this.key = key;\r
-       }\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffKey.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffKey.java
deleted file mode 100644 (file)
index 8c2e60d..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/**\r
- * Object able to uniquely identify an atomic diff part. Used to identify\r
- * missings and left-overs.\r
- */\r
-public interface DiffKey {\r
-       public String toString();\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissing.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissing.java
deleted file mode 100644 (file)
index 7e7ba24..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/**\r
- * A value missing in one of the file. If its position is related to expected,\r
- * this means it is a left over in the reached, if its position is related to\r
- * the reached it means that it is missing from the reached. If the value is\r
- * null it means that the entire line is missing.\r
- */\r
-public class DiffMissing extends DiffIssueKey {\r
-\r
-       public DiffMissing(DiffPosition position, DiffKey key) {\r
-               super(position);\r
-               super.key = key;\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               if (position.relatedFile == RelatedFile.EXPECTED) {\r
-                       return position + ": left over " + super.toString();\r
-               } else if (position.relatedFile == RelatedFile.REACHED) {\r
-                       return position + ": missing " + super.toString();\r
-               }\r
-               return super.toString();\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissingXml.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffMissingXml.java
deleted file mode 100644 (file)
index 50fc7cd..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/**\r
- * <code>DiffMissing</code> using the XPath of the position as\r
- * <code>DiffKey</code>\r
- */\r
-public class DiffMissingXml extends DiffMissing {\r
-\r
-       public DiffMissingXml(XPathDiffPosition position) {\r
-               super(position, new DiffKeyXml(position.getXPath()));\r
-       }\r
-\r
-       /** Implementation of <code>DiffKey</code> based on an XPath string. */\r
-       protected static class DiffKeyXml implements DiffKey {\r
-               private final String xPath;\r
-\r
-               public DiffKeyXml(String xPath) {\r
-                       this.xPath = xPath;\r
-               }\r
-\r
-               public String getXPath() {\r
-                       return xPath;\r
-               }\r
-\r
-               @Override\r
-               public String toString() {\r
-                       return xPath;\r
-               }\r
-\r
-               @Override\r
-               public boolean equals(Object obj) {\r
-                       if (!(obj instanceof DiffKeyXml))\r
-                               return false;\r
-                       return xPath.equals(((DiffKeyXml) obj).xPath);\r
-               }\r
-\r
-               @Override\r
-               public int hashCode() {\r
-                       return xPath.hashCode();\r
-               }\r
-\r
-       }\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffNotMatched.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffNotMatched.java
deleted file mode 100644 (file)
index 9483dfe..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-import org.argeo.slc.SlcException;\r
-\r
-/** Diff issue where reached and expected values are different. */\r
-public class DiffNotMatched extends DiffIssueKey {\r
-\r
-       // To enable hibernate persistance, these object cannot be final\r
-       // private final Object expected;\r
-       // private final Object reached;\r
-\r
-       private Object expected;\r
-       private Object reached;\r
-\r
-       public DiffNotMatched(DiffPosition position, Object expected, Object reached) {\r
-               super(position);\r
-               this.expected = expected;\r
-               this.reached = reached;\r
-       }\r
-\r
-       public DiffNotMatched(DiffPosition position, Object expected,\r
-                       Object reached, DiffKey key) {\r
-               super(position, key);\r
-               this.expected = expected;\r
-               this.reached = reached;\r
-       }\r
-\r
-       public Object getExpected() {\r
-               return expected;\r
-       }\r
-\r
-       public Object getReached() {\r
-               return reached;\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               String result = position + ": not matched " + expected + " <> "\r
-                               + reached;\r
-               if (super.key != null) {\r
-                       result = result + " - Key: " + super.toString();\r
-               }\r
-\r
-               return result;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private String getExpectedStr() {\r
-               if (expected instanceof String)\r
-                       return (String) expected;\r
-               else\r
-                       throw new SlcException(\r
-                                       "Object 'expected' is of wrong type. Must be a String");\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private String getReachedStr() {\r
-               if (reached instanceof String)\r
-                       return (String) reached;\r
-               else\r
-                       throw new SlcException(\r
-                                       "Object 'reached' is of wrong type. Must be a String");\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setReachedStr(String reachedStr) {\r
-               this.reached = reachedStr;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setExpectedStr(String expectedStr) {\r
-               this.expected = expectedStr;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffPosition.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffPosition.java
deleted file mode 100644 (file)
index f8ff823..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/** The position of a diff issue within the test resource. */\r
-public abstract class DiffPosition implements Comparable<DiffPosition> {\r
-       protected RelatedFile relatedFile;\r
-\r
-       public DiffPosition(RelatedFile relatedFile) {\r
-               super();\r
-               this.relatedFile = relatedFile;\r
-       }\r
-\r
-       // For Hibernate\r
-       DiffPosition() {\r
-       }\r
-\r
-       public RelatedFile getRelatedFile() {\r
-               return relatedFile;\r
-       }\r
-\r
-       // Added to enable the new data model for persisting TabularDiffTestResult\r
-       @SuppressWarnings("unused")\r
-       private Boolean getIsReached() {\r
-               return relatedFile.equals(RelatedFile.REACHED);\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setIsReached(Boolean isReached) {\r
-               this.relatedFile = (isReached ? RelatedFile.REACHED\r
-                               : RelatedFile.EXPECTED);\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffResult.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/DiffResult.java
deleted file mode 100644 (file)
index 8cdcf7e..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.diff;
-
-/**
- * The result of a diff, to be subclassed in order to provide richer information
- */
-public interface DiffResult {
-       /** Adds a diff issue */
-       public void addDiffIssue(DiffIssue diffIssue);
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/KeyColumnsDiff.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/KeyColumnsDiff.java
deleted file mode 100644 (file)
index 8ba832d..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.diff;
-
-import java.util.List;
-
-/**
- * Diff which is based on comparison of multiple-key atomic elements (typically
- * columns in a tabular content)
- */
-public interface KeyColumnsDiff extends Diff {
-       /** $The list of key columns. */
-       List<String> getKeyColumns();
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/LineTokenizer.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/LineTokenizer.java
deleted file mode 100644 (file)
index baaa3b9..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.diff;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Parses a string as a vector of strings according to a separator, dealing
- * properly with missing values. This is intended to be used instead of the
- * standard StringTokenizer, which does not deal well with empty values.
- * Contrary to the StringTokenizer the provided String is parsed in the
- * constructor and the values stored as a property. This should therefore not be
- * used to parse long strings. No reference to the argument passed in
- * constructor is kept.
- */
-public class LineTokenizer {
-       private final List<String> tokens;
-
-       /** Complete constructor. */
-       public LineTokenizer(String stringToParse, Character separator,
-                       String noValueString) {
-               this.tokens = parse(stringToParse, separator, noValueString);
-       }
-
-       /**
-        * Parse the string as a vector of strings. Can be overridden in order to
-        * provide another implementation.
-        */
-       protected List<String> parse(final String stringToParse,
-                       final char separator, final String noValueString) {
-               // Init
-               final int NULL = -1;
-               List<String> res = new ArrayList<String>();
-               final char[] array = stringToParse.toCharArray();
-               int lastSeparatorIndex = NULL;
-
-               // Loop on chars
-               for (int currIndex = 0; currIndex < array.length; currIndex++) {
-                       char c = array[currIndex];
-                       if (c == separator) {
-                               if (currIndex == 0) {
-                                       // first char is a separator
-                                       res.add(new String(noValueString));
-                                       lastSeparatorIndex = 0;
-                               } else if (lastSeparatorIndex == NULL) {
-                                       // first separator found
-                                       res.add(new String(array, 0, currIndex));
-                                       lastSeparatorIndex = currIndex;
-                               } else if (lastSeparatorIndex != NULL
-                                               && (lastSeparatorIndex == (currIndex - 1))) {
-                                       // consecutive separators
-                                       res.add(new String(noValueString));
-                                       lastSeparatorIndex = currIndex;
-                               } else {
-                                       // simple case
-                                       res.add(new String(array, lastSeparatorIndex + 1, currIndex
-                                                       - lastSeparatorIndex - 1));
-                                       lastSeparatorIndex = currIndex;
-                               }
-                       }
-               }
-
-               // Finalize
-               if (lastSeparatorIndex == NULL) {
-                       // no separator found
-                       res.add(new String(stringToParse));
-               } else if (lastSeparatorIndex == (array.length - 1)) {
-                       // last char is a separator
-                       res.add(new String(noValueString));
-               } else {
-                       // last token
-                       res.add(new String(array, lastSeparatorIndex + 1, array.length
-                                       - lastSeparatorIndex - 1));
-               }
-               return res;
-       }
-
-       /** The tokens. */
-       public List<String> getTokens() {
-               return tokens;
-       }
-
-       /** Parse */
-       public static List<String> tokenize(String stringToParse,
-                       Character separator, String noValueString) {
-               LineTokenizer lt = new LineTokenizer(stringToParse, separator,
-                               noValueString);
-               return lt.getTokens();
-       }
-
-       /** Parse, using the empty string as no value string. */
-       public static List<String> tokenize(String stringToParse,
-                       Character separator) {
-               return tokenize(stringToParse, separator, "");
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/RelatedFile.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/RelatedFile.java
deleted file mode 100644 (file)
index e2887ba..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/** Enumeration of the types of resource tested. */\r
-public enum RelatedFile {\r
-       /** The expected resource */\r
-       EXPECTED,\r
-       /** The reached resource */\r
-       REACHED\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/TableDiffPosition.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/TableDiffPosition.java
deleted file mode 100644 (file)
index 7d5aa3e..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-import org.argeo.slc.UnsupportedException;\r
-\r
-/**\r
- * A diff position within a table structure such a CSV file or an SQL result\r
- * set.\r
- */\r
-public class TableDiffPosition extends DiffPosition {\r
-       private Integer line;\r
-       /** Can be null */\r
-       private Integer column;\r
-       /** Can be null */\r
-       private String columnName;\r
-\r
-       public TableDiffPosition(RelatedFile relatedFile, Integer line,\r
-                       Integer column, String columnName) {\r
-               super(relatedFile);\r
-               this.line = line;\r
-               this.column = column;\r
-               this.columnName = columnName;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private TableDiffPosition() {\r
-       }\r
-\r
-       public Integer getLine() {\r
-               return line;\r
-       }\r
-\r
-       public Integer getColumn() {\r
-               return column;\r
-       }\r
-\r
-       public String getColumnName() {\r
-               return columnName;\r
-       }\r
-\r
-       public int compareTo(DiffPosition dp) {\r
-               if (!(dp instanceof TableDiffPosition))\r
-                       throw new UnsupportedException("position", dp);\r
-\r
-               TableDiffPosition o = (TableDiffPosition) dp;\r
-               if (relatedFile.equals(o.relatedFile)) {\r
-                       if (line == o.line) {\r
-                               return column.compareTo(o.column);\r
-                       } else {\r
-                               return line.compareTo(o.line);\r
-                       }\r
-               } else {\r
-                       return relatedFile.compareTo(o.relatedFile);\r
-               }\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               StringBuffer buf = new StringBuffer("");\r
-               buf.append(relatedFile).append('[').append(line);\r
-               if (column != null) {\r
-                       buf.append(',').append(column);\r
-                       if (columnName != null) {\r
-                               buf.append('-').append(columnName);\r
-                       }\r
-               }\r
-               buf.append(']');\r
-               return buf.toString();\r
-       }\r
-\r
-       // Hibernate\r
-       @SuppressWarnings("unused")\r
-       private void setLine(Integer line) {\r
-               this.line = line;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setColumn(Integer column) {\r
-               this.column = column;\r
-       }\r
-\r
-       @SuppressWarnings("unused")\r
-       private void setColumnName(String columnName) {\r
-               this.columnName = columnName;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Tolerance.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/Tolerance.java
deleted file mode 100644 (file)
index 625699c..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-/** Compares objects, eventually using tolerance mechanisms. */\r
-public interface Tolerance {\r
-       /**\r
-        * Compares objects\r
-        * \r
-        * @param key\r
-        *            any object used to differentiate the type of data (e.g.\r
-        *            column, path)\r
-        * @param expected\r
-        *            the expected value\r
-        * @param reached\r
-        *            the reached value\r
-        * @return the converted object\r
-        */\r
-       public Boolean compare(Object key, Object expected, Object reached);\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/ToleranceDiff.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/ToleranceDiff.java
deleted file mode 100644 (file)
index 798b658..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.diff;
-
-import java.util.Map;
-
-/** A diff which can manage tolerances. */
-public interface ToleranceDiff extends Diff {
-
-       /** Get tolerances, key is the column name. */
-       public Map<String, String> getTolerances();
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/XPathDiffPosition.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/XPathDiffPosition.java
deleted file mode 100644 (file)
index a1ddb6e..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.diff;\r
-\r
-import org.argeo.slc.UnsupportedException;\r
-\r
-/** A diff position within an Xml file. <b>NOT YET IMPLEMENTED</b>. */\r
-public class XPathDiffPosition extends DiffPosition {\r
-\r
-       private String xPath;\r
-\r
-       public XPathDiffPosition(RelatedFile relatedFile, String path) {\r
-               super(relatedFile);\r
-               xPath = path;\r
-       }\r
-\r
-       public int compareTo(DiffPosition dp) {\r
-               if (!(dp instanceof XPathDiffPosition))\r
-                       throw new UnsupportedException("position", dp);\r
-\r
-               XPathDiffPosition o = (XPathDiffPosition) dp;\r
-               if (relatedFile.equals(o.relatedFile)) {\r
-                       return xPath.compareTo(o.xPath);\r
-               } else {\r
-                       return relatedFile.compareTo(o.relatedFile);\r
-               }\r
-       }\r
-\r
-       public String getXPath() {\r
-               return xPath;\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               return xPath;\r
-       }\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/package.html b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/diff/package.html
deleted file mode 100644 (file)
index a58e685..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<html>\r
-<head></head>\r
-<body>\r
-Abstraction of diff comparison with structured results.\r
-</body>\r
-</html>
\ No newline at end of file
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/AbstractJschTask.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/AbstractJschTask.java
deleted file mode 100644 (file)
index ed37069..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Session;
-
-public abstract class AbstractJschTask implements Runnable {
-       private final Log log = LogFactory.getLog(getClass());
-
-       private SshTarget sshTarget;
-
-       protected Session openSession() {
-               if (sshTarget.getSession() != null) {
-                       Session session = sshTarget.getSession();
-                       if (session.isConnected()) {
-                               if (log.isTraceEnabled())
-                                       log.debug("Using cached session to " + getSshTarget()
-                                                       + " via SSH");
-                               return session;
-                       }
-               }
-
-               try {
-                       JSch jsch = new JSch();
-                       if (sshTarget.getUsePrivateKey()
-                                       && sshTarget.getLocalPrivateKey().exists())
-                               jsch.addIdentity(sshTarget.getLocalPrivateKey()
-                                               .getAbsolutePath());
-                       Session session = jsch.getSession(getSshTarget().getUser(),
-                                       getSshTarget().getHost(), getSshTarget().getPort());
-
-                       session.setUserInfo(getSshTarget().getUserInfo());
-                       session.setServerAliveInterval(1000);
-                       session.connect();
-                       if (log.isTraceEnabled())
-                               log.trace("Connected to " + getSshTarget() + " via SSH");
-                       if (sshTarget.getSession() != null) {
-                               if (log.isTraceEnabled())
-                                       log.trace("The cached session to " + getSshTarget()
-                                                       + " was disconnected and was reset.");
-                               sshTarget.setSession(session);
-                       }
-                       return session;
-               } catch (JSchException e) {
-                       if (sshTarget.getUserInfo() instanceof SimpleUserInfo)
-                               ((SimpleUserInfo) sshTarget.getUserInfo()).reset();
-                       throw new SlcException("Could not open session to "
-                                       + getSshTarget(), e);
-               }
-       }
-
-       public void run() {
-               Session session = openSession();
-               try {
-                       run(session);
-               } finally {
-                       if (sshTarget != null && sshTarget.getSession() == null) {
-                               session.disconnect();
-                               if (log.isTraceEnabled())
-                                       log.trace("Disconnected from " + getSshTarget()
-                                                       + " via SSH");
-                       }
-               }
-       }
-
-       abstract void run(Session session);
-
-       protected int checkAck(InputStream in) throws IOException {
-               int b = in.read();
-               // b may be 0 for success,
-               // 1 for error,
-               // 2 for fatal error,
-               // -1
-               if (b == 0)
-                       return b;
-               else if (b == -1)
-                       return b;// throw new SlcException("SSH ack returned -1");
-               else if (b == 1 || b == 2) {
-                       StringBuffer sb = new StringBuffer();
-                       int c;
-                       do {
-                               c = in.read();
-                               sb.append((char) c);
-                       } while (c != '\n');
-                       if (b == 1) { // error
-                               throw new SlcException("SSH ack error: " + sb.toString());
-                       }
-                       if (b == 2) { // fatal error
-                               throw new SlcException("SSH fatal error: " + sb.toString());
-                       }
-               }
-               return b;
-       }
-
-       public SshTarget getSshTarget() {
-               if (sshTarget == null)
-                       throw new SlcException("No SSH target defined.");
-               return sshTarget;
-       }
-
-       public void setSshTarget(SshTarget sshTarget) {
-               this.sshTarget = sshTarget;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/CallbackHandlerUserInfo.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/CallbackHandlerUserInfo.java
deleted file mode 100644 (file)
index ab358aa..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.PasswordCallback;
-
-import org.argeo.slc.SlcException;
-
-/** Retrieve a password or a passphrase using a standard callback handler. */
-public final class CallbackHandlerUserInfo extends SimpleUserInfo {
-       private CallbackHandler callbackHandler;
-
-       private Boolean alwaysPrompt = false;
-
-       public boolean promptPassphrase(String message) {
-               if (passphrase != null)
-                       return true;
-
-               if (!alwaysPrompt && passphraseSafe != null)
-                       return true;
-
-               reset();
-               PasswordCallback passwordCb = new PasswordCallback("SSH Passphrase",
-                               false);
-               Callback[] dialogCbs = new Callback[] { passwordCb };
-               try {
-                       callbackHandler.handle(dialogCbs);
-                       passphraseSafe = passwordCb.getPassword();
-                       return passphraseSafe != null;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot ask for a password", e);
-               }
-       }
-
-       public boolean promptPassword(String message) {
-               if (password != null)
-                       return true;
-
-               if (!alwaysPrompt && passwordSafe != null)
-                       return true;
-
-               reset();
-               PasswordCallback passwordCb = new PasswordCallback("SSH Password",
-                               false);
-               Callback[] dialogCbs = new Callback[] { passwordCb };
-               try {
-                       callbackHandler.handle(dialogCbs);
-                       passwordSafe = passwordCb.getPassword();
-                       return passwordSafe != null;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot ask for a password", e);
-               }
-       }
-
-       public void setAlwaysPrompt(Boolean alwaysPrompt) {
-               this.alwaysPrompt = alwaysPrompt;
-       }
-
-       public void setCallbackHandler(CallbackHandler defaultCallbackHandler) {
-               this.callbackHandler = defaultCallbackHandler;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschContextSession.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschContextSession.java
deleted file mode 100644 (file)
index 44d0bcc..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.beans.factory.DisposableBean;
-import org.springframework.beans.factory.InitializingBean;
-
-import com.jcraft.jsch.Session;
-
-/** Caches a JSCH session in the the ssh target. */
-public class JschContextSession extends AbstractJschTask implements
-               InitializingBean, DisposableBean {
-       private final static Log log = LogFactory.getLog(JschContextSession.class);
-       private Boolean autoconnect = false;
-
-       @Override
-       void run(Session session) {
-               // clear();
-               getSshTarget().setSession(session);
-               if (log.isDebugEnabled())
-                       log.debug("Cached SSH context session to " + getSshTarget());
-       }
-
-       public void afterPropertiesSet() throws Exception {
-               // if (log.isDebugEnabled())
-               // log.debug(getClass() + ".afterPropertiesSet(), " + beanName + ", "
-               // + this);
-               if (autoconnect)
-                       try {
-                               run();
-                       } catch (Exception e) {
-                               log.error("Could not automatically open session", e);
-                       }
-       }
-
-       public void destroy() throws Exception {
-               clear();
-       }
-
-       public void clear() {
-               SshTarget sshTarget = getSshTarget();
-               synchronized (sshTarget) {
-                       if (sshTarget.getSession() != null) {
-                               sshTarget.getSession().disconnect();
-                               sshTarget.setSession(null);
-                               if (log.isDebugEnabled())
-                                       log.debug("Cleared cached SSH context session to "
-                                                       + getSshTarget());
-                       }
-               }
-       }
-
-       public void setAutoconnect(Boolean autoconnect) {
-               this.autoconnect = autoconnect;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschExecutor.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschExecutor.java
deleted file mode 100644 (file)
index b15694c..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-
-import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.ExecuteException;
-import org.apache.commons.exec.ExecuteResultHandler;
-import org.apache.commons.exec.ExecuteStreamHandler;
-import org.apache.commons.exec.ExecuteWatchdog;
-import org.apache.commons.exec.Executor;
-import org.apache.commons.exec.ProcessDestroyer;
-
-/** A Commons Exec executor executing remotely via SSH */
-public class JschExecutor implements Executor {
-       private File workingDirectory;
-       private ExecuteStreamHandler streamHandler;
-
-       private SshTarget sshTarget;
-
-       public void setExitValue(int value) {
-               // TODO Auto-generated method stub
-
-       }
-
-       public void setExitValues(int[] values) {
-               // TODO Auto-generated method stub
-
-       }
-
-       public boolean isFailure(int exitValue) {
-               return Executor.INVALID_EXITVALUE == exitValue;
-       }
-
-       public ExecuteStreamHandler getStreamHandler() {
-               return streamHandler;
-       }
-
-       public void setStreamHandler(ExecuteStreamHandler streamHandler) {
-               this.streamHandler = streamHandler;
-       }
-
-       public ExecuteWatchdog getWatchdog() {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       public void setWatchdog(ExecuteWatchdog watchDog) {
-               // TODO Auto-generated method stub
-
-       }
-
-       public ProcessDestroyer getProcessDestroyer() {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       public void setProcessDestroyer(ProcessDestroyer processDestroyer) {
-               // TODO Auto-generated method stub
-
-       }
-
-       public File getWorkingDirectory() {
-               return workingDirectory;
-       }
-
-       public void setWorkingDirectory(File workingDirectory) {
-               this.workingDirectory = workingDirectory;
-       }
-
-       public int execute(CommandLine command) throws ExecuteException,
-                       IOException {
-               return execute(command, (Map) null);
-       }
-
-       public int execute(CommandLine command, Map environment)
-                       throws ExecuteException, IOException {
-               String cmd = command.toString();
-               if(workingDirectory!=null)
-                       cmd = "cd "+workingDirectory.getPath()+" && "+cmd;
-               RemoteExec remoteExec = new RemoteExec();
-               remoteExec.setSshTarget(sshTarget);
-               remoteExec.setStreamHandler(streamHandler);
-               remoteExec.setCommand(cmd);
-               if (environment != null)
-                       remoteExec.setEnv(environment);
-               remoteExec.run();
-               return remoteExec.getLastExitStatus() != null ? remoteExec
-                               .getLastExitStatus() : Executor.INVALID_EXITVALUE;
-       }
-
-       public void execute(CommandLine command, ExecuteResultHandler handler)
-                       throws ExecuteException, IOException {
-               // TODO Auto-generated method stub
-
-       }
-
-       public void execute(CommandLine command, Map environment,
-                       ExecuteResultHandler handler) throws ExecuteException, IOException {
-
-       }
-
-       public SshTarget getSshTarget() {
-               return sshTarget;
-       }
-
-       public void setSshTarget(SshTarget sshTarget) {
-               this.sshTarget = sshTarget;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschMultiTasks.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/JschMultiTasks.java
deleted file mode 100644 (file)
index 40d4034..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.jcraft.jsch.Session;
-
-public class JschMultiTasks extends AbstractJschTask {
-       private List<AbstractJschTask> tasks = new ArrayList<AbstractJschTask>();
-
-       @Override
-       protected void run(Session session) {
-               for (AbstractJschTask task : tasks) {
-                       task.setSshTarget(getSshTarget());
-                       task.run(session);
-               }
-       }
-
-       public void setTasks(List<AbstractJschTask> tasks) {
-               this.tasks = tasks;
-       }
-
-       public List<AbstractJschTask> getTasks() {
-               return tasks;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/RemoteExec.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/RemoteExec.java
deleted file mode 100644 (file)
index 691d0d6..0000000
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.apache.commons.exec.ExecuteStreamHandler;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.ExecutionResources;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.springframework.core.io.Resource;
-import org.springframework.util.StringUtils;
-
-import com.jcraft.jsch.Channel;
-import com.jcraft.jsch.ChannelExec;
-import com.jcraft.jsch.ChannelShell;
-import com.jcraft.jsch.Session;
-
-public class RemoteExec extends AbstractJschTask {
-       private final static Log log = LogFactory.getLog(RemoteExec.class);
-
-       private Boolean failOnBadExitStatus = true;
-
-       private List<String> commands = new ArrayList<String>();
-       private String command;
-       private SystemCall systemCall;
-       private List<SystemCall> systemCalls = new ArrayList<SystemCall>();
-       private Resource script;
-       private Boolean xForwarding = false;
-       private Boolean agentForwarding = false;
-       private Boolean forceShell = false;
-       private Map<String, String> env = new HashMap<String, String>();
-       private Resource stdIn = null;
-       private Resource stdOut = null;
-       private ExecutionResources executionResources;
-
-       private String user;
-
-       private ExecuteStreamHandler streamHandler = null;
-
-       private Integer lastExitStatus = null;
-       /**
-        * If set, stdout is written to it as a list of lines. Cleared before each
-        * run.
-        */
-       private List<String> stdOutLines = null;
-       private Boolean logEvenIfStdOutLines = false;
-       private Boolean quiet = false;
-
-       public RemoteExec() {
-       }
-
-       public RemoteExec(SshTarget sshTarget, String cmd) {
-               setSshTarget(sshTarget);
-               setCommand(cmd);
-       }
-
-       public void run(Session session) {
-               List<String> commandsToUse = new ArrayList<String>(commands);
-               String commandToUse = command;
-               // convert system calls
-               if (systemCall != null) {
-                       if (command != null)
-                               throw new SlcException("Cannot specify command AND systemCall");
-                       commandToUse = convertSystemCall(systemCall);
-               }
-
-               if (systemCalls.size() != 0) {
-                       if (commandsToUse.size() != 0)
-                               throw new SlcException(
-                                               "Cannot specify commands AND systemCalls");
-                       for (SystemCall systemCall : systemCalls)
-                               commandsToUse.add(convertSystemCall(systemCall));
-               }
-
-               if (script != null) {
-                       // TODO: simply pass the script as a string command
-                       if (commandsToUse.size() != 0)
-                               throw new SlcException("Cannot specify commands and script");
-                       BufferedReader reader = null;
-                       try {
-                               reader = new BufferedReader(new InputStreamReader(
-                                               script.getInputStream()));
-                               String line = null;
-                               while ((line = reader.readLine()) != null) {
-                                       if (!StringUtils.hasText(line))
-                                               continue;
-                                       commandsToUse.add(line);
-                               }
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot read script " + script, e);
-                       } finally {
-                               IOUtils.closeQuietly(reader);
-                       }
-               }
-
-               if (forceShell) {
-                       // for the time being do not interpret both \n and ;
-                       // priority to \n
-                       // until we know how to parse ; within ""
-                       if (commandToUse.indexOf('\n') >= 0) {
-                               StringTokenizer st = new StringTokenizer(commandToUse, "\n");
-                               while (st.hasMoreTokens()) {
-                                       String cmd = st.nextToken();
-                                       commandsToUse.add(cmd);
-                               }
-                       } else if (commandToUse.indexOf(';') >= 0) {
-                               StringTokenizer st = new StringTokenizer(commandToUse, ";");
-                               while (st.hasMoreTokens()) {
-                                       String cmd = st.nextToken();
-                                       commandsToUse.add(cmd);
-                               }
-                       } else {
-                               commandsToUse.add(commandToUse);
-                       }
-                       commandToUse = null;
-               }
-
-               // run as user
-               if (user != null) {
-                       if (commandsToUse.size() > 0) {
-                               commandsToUse.add(0, "su - " + user);
-                               commandsToUse.add("exit");
-                       } else {
-                               if (command.indexOf('\"') >= 0)
-                                       throw new SlcException(
-                                                       "Don't know how to su a command with \", use shell instead.");
-                               commandToUse = "su - " + user + " -c \"" + command + "\"";
-                       }
-               }
-
-               // execute command(s)
-               if (commandToUse != null) {
-                       if (commandsToUse.size() != 0)
-                               throw new SlcException(
-                                               "Specify either a single command or a list of commands.");
-                       remoteExec(session, commandToUse);
-               } else {
-                       if (commandsToUse.size() == 0)
-                               throw new SlcException(
-                                               "Neither a single command or a list of commands has been specified.");
-
-                       remoteExec(session, commandsToUse, script != null ? "script "
-                                       + script.getFilename() : commandsToUse.size() + " commands");
-               }
-       }
-
-       protected String convertSystemCall(SystemCall systemCall) {
-               // TODO: prepend environment variables
-               // TODO: deal with exec dir
-               return systemCall.asCommand();
-       }
-
-       protected void remoteExec(Session session, final List<String> commands,
-                       String description) {
-               try {
-                       final ChannelShell channel = (ChannelShell) session
-                                       .openChannel("shell");
-                       channel.setInputStream(null);
-                       channel.setXForwarding(xForwarding);
-                       channel.setAgentForwarding(agentForwarding);
-                       channel.setEnv(new Hashtable<String, String>(env));
-
-                       /*
-                        * // Choose the pty-type "vt102".
-                        * ((ChannelShell)channel).setPtyType("vt102");
-                        */
-                       // Writer thread
-                       final BufferedWriter writer = new BufferedWriter(
-                                       new OutputStreamWriter(channel.getOutputStream()));
-
-                       if (log.isDebugEnabled())
-                               log.debug("Run " + description + " on " + getSshTarget()
-                                               + "...");
-                       channel.connect();
-
-                       // write commands to shell
-                       Thread writerThread = new Thread("Shell writer " + getSshTarget()) {
-                               @Override
-                               public void run() {
-                                       try {
-                                               for (String line : commands) {
-                                                       if (!StringUtils.hasText(line))
-                                                               continue;
-                                                       writer.write(line);
-                                                       writer.newLine();
-                                               }
-                                               writer.append("exit");
-                                               writer.newLine();
-                                               writer.flush();
-                                               // channel.disconnect();
-                                       } catch (IOException e) {
-                                               throw new SlcException("Cannot write to shell on "
-                                                               + getSshTarget(), e);
-                                       } finally {
-                                               IOUtils.closeQuietly(writer);
-                                       }
-                               }
-                       };
-                       writerThread.start();
-
-                       readStdOut(channel);
-                       checkExitStatus(channel);
-                       channel.disconnect();
-
-               } catch (Exception e) {
-                       throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
-                                       e);
-               }
-
-       }
-
-       protected void remoteExec(Session session, String command) {
-               try {
-                       final ChannelExec channel = (ChannelExec) session
-                                       .openChannel("exec");
-                       channel.setCommand(command);
-
-                       channel.setInputStream(null);
-                       channel.setXForwarding(xForwarding);
-                       channel.setAgentForwarding(agentForwarding);
-                       channel.setEnv(new Hashtable<String, String>(env));
-                       channel.setErrStream(null);
-
-                       // Standard Error
-                       readStdErr(channel);
-
-                       if (log.isTraceEnabled())
-                               log.trace("Run '" + command + "' on " + getSshTarget() + "...");
-                       channel.connect();
-
-                       readStdIn(channel);
-                       readStdOut(channel);
-
-                       if (streamHandler != null) {
-                               streamHandler.start();
-                               while (!channel.isClosed()) {
-                                       try {
-                                               Thread.sleep(100);
-                                       } catch (Exception e) {
-                                               break;
-                                       }
-                               }
-                       }
-
-                       checkExitStatus(channel);
-                       channel.disconnect();
-               } catch (Exception e) {
-                       throw new SlcException("Cannot execute remotely '" + command
-                                       + "' on " + getSshTarget(), e);
-               }
-       }
-
-       protected void readStdOut(Channel channel) {
-               try {
-                       if (stdOut != null) {
-                               OutputStream localStdOut = createOutputStream(stdOut);
-                               try {
-                                       IOUtils.copy(channel.getInputStream(), localStdOut);
-                               } finally {
-                                       IOUtils.closeQuietly(localStdOut);
-                               }
-                       } else if (streamHandler != null) {
-                               if (channel.getInputStream() != null)
-                                       streamHandler.setProcessOutputStream(channel
-                                                       .getInputStream());
-                       } else {
-                               BufferedReader stdOut = null;
-                               try {
-                                       InputStream in = channel.getInputStream();
-                                       stdOut = new BufferedReader(new InputStreamReader(in));
-                                       String line = null;
-                                       while ((line = stdOut.readLine()) != null) {
-                                               if (!line.trim().equals("")) {
-
-                                                       if (stdOutLines != null) {
-                                                               stdOutLines.add(line);
-                                                               if (logEvenIfStdOutLines && !quiet)
-                                                                       log.info(line);
-                                                       } else {
-                                                               if (!quiet)
-                                                                       log.info(line);
-                                                       }
-                                               }
-                                       }
-                               } finally {
-                                       IOUtils.closeQuietly(stdOut);
-                               }
-                       }
-               } catch (IOException e) {
-                       throw new SlcException("Cannot redirect stdout from "
-                                       + getSshTarget(), e);
-               }
-       }
-
-       protected void readStdErr(final ChannelExec channel) {
-               if (streamHandler != null) {
-                       try {
-                               streamHandler.setProcessOutputStream(channel.getErrStream());
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot read stderr from "
-                                               + getSshTarget(), e);
-                       }
-               } else {
-                       new Thread("stderr " + getSshTarget()) {
-                               public void run() {
-                                       BufferedReader stdErr = null;
-                                       try {
-                                               InputStream in = channel.getErrStream();
-                                               stdErr = new BufferedReader(new InputStreamReader(in));
-                                               String line = null;
-                                               while ((line = stdErr.readLine()) != null) {
-                                                       if (!line.trim().equals(""))
-                                                               log.error(line);
-                                               }
-                                       } catch (IOException e) {
-                                               if (log.isDebugEnabled())
-                                                       log.error("Cannot read stderr from "
-                                                                       + getSshTarget(), e);
-                                       } finally {
-                                               IOUtils.closeQuietly(stdErr);
-                                       }
-                               }
-                       }.start();
-               }
-       }
-
-       protected void readStdIn(final ChannelExec channel) {
-               if (stdIn != null) {
-                       Thread stdInThread = new Thread("Stdin " + getSshTarget()) {
-                               @Override
-                               public void run() {
-                                       OutputStream out = null;
-                                       try {
-                                               out = channel.getOutputStream();
-                                               IOUtils.copy(stdIn.getInputStream(), out);
-                                       } catch (IOException e) {
-                                               throw new SlcException("Cannot write stdin on "
-                                                               + getSshTarget(), e);
-                                       } finally {
-                                               IOUtils.closeQuietly(out);
-                                       }
-                               }
-                       };
-                       stdInThread.start();
-               } else if (streamHandler != null) {
-                       try {
-                               streamHandler.setProcessInputStream(channel.getOutputStream());
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot write stdin on "
-                                               + getSshTarget(), e);
-                       }
-               }
-       }
-
-       protected void checkExitStatus(Channel channel) {
-               if (channel.isClosed()) {
-                       lastExitStatus = channel.getExitStatus();
-                       if (lastExitStatus == 0) {
-                               if (log.isTraceEnabled())
-                                       log.trace("Remote execution exit status: " + lastExitStatus);
-                       } else {
-                               String msg = "Remote execution failed with " + " exit status: "
-                                               + lastExitStatus;
-                               if (failOnBadExitStatus)
-                                       throw new SlcException(msg);
-                               else
-                                       log.error(msg);
-                       }
-               }
-
-       }
-
-       protected OutputStream createOutputStream(Resource target) {
-               FileOutputStream out = null;
-               try {
-
-                       final File file;
-                       if (executionResources != null)
-                               file = new File(executionResources.getAsOsPath(target, true));
-                       else
-                               file = target.getFile();
-                       out = new FileOutputStream(file, false);
-               } catch (IOException e) {
-                       log.error("Cannot get file for " + target, e);
-                       IOUtils.closeQuietly(out);
-               }
-               return out;
-       }
-
-       public Integer getLastExitStatus() {
-               return lastExitStatus;
-       }
-
-       public void setStreamHandler(ExecuteStreamHandler executeStreamHandler) {
-               this.streamHandler = executeStreamHandler;
-       }
-
-       public void setCommand(String command) {
-               this.command = command;
-       }
-
-       public void setCommands(List<String> commands) {
-               this.commands = commands;
-       }
-
-       public void setFailOnBadExitStatus(Boolean failOnBadExitStatus) {
-               this.failOnBadExitStatus = failOnBadExitStatus;
-       }
-
-       public void setSystemCall(SystemCall systemCall) {
-               this.systemCall = systemCall;
-       }
-
-       public void setSystemCalls(List<SystemCall> systemCalls) {
-               this.systemCalls = systemCalls;
-       }
-
-       public void setScript(Resource script) {
-               this.script = script;
-       }
-
-       public void setxForwarding(Boolean xForwarding) {
-               this.xForwarding = xForwarding;
-       }
-
-       public void setAgentForwarding(Boolean agentForwarding) {
-               this.agentForwarding = agentForwarding;
-       }
-
-       public void setEnv(Map<String, String> env) {
-               this.env = env;
-       }
-
-       public void setForceShell(Boolean forceShell) {
-               this.forceShell = forceShell;
-       }
-
-       public List<String> getCommands() {
-               return commands;
-       }
-
-       public void setStdOutLines(List<String> stdOutLines) {
-               this.stdOutLines = stdOutLines;
-       }
-
-       public void setLogEvenIfStdOutLines(Boolean logEvenIfStdOutLines) {
-               this.logEvenIfStdOutLines = logEvenIfStdOutLines;
-       }
-
-       public void setQuiet(Boolean quiet) {
-               this.quiet = quiet;
-       }
-
-       public void setStdIn(Resource stdIn) {
-               this.stdIn = stdIn;
-       }
-
-       public void setStdOut(Resource stdOut) {
-               this.stdOut = stdOut;
-       }
-
-       public void setExecutionResources(ExecutionResources executionResources) {
-               this.executionResources = executionResources;
-       }
-
-       public void setUser(String user) {
-               this.user = user;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpFrom.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpFrom.java
deleted file mode 100644 (file)
index 3f83778..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-
-import com.jcraft.jsch.Channel;
-import com.jcraft.jsch.ChannelExec;
-import com.jcraft.jsch.Session;
-
-public class ScpFrom extends AbstractJschTask {
-       private final static Log log = LogFactory.getLog(ScpFrom.class);
-
-       private Resource localResource;
-       private String remotePath;
-       private Boolean mkdir = false;
-
-       public void run(Session session) {
-               if (localResource != null) {
-                       File lFile;
-                       try {
-                               lFile = localResource.getFile();
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot interpret resource "
-                                               + localResource + " as file.", e);
-                       }
-                       downloadFile(session, lFile, remotePath);
-               }
-       }
-
-       protected void downloadFile(Session session, File localFile,
-                       String remoteFile) {
-               OutputStream out = null;
-               OutputStream channelOut;
-               InputStream channelIn;
-               try {
-                       // exec 'scp -f rfile' remotely
-                       String command = "scp -f " + remoteFile;
-                       Channel channel = session.openChannel("exec");
-                       ((ChannelExec) channel).setCommand(command);
-
-                       // get I/O streams for remote scp
-                       channelOut = channel.getOutputStream();
-                       channelIn = channel.getInputStream();
-
-                       channel.connect();
-
-                       byte[] buf = new byte[1024];
-
-                       // send '\0'
-                       buf[0] = 0;
-                       channelOut.write(buf, 0, 1);
-                       channelOut.flush();
-
-                       while (true) {
-                               int c = checkAck(channelIn);
-                               if (c != 'C') {
-                                       break;
-                               }
-
-                               // read '0644 '
-                               channelIn.read(buf, 0, 5);
-
-                               long filesize = 0L;
-                               while (true) {
-                                       if (channelIn.read(buf, 0, 1) < 0) {
-                                               // error
-                                               break;
-                                       }
-                                       if (buf[0] == ' ')
-                                               break;
-                                       filesize = filesize * 10L + (long) (buf[0] - '0');
-                               }
-
-                               String remoteFileName = null;
-                               for (int i = 0;; i++) {
-                                       channelIn.read(buf, i, 1);
-                                       if (buf[i] == (byte) 0x0a) {
-                                               remoteFileName = new String(buf, 0, i);
-                                               break;
-                                       }
-                               }
-
-                               // System.out.println("filesize="+filesize+", file="+file);
-
-                               // send '\0'
-                               buf[0] = 0;
-                               channelOut.write(buf, 0, 1);
-                               channelOut.flush();
-
-                               // Create a s adirectory if it doesn't exists
-                               if (!localFile.exists() && mkdir)
-                                       localFile.mkdirs();
-
-                               // read a content of lfile
-                               String localPath = localFile.isDirectory() ? localFile
-                                               .getPath()
-                                               + File.separator + remoteFileName : localFile.getPath();
-
-                               out = new FileOutputStream(localPath);
-                               int foo;
-                               while (true) {
-                                       if (buf.length < filesize)
-                                               foo = buf.length;
-                                       else
-                                               foo = (int) filesize;
-                                       foo = channelIn.read(buf, 0, foo);
-                                       if (foo < 0) {
-                                               // error
-                                               break;
-                                       }
-                                       out.write(buf, 0, foo);
-                                       filesize -= foo;
-                                       if (filesize == 0L)
-                                               break;
-                               }
-
-                               checkAck(channelIn);
-
-                               // send '\0'
-                               buf[0] = 0;
-                               channelOut.write(buf, 0, 1);
-                               channelOut.flush();
-
-                               if (log.isDebugEnabled())
-                                       log.debug("Finished downloading " + remoteFile + " on "
-                                                       + getSshTarget() + " to " + localPath);
-                       }
-
-                       channel.disconnect();
-                       // session.disconnect();
-               } catch (Exception e) {
-                       throw new SlcException("Cannot download " + remoteFile + " to "
-                                       + localFile, e);
-               } finally {
-                       IOUtils.closeQuietly(out);
-               }
-       }
-
-       public void setLocalResource(Resource localFile) {
-               this.localResource = localFile;
-       }
-
-       public void setRemotePath(String remoteFile) {
-               this.remotePath = remoteFile;
-       }
-
-       public void setMkdir(Boolean mkdir) {
-               this.mkdir = mkdir;
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpTo.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpTo.java
deleted file mode 100644 (file)
index c0af991..0000000
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-import org.springframework.util.AntPathMatcher;
-import org.springframework.util.PathMatcher;
-import org.springframework.util.StringUtils;
-
-import com.jcraft.jsch.Channel;
-import com.jcraft.jsch.ChannelExec;
-import com.jcraft.jsch.Session;
-
-public class ScpTo extends AbstractJschTask {
-       private final static Log log = LogFactory.getLog(ScpTo.class);
-
-       private Resource localResource;
-       private String remotePath;
-
-       private String dir;
-       private String remoteDir;
-       private List<String> includes = new ArrayList<String>();
-
-       private List<String> excludes = new ArrayList<String>();
-
-       private PathMatcher pathMatcher;
-
-       public void run(Session session) {
-               if (StringUtils.hasText(dir)) {
-                       if (!StringUtils.hasText(remoteDir))
-                               throw new SlcException("Remote dir has to be specified.");
-
-                       String dirOs = dir.replace('/', File.separatorChar);
-                       if (dirOs.charAt(dir.length() - 1) != File.separatorChar) {
-                               dirOs = dirOs + File.separator;
-                       }
-
-                       if (pathMatcher == null)
-                               pathMatcher = new AntPathMatcher();
-
-                       log.info("Start multiple scp based on " + dirOs);
-                       scanDir(session, dirOs, "", includes, excludes);
-               }
-
-               if (localResource != null) {
-                       uploadResource(session, localResource);
-               }
-       }
-
-       protected void scanDir(Session session, String dir, String currentRelPath,
-                       List<String> includes, List<String> excludes) {
-               File[] files = new File(dir).listFiles();
-               for (File file : files) {
-                       if (!file.isDirectory()) {
-                               String relPath = currentRelPath.concat(file.getName());
-                               if (match(relPath, includes, excludes, false)) {
-                                       uploadFile(session, file, remoteDir + '/' + relPath);
-                               }
-                       } else {
-                               String relPath = currentRelPath.concat(file.getName()).concat(
-                                               "/");
-                               if (match(relPath, includes, excludes, true)) {
-                                       String nextDir = dir.concat(file.getName()).concat(
-                                                       File.separator);
-                                       scanDir(session, nextDir, relPath, includes, excludes);
-                               }
-                       }
-               }
-       }
-
-       protected Boolean match(String path, List<String> includes,
-                       List<String> excludes, boolean matchStart) {
-               for (String patternIn : includes) {
-                       boolean matchIn = matchStart ? pathMatcher.matchStart(patternIn,
-                                       path) : pathMatcher.match(patternIn, path);
-                       if (matchIn) {
-                               // Could be included, check excludes
-                               boolean excluded = false;
-                               ex: for (String patternEx : excludes) {
-                                       boolean matchEx = matchStart ? pathMatcher.matchStart(
-                                                       patternEx, path) : pathMatcher.match(patternEx,
-                                                       path);
-
-                                       if (matchEx) {
-                                               excluded = true;
-                                               break ex;
-                                       }
-                               }
-                               if (!excluded)
-                                       return true;
-                       }
-               }
-               return false;
-       }
-
-       protected void uploadFile(Session session, File file, String remoteFile) {
-               try {
-                       upload(session, new FileInputStream(file), file.length(), file
-                                       .getPath(), file.toString(), remoteFile);
-               } catch (FileNotFoundException e) {
-                       throw new SlcException("Cannot upload " + file, e);
-               }
-       }
-
-       protected void uploadResource(Session session, Resource resource) {
-               String targetPath = remotePath != null ? remotePath : remoteDir + '/'
-                               + resource.getFilename();
-               try {
-                       File lFile = resource.getFile();
-                       uploadFile(session, lFile, targetPath);
-               } catch (IOException e) {
-                       // no underlying file found
-                       // load the resource in memory before transferring it
-                       InputStream in = null;
-                       try {
-                               byte[] arr;
-                               String path;
-                               if (resource instanceof ByteArrayResource) {
-                                       arr = ((ByteArrayResource) resource).getByteArray();
-                                       path = "bytearray";
-                               } else {
-                                       in = resource.getInputStream();
-                                       ByteArrayOutputStream out = new ByteArrayOutputStream();
-                                       IOUtils.copy(in, out);
-                                       arr = out.toByteArray();
-                                       path = resource.getURL().getPath();
-                                       if (path.startsWith("/"))
-                                               path = path.substring(1);
-                               }
-                               ByteArrayInputStream content = new ByteArrayInputStream(arr);
-                               upload(session, content, arr.length, path, resource.toString(),
-                                               targetPath);
-                               arr = null;
-                       } catch (IOException e1) {
-                               throw new SlcException("Can not interpret resource "
-                                               + localResource, e1);
-                       } finally {
-                               IOUtils.closeQuietly(in);
-                               // no need to close byte arrays streams
-                       }
-               }
-       }
-
-       protected void upload(Session session, InputStream in, long size,
-                       String path, String sourceDesc, String remoteFile) {
-               OutputStream channelOut;
-               InputStream channelIn;
-               try {
-
-                       // exec 'scp -t rfile' remotely
-                       String command = "scp -p -t " + remoteFile;
-                       Channel channel = session.openChannel("exec");
-                       ((ChannelExec) channel).setCommand(command);
-
-                       // get I/O streams for remote scp
-                       channelOut = channel.getOutputStream();
-                       channelIn = channel.getInputStream();
-
-                       channel.connect();
-                       checkAck(channelIn);
-
-                       // send "C0644 filesize filename", where filename should not include
-                       // '/'
-                       long filesize = size;
-                       command = "C0644 " + filesize + " ";
-                       int index = path.lastIndexOf('/');
-                       if (index > 0) {
-                               command += path.substring(index + 1);
-                       } else {
-                               command += path;
-                       }
-                       command += "\n";
-
-                       channelOut.write(command.getBytes());
-                       channelOut.flush();
-                       checkAck(channelIn);
-
-                       if (log.isTraceEnabled())
-                               log.debug("Start copy of " + sourceDesc + " to " + remoteFile
-                                               + " on " + getSshTarget() + "...");
-
-                       final long oneMB = 1024l;// in KB
-                       final long tenMB = 10 * oneMB;// in KB
-
-                       // send a content of lfile
-                       byte[] buf = new byte[1024];
-                       long cycleCount = 0;
-                       long nbrOfBytes = 0;
-                       while (true) {
-                               int len = in.read(buf, 0, buf.length);
-                               if (len <= 0)
-                                       break;
-                               channelOut.write(buf, 0, len); // out.flush();
-                               nbrOfBytes = nbrOfBytes + len;
-                               if (((cycleCount % oneMB) == 0) && cycleCount != 0)// each 1 MB
-                                       System.out.print('#');
-                               if (((cycleCount % (tenMB)) == 0) && cycleCount != 0)// each 10
-                                       // MB
-                                       System.out.print(" - " + cycleCount / tenMB + "0 MB\n");
-                               cycleCount++;
-                       }
-                       // send '\0'
-                       buf[0] = 0;
-                       channelOut.write(buf, 0, 1);
-                       channelOut.flush();
-                       checkAck(channelIn);
-
-                       if (log.isDebugEnabled())
-                               log.debug("Transferred to " + remoteFile + " ("
-                                               + sizeDesc(nbrOfBytes) + ") on " + getSshTarget()
-                                               + " from " + sourceDesc);
-
-                       IOUtils.closeQuietly(channelOut);
-
-                       channel.disconnect();
-               } catch (Exception e) {
-                       throw new SlcException("Cannot copy " + path + " to " + remoteFile,
-                                       e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       protected String sizeDesc(Long nbrOfBytes) {
-               if (nbrOfBytes < 1024)
-                       return nbrOfBytes + " B";
-               else if (nbrOfBytes < 1024 * 1024)
-                       return (nbrOfBytes / 1024) + " KB";
-               else
-                       return nbrOfBytes / (1024 * 1024) + " MB";
-       }
-
-       public void setLocalResource(Resource localFile) {
-               this.localResource = localFile;
-       }
-
-       public void setRemotePath(String remoteFile) {
-               this.remotePath = remoteFile;
-       }
-
-       public void setDir(String dir) {
-               this.dir = dir;
-       }
-
-       public void setRemoteDir(String remoteDir) {
-               this.remoteDir = remoteDir;
-       }
-
-       public void setIncludes(List<String> includes) {
-               this.includes = includes;
-       }
-
-       public void setExcludes(List<String> excludes) {
-               this.excludes = excludes;
-       }
-
-       public void setPathMatcher(PathMatcher pathMatcher) {
-               this.pathMatcher = pathMatcher;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SimpleUserInfo.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SimpleUserInfo.java
deleted file mode 100644 (file)
index cabeeb2..0000000
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-import java.util.Arrays;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-
-import com.jcraft.jsch.UserInfo;
-
-/** Basic implementation of user info. */
-public class SimpleUserInfo implements UserInfo {
-       private Boolean permissive = true;
-       private Boolean verbose = false;
-
-       private final static Log log = LogFactory.getLog(SimpleUserInfo.class);
-
-       protected String password;
-       protected char[] passwordSafe;
-       protected String passphrase;
-       protected char[] passphraseSafe;
-
-       public void reset() {
-               if (passwordSafe != null)
-                       Arrays.fill(passwordSafe, (char) 0);
-               passwordSafe = null;
-               if (passphraseSafe != null)
-                       Arrays.fill(passphraseSafe, (char) 0);
-               passphraseSafe = null;
-       }
-
-       public void setPassword(String password) {
-               this.password = password;
-       }
-
-       public void setPassphrase(String passphrase) {
-               this.passphrase = passphrase;
-       }
-
-       public String getPassphrase() {
-               if (passphraseSafe != null)
-                       return new String(passphraseSafe);
-               return passphrase;
-       }
-
-       public String getPassword() {
-               if (passwordSafe != null)
-                       return new String(passwordSafe);
-               return password;
-       }
-
-       public boolean promptPassphrase(String message) {
-               if (permissive)
-                       return true;
-               else {
-                       log.info(message);
-                       passwordSafe = readPassword(System.in);
-                       return passwordSafe != null;
-               }
-       }
-
-       public boolean promptPassword(String message) {
-               if (permissive)
-                       return true;
-               else {
-                       log.info(message);
-                       passwordSafe = readPassword(System.in);
-                       return passwordSafe != null;
-               }
-       }
-
-       public boolean promptYesNo(String message) {
-               String msg = message + " (y/n): ";
-               if (permissive) {
-                       if (verbose)
-                               log.info(msg + "y");
-                       return true;
-               } else {
-                       log.info(msg);
-                       char c;
-                       try {
-                               c = (char) System.in.read();
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot read stdin", e);
-                       }
-                       if (c == 'y')
-                               return true;
-                       else
-                               return false;
-               }
-       }
-
-       public void showMessage(String message) {
-               log.info(message);
-       }
-
-       public void setPermissive(Boolean permissive) {
-               this.permissive = permissive;
-       }
-
-       public void setVerbose(Boolean verbose) {
-               this.verbose = verbose;
-       }
-
-       protected char[] readPassword(InputStream in) {
-
-               try {
-                       char[] lineBuffer;
-                       char[] buf;
-                       // int i;
-
-                       buf = lineBuffer = new char[128];
-
-                       int room = buf.length;
-                       int offset = 0;
-                       int c;
-
-                       loop: while (true) {
-                               switch (c = in.read()) {
-                               case -1:
-                               case '\n':
-                                       break loop;
-
-                               case '\r':
-                                       int c2 = in.read();
-                                       if ((c2 != '\n') && (c2 != -1)) {
-                                               if (!(in instanceof PushbackInputStream)) {
-                                                       in = new PushbackInputStream(in);
-                                               }
-                                               ((PushbackInputStream) in).unread(c2);
-                                       } else
-                                               break loop;
-
-                               default:
-                                       if (--room < 0) {
-                                               buf = new char[offset + 128];
-                                               room = buf.length - offset - 1;
-                                               System.arraycopy(lineBuffer, 0, buf, 0, offset);
-                                               Arrays.fill(lineBuffer, ' ');
-                                               lineBuffer = buf;
-                                       }
-                                       buf[offset++] = (char) c;
-                                       break;
-                               }
-                       }
-
-                       if (offset == 0) {
-                               return null;
-                       }
-
-                       char[] ret = new char[offset];
-                       System.arraycopy(buf, 0, ret, 0, offset);
-                       Arrays.fill(buf, ' ');
-
-                       return ret;
-               } catch (IOException e) {
-                       throw new SlcException("Cannot read password.", e);
-               }
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshFilesDeployment.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshFilesDeployment.java
deleted file mode 100644 (file)
index 9254d7c..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.deploy.DigestCheck;
-import org.argeo.slc.core.deploy.ResourceSet;
-import org.springframework.core.io.Resource;
-
-import com.jcraft.jsch.Session;
-
-public class SshFilesDeployment extends AbstractJschTask implements Runnable {
-       private final static Log log = LogFactory.getLog(SshFilesDeployment.class);
-       private String targetBase = "";
-       private ResourceSet resourceSet;
-       /**
-        * Activate with algorithm as per
-        * http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#AppA
-        */
-       private String checksum = "MD5";
-       private int remoteChecksumsPerCall = 20;
-
-       public SshFilesDeployment() {
-       }
-
-       public SshFilesDeployment(SshTarget sshTarget, ResourceSet resourceSet) {
-               setSshTarget(sshTarget);
-               this.resourceSet = resourceSet;
-       }
-
-       @Override
-       void run(Session session) {
-               JschMultiTasks multiTasks = new JschMultiTasks();
-
-               Map<String, Resource> resources = resourceSet.listResources();
-
-               // Analyze set
-               List<String> subDirs = new ArrayList<String>();
-               Map<String, String> targetPaths = new HashMap<String, String>();
-               for (String relPath : resources.keySet()) {
-                       String parentDir;
-                       int lastIndexSubDir = relPath.lastIndexOf('/');
-                       if (lastIndexSubDir > 0)
-                               parentDir = targetBase + '/'
-                                               + relPath.substring(0, lastIndexSubDir);
-                       else
-                               parentDir = targetBase;
-
-                       boolean skipDir = false;
-                       registerDirs: for (String registeredDir : new ArrayList<String>(
-                                       subDirs)) {
-                               if (parentDir.equals(registeredDir)) {
-                                       if (log.isTraceEnabled())
-                                               log.trace("Already registered, skip " + parentDir);
-                                       skipDir = true;
-                                       break registerDirs;
-                               }
-
-                               if (parentDir.startsWith(registeredDir))
-                                       if (subDirs.contains(registeredDir)) {
-                                               subDirs.remove(registeredDir);
-                                               if (log.isTraceEnabled())
-                                                       log.trace("Remove parent " + registeredDir + " of "
-                                                                       + parentDir);
-                                               continue registerDirs;
-                                       }
-
-                               if (registeredDir.startsWith(parentDir)) {
-                                       skipDir = true;
-                                       if (log.isTraceEnabled())
-                                               log.trace("Skip " + parentDir
-                                                               + " because child already registered.");
-                                       break registerDirs;
-                               }
-                       }
-
-                       if (!subDirs.contains(parentDir) && !skipDir) {
-                               subDirs.add(parentDir);
-                       }
-
-                       targetPaths.put(relPath, targetBase + "/" + relPath);
-               }
-
-               // checksum
-               List<String> targetPathsEqualsToLocal = new ArrayList<String>();
-               if (checksum != null) {
-                       Map<String, String> remoteChecksums = new HashMap<String, String>();
-                       List<String> csLines = new ArrayList<String>();
-                       String csExecutable;
-                       if ("MD5".equals(checksum))
-                               csExecutable = "/usr/bin/md5sum";
-                       else if ("SHA".equals(checksum))
-                               csExecutable = "/usr/bin/sha1sum";
-                       else if ("SHA-256".equals(checksum))
-                               csExecutable = "/usr/bin/sha256sum";
-                       else if ("SHA-512".equals(checksum))
-                               csExecutable = "/usr/bin/sha512sum";
-                       else
-                               throw new SlcException(
-                                               "Don't know how to remotely execute checksum "
-                                                               + checksum);
-
-                       StringBuffer csCmd = new StringBuffer(csExecutable);
-                       int numberOfPaths = targetPaths.size();
-                       int count = 0;
-                       for (String targetPath : targetPaths.values()) {
-                               csCmd.append(" ").append(targetPath);
-                               count++;
-
-                               if ((count % remoteChecksumsPerCall == 0)
-                                               || count == numberOfPaths) {
-                                       RemoteExec remoteCs = new RemoteExec();
-                                       remoteCs.setSshTarget(getSshTarget());
-                                       remoteCs.setCommand(csCmd.toString());
-                                       remoteCs.setStdOutLines(csLines);
-                                       remoteCs.setFailOnBadExitStatus(false);
-                                       remoteCs.run(session);
-                                       csCmd = new StringBuffer(csExecutable);
-                               }
-
-                       }
-
-                       remoteChecksums: for (String csLine : csLines) {
-                               StringTokenizer st = new StringTokenizer(csLine, ": ");
-                               String cs = st.nextToken();
-                               if (cs.equals(csExecutable)) {
-                                       // remote does not exist
-                                       continue remoteChecksums;
-                               } else {
-                                       String targetPath = st.nextToken();
-                                       if (log.isTraceEnabled())
-                                               log.trace("REMOTE: " + targetPath + "=" + cs);
-                                       remoteChecksums.put(targetPath, cs);
-                               }
-                       }
-
-                       // Local checksums
-                       for (String relPath : resources.keySet()) {
-                               Resource resource = resources.get(relPath);
-                               String targetPath = targetPaths.get(relPath);
-                               if (remoteChecksums.containsKey(targetPath)) {
-                                       String cs = DigestCheck.digest(checksum, resource);
-                                       if (log.isTraceEnabled())
-                                               log.trace("LOCAL : " + targetPath + "=" + cs);
-                                       if (remoteChecksums.get(targetPath).equals(cs))
-                                               targetPathsEqualsToLocal.add(targetPath);
-                               }
-                       }
-               }
-
-               // Prepare multitask
-
-               // Create dirs
-               StringBuffer mkdirCmd = new StringBuffer("mkdir -p");
-               RemoteExec remoteExec = new RemoteExec();
-               for (String dir : subDirs) {
-                       // remoteExec.getCommands().add("mkdir -p " + dir);
-                       mkdirCmd.append(' ');
-                       if (dir.indexOf(' ') >= 0)
-                               mkdirCmd.append('\"').append(dir).append('\"');
-                       else
-                               mkdirCmd.append(dir);
-               }
-               remoteExec.setCommand(mkdirCmd.toString());
-               multiTasks.getTasks().add(remoteExec);
-
-               // Perform copies
-               int copied = 0;
-               int skipped = 0;
-               copy: for (String relPath : resources.keySet()) {
-                       String targetPath = targetPaths.get(relPath);
-                       if (targetPathsEqualsToLocal.contains(targetPath)) {
-                               if (log.isTraceEnabled())
-                                       log.trace("Skip copy of " + relPath
-                                                       + " since it is equal to remote " + targetPath);
-                               skipped++;
-                               continue copy;
-                       }
-                       // Copy resource
-                       Resource resource = resources.get(relPath);
-                       ScpTo scpTo = new ScpTo();
-                       scpTo.setLocalResource(resource);
-                       scpTo.setRemotePath(targetPath);
-                       multiTasks.getTasks().add(scpTo);
-                       copied++;
-                       // TODO: set permissions
-               }
-
-               multiTasks.setSshTarget(getSshTarget());
-               multiTasks.run(session);
-
-               if (checksum != null && log.isDebugEnabled())
-                       log.debug("Copied " + copied + " files, skipped " + skipped
-                                       + " with same checksum.");
-       }
-
-       public void setTargetBase(String targetBase) {
-               this.targetBase = targetBase;
-       }
-
-       public void setResourceSet(ResourceSet resourceSet) {
-               this.resourceSet = resourceSet;
-       }
-
-       public void setChecksum(String checksum) {
-               this.checksum = checksum;
-       }
-
-       /** Number of remote checksums per remote call */
-       public void setRemoteChecksumsPerCall(int remoteChecksumsPerCall) {
-               this.remoteChecksumsPerCall = remoteChecksumsPerCall;
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshShell.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshShell.java
deleted file mode 100644 (file)
index cb1b724..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-import org.springframework.util.StringUtils;
-
-import com.jcraft.jsch.Channel;
-import com.jcraft.jsch.Session;
-
-public class SshShell extends AbstractJschTask {
-       private final static Log log = LogFactory.getLog(SshShell.class);
-       private Resource input;
-
-       @Override
-       void run(Session session) {
-               try {
-                       final Channel channel = session.openChannel("shell");
-
-                       // Enable agent-forwarding.
-                       // ((ChannelShell)channel).setAgentForwarding(true);
-
-                       // channel.setInputStream(System.in);
-                       // channel.setInputStream(input.getInputStream());
-                       /*
-                        * // a hack for MS-DOS prompt on Windows.
-                        * channel.setInputStream(new FilterInputStream(System.in){ public
-                        * int read(byte[] b, int off, int len)throws IOException{ return
-                        * in.read(b, off, (len>1024?1024:len)); } });
-                        */
-
-                       // channel.setOutputStream(System.out);
-
-                       /*
-                        * // Choose the pty-type "vt102".
-                        * ((ChannelShell)channel).setPtyType("vt102");
-                        */
-
-                       /*
-                        * // Set environment variable "LANG" as "ja_JP.eucJP".
-                        * ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
-                        */
-
-                       // Writer thread
-                       final BufferedWriter writer = new BufferedWriter(
-                                       new OutputStreamWriter(channel.getOutputStream()));
-
-                       // channel.connect();
-                       channel.connect(3 * 1000);
-
-                       // while (!channel.isConnected())
-                       // try {
-                       // Thread.sleep(500);
-                       // } catch (InterruptedException e1) {
-                       // // silent
-                       // }
-
-                       Thread writerThread = new Thread("Shell writer " + getSshTarget()) {
-
-                               @Override
-                               public void run() {
-
-                                       if (log.isDebugEnabled())
-                                               log.debug("Start writing to shell");
-
-                                       BufferedReader reader = null;
-                                       try {
-                                               reader = new BufferedReader(new InputStreamReader(input
-                                                               .getInputStream()));
-                                               String line = null;
-                                               while ((line = reader.readLine()) != null) {
-                                                       if (!StringUtils.hasText(line))
-                                                               continue;
-                                                       writer.write(line);
-                                                       writer.newLine();
-                                               }
-                                               writer.append("exit");
-                                               writer.newLine();
-                                               writer.flush();
-                                               // channel.disconnect();
-                                       } catch (IOException e) {
-                                               throw new SlcException("Cannot write to shell on "
-                                                               + getSshTarget(), e);
-                                       } finally {
-                                               IOUtils.closeQuietly(reader);
-                                       }
-                               }
-                       };
-                       writerThread.start();
-
-                       BufferedReader execIn = null;
-                       try {
-                               execIn = new BufferedReader(new InputStreamReader(channel
-                                               .getInputStream()));
-                               String line = null;
-                               while ((line = execIn.readLine()) != null) {
-                                       if (!line.trim().equals(""))
-                                               log.info(line);
-                               }
-                       } catch (Exception e) {
-                               throw new SlcException("Cannot read from shell on "
-                                               + getSshTarget(), e);
-                       } finally {
-                               IOUtils.closeQuietly(execIn);
-                       }
-
-               } catch (Exception e) {
-                       throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
-                                       e);
-               }
-       }
-
-       public void setInput(Resource input) {
-               this.input = input;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshTarget.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SshTarget.java
deleted file mode 100644 (file)
index eeebbc6..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.io.File;
-
-import com.jcraft.jsch.Session;
-import com.jcraft.jsch.UserInfo;
-
-public class SshTarget {
-       private String host;
-       private Integer port = 22;
-       private String user;
-       private UserInfo userInfo = new SimpleUserInfo();
-
-       private Boolean usePrivateKey = true;
-       private File localPrivateKey = new File(System.getProperty("user.home")
-                       + File.separator + ".ssh" + File.separator + "id_rsa");
-
-       /** cached session */
-       private transient Session session;
-
-       public String getHost() {
-               return host;
-       }
-
-       public void setHost(String host) {
-               this.host = host;
-       }
-
-       public Integer getPort() {
-               return port;
-       }
-
-       public void setPort(Integer port) {
-               this.port = port;
-       }
-
-       public String getUser() {
-               return user;
-       }
-
-       public void setUser(String user) {
-               this.user = user;
-       }
-
-       public UserInfo getUserInfo() {
-               return userInfo;
-       }
-
-       public void setUserInfo(UserInfo userInfo) {
-               this.userInfo = userInfo;
-       }
-
-       public void setLocalPrivateKey(File localPrivateKey) {
-               this.localPrivateKey = localPrivateKey;
-       }
-
-       public File getLocalPrivateKey() {
-               return localPrivateKey;
-       }
-
-       public Boolean getUsePrivateKey() {
-               return usePrivateKey;
-       }
-
-       public void setUsePrivateKey(Boolean usePrivateKey) {
-               this.usePrivateKey = usePrivateKey;
-       }
-
-       public String toString() {
-               return getUser() + "@" + getHost() + ":" + getPort();
-       }
-
-       public synchronized Session getSession() {
-               return session;
-       }
-
-       public synchronized void setSession(Session session) {
-               this.session = session;
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SwingUserInfo.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/SwingUserInfo.java
deleted file mode 100644 (file)
index 963cbab..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.jsch;
-
-import java.awt.Container;
-import java.awt.GridLayout;
-import java.awt.Panel;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.util.Arrays;
-
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JPasswordField;
-
-/** Retrieves a password or a passphrase using standard Swing */
-public class SwingUserInfo extends SimpleUserInfo {
-
-       private Boolean alwaysPrompt = false;
-
-       public boolean promptPassphrase(String message) {
-               if (passphrase != null)
-                       return true;
-
-               if (!alwaysPrompt && passphraseSafe != null)
-                       return true;
-
-               PasswordDialog dialog = new PasswordDialog(message) {
-                       private static final long serialVersionUID = 3266299327166418364L;
-
-                       @Override
-                       protected void useCredentials(char[] password) {
-                               passphraseSafe = new char[password.length];
-                               System.arraycopy(password, 0, passphraseSafe, 0,
-                                               password.length);
-                               // passphraseSafe = Arrays.copyOf(password, password.length);
-                       }
-               };
-               dialog.setVisible(true);
-               return dialog.getWasProvided();
-       }
-
-       public boolean promptPassword(String message) {
-               if (password != null)
-                       return true;
-
-               if (!alwaysPrompt && passwordSafe != null)
-                       return true;
-
-               PasswordDialog dialog = new PasswordDialog(message) {
-                       private static final long serialVersionUID = 3266299327166418364L;
-
-                       @Override
-                       protected void useCredentials(char[] password) {
-                               // passwordSafe = Arrays.copyOf(password, password.length);
-                               passwordSafe = new char[password.length];
-                               System.arraycopy(password, 0, passwordSafe, 0, password.length);
-                       }
-               };
-               dialog.setVisible(true);
-               return dialog.getWasProvided();
-       }
-
-       public void setAlwaysPrompt(Boolean alwaysPrompt) {
-               this.alwaysPrompt = alwaysPrompt;
-       }
-
-       protected static class PasswordDialog extends JDialog implements
-                       ActionListener {
-               private static final long serialVersionUID = 3399155607980846207L;
-
-               private static final String OK = "ok";
-
-               private JPasswordField password = new JPasswordField("", 10);
-
-               private JButton okButton;
-               private JButton cancelButton;
-
-               private Boolean wasProvided = false;
-
-               public PasswordDialog(String title) {
-                       setTitle(title);
-                       setModal(true);
-                       setLocationRelativeTo(null);
-                       setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
-
-                       JPanel p1 = new JPanel(new GridLayout(1, 2, 3, 3));
-                       p1.add(new JLabel("Password"));
-                       password.setActionCommand(OK);
-                       password.addActionListener(this);
-                       p1.add(password);
-                       add("Center", p1);
-
-                       Panel p2 = new Panel();
-                       okButton = addButton(p2, "OK");
-                       okButton.setActionCommand(OK);
-                       cancelButton = addButton(p2, "Cancel");
-                       add("South", p2);
-                       setSize(240, 120);
-
-                       pack();
-               }
-
-               /** To be overridden */
-               protected void useCredentials(char[] password) {
-                       // does nothing
-               }
-
-               private JButton addButton(Container c, String name) {
-                       JButton button = new JButton(name);
-                       button.addActionListener(this);
-                       c.add(button);
-                       return button;
-               }
-
-               public final void actionPerformed(ActionEvent evt) {
-                       Object source = evt.getSource();
-                       if (source == okButton || evt.getActionCommand().equals(OK)) {
-                               char[] p = password.getPassword();
-                               useCredentials(p);
-                               wasProvided = true;
-                               Arrays.fill(p, '0');
-                               cleanUp();
-                       } else if (source == cancelButton)
-                               cleanUp();
-               }
-
-               private void cleanUp() {
-                       password.setText("");
-                       dispose();
-               }
-
-               public Boolean getWasProvided() {
-                       return wasProvided;
-               }
-
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/jcr/JcrRepositoryBackup.java
deleted file mode 100644 (file)
index c63bdf0..0000000
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.jcr;
-
-import java.util.UUID;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.commons.vfs.FileObject;
-import org.apache.commons.vfs.FileSelectInfo;
-import org.apache.commons.vfs.FileSelector;
-import org.apache.commons.vfs.FileSystemException;
-import org.apache.commons.vfs.FileSystemManager;
-import org.argeo.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-
-/** Backups a JCR repository */
-public class JcrRepositoryBackup implements Runnable {
-       private final static Log log = LogFactory.getLog(JcrRepositoryBackup.class);
-
-       private String sourceRepo;
-       private String sourceDatastore;
-       private String targetFile;
-
-       private String sourceWksp;
-
-       private String sourceUsername;
-       private char[] sourcePassword;
-
-       private RepositoryFactory repositoryFactory;
-       private FileSystemManager fileSystemManager;
-
-       public void run() {
-               Session sourceDefaultSession = null;
-               try {
-                       long begin = System.currentTimeMillis();
-
-                       FileObject archiveRoot = fileSystemManager.resolveFile(targetFile);
-                       archiveRoot.createFolder();
-
-                       String datastoreFolderName = "datastore";
-                       if (hasDatastore())
-                               backupDataStore(archiveRoot.resolveFile(datastoreFolderName));
-
-                       Repository sourceRepository = ArgeoJcrUtils.getRepositoryByUri(
-                                       repositoryFactory, sourceRepo);
-                       Credentials sourceCredentials = null;
-                       if (sourceUsername != null)
-                               sourceCredentials = new SimpleCredentials(sourceUsername,
-                                               sourcePassword);
-
-                       sourceDefaultSession = sourceRepository.login(sourceCredentials);
-                       for (String sourceWorkspaceName : sourceDefaultSession
-                                       .getWorkspace().getAccessibleWorkspaceNames()) {
-                               if (Thread.interrupted()) {
-                                       log.error("Workspace backup interrupted");
-                                       Thread.currentThread().interrupt();
-                                       return;
-                               }
-
-                               if (sourceWksp != null && !sourceWksp.trim().equals("")
-                                               && !sourceWorkspaceName.equals(sourceWksp))
-                                       continue;
-                               Session sourceSession = null;
-                               JarOutputStream out = null;
-                               FileObject workspaceBackup = null;
-                               try {
-                                       Manifest manifest = new Manifest();
-                                       manifest.getMainAttributes().put(
-                                                       Attributes.Name.MANIFEST_VERSION, "1.0");
-                                       manifest.getMainAttributes().putValue("Backup-UUID",
-                                                       UUID.randomUUID().toString());
-                                       manifest.getMainAttributes().putValue("Backup-Timestamp",
-                                                       Long.toString(System.currentTimeMillis()));
-                                       manifest.getMainAttributes().putValue(
-                                                       "Backup-JCR-Workspace", sourceWorkspaceName);
-                                       workspaceBackup = fileSystemManager.resolveFile(targetFile
-                                                       + "/" + sourceWorkspaceName + ".jar");
-
-                                       out = new JarOutputStream(workspaceBackup.getContent()
-                                                       .getOutputStream(), manifest);
-                                       sourceSession = sourceRepository.login(sourceCredentials,
-                                                       sourceWorkspaceName);
-                                       backupWorkspace(sourceSession, out);
-                               } finally {
-                                       JcrUtils.logoutQuietly(sourceSession);
-                                       IOUtils.closeQuietly(out);
-                                       if (workspaceBackup != null)
-                                               workspaceBackup.close();
-                               }
-                       }
-
-                       // in case some binaries have been added during the backup
-                       if (hasDatastore())
-                               backupDataStore(archiveRoot.resolveFile(datastoreFolderName));
-
-                       long duration = (System.currentTimeMillis() - begin) / 1000;// s
-                       log.info("Backed-up " + sourceRepo + " in " + (duration / 60)
-                                       + "min " + (duration % 60) + "s");
-               } catch (Exception e) {
-                       throw new SlcException("Cannot backup " + sourceRepo, e);
-               } finally {
-                       JcrUtils.logoutQuietly(sourceDefaultSession);
-               }
-       }
-
-       protected Boolean hasDatastore() {
-               return sourceDatastore != null && !sourceDatastore.trim().equals("");
-       }
-
-       protected void backupWorkspace(Session sourceSession, JarOutputStream out) {
-               try {
-                       if (log.isTraceEnabled())
-                               log.trace("Backup " + sourceSession.getWorkspace().getName()
-                                               + "...");
-                       Boolean skipBinaries = hasDatastore();
-                       for (NodeIterator it = sourceSession.getRootNode().getNodes(); it
-                                       .hasNext();) {
-                               if (Thread.interrupted()) {
-                                       log.error("Node backup interrupted");
-                                       Thread.currentThread().interrupt();
-                                       return;
-                               }
-                               Node node = it.nextNode();
-                               JarEntry entry = new JarEntry(node.getPath());
-                               out.putNextEntry(entry);
-                               sourceSession.exportSystemView(node.getPath(), out,
-                                               skipBinaries, false);
-                               out.flush();
-                               out.closeEntry();
-                       }
-                       if (log.isDebugEnabled())
-                               log.debug("Backed up " + sourceSession.getWorkspace().getName());
-               } catch (Exception e) {
-                       throw new SlcException("Cannot backup "
-                                       + sourceSession.getWorkspace().getName(), e);
-               }
-       }
-
-       protected void backupDataStore(final FileObject targetDatastore) {
-               try {
-                       targetDatastore.createFolder();
-                       final FileObject sourceDataStore = fileSystemManager
-                                       .resolveFile(sourceDatastore);
-                       if (log.isDebugEnabled())
-                               log.debug("Backup " + sourceDatastore);
-                       targetDatastore.copyFrom(sourceDataStore, new FileSelector() {
-                               public boolean traverseDescendents(FileSelectInfo fileInfo)
-                                               throws Exception {
-                                       return true;
-                               }
-
-                               public boolean includeFile(FileSelectInfo fileInfo)
-                                               throws Exception {
-                                       String relativeName = fileInfo
-                                                       .getFile()
-                                                       .getName()
-                                                       .getPath()
-                                                       .substring(
-                                                                       sourceDataStore.getName().getPath()
-                                                                                       .length());
-                                       FileObject target = targetDatastore
-                                                       .resolveFile(relativeName);
-                                       if (target.exists()) {
-                                               return false;
-                                       } else {
-                                               return true;
-                                       }
-                               }
-                       });
-                       if (log.isDebugEnabled())
-                               log.debug("Backed-up " + sourceDatastore);
-               } catch (FileSystemException e) {
-                       throw new SlcException("Cannot backup datastore", e);
-               }
-       }
-
-       public void setSourceRepo(String sourceRepo) {
-               this.sourceRepo = sourceRepo;
-       }
-
-       public void setSourceWksp(String sourceWksp) {
-               this.sourceWksp = sourceWksp;
-       }
-
-       public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
-               this.repositoryFactory = repositoryFactory;
-       }
-
-       public void setSourceUsername(String sourceUsername) {
-               this.sourceUsername = sourceUsername;
-       }
-
-       public void setSourcePassword(char[] sourcePassword) {
-               this.sourcePassword = sourcePassword;
-       }
-
-       public void setFileSystemManager(FileSystemManager fileSystemManager) {
-               this.fileSystemManager = fileSystemManager;
-       }
-
-       public void setTargetFile(String targetFile) {
-               this.targetFile = targetFile;
-       }
-
-       public void setSourceDatastore(String sourceDatastore) {
-               this.sourceDatastore = sourceDatastore;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRedhatDeploymentData.java
deleted file mode 100644 (file)
index 641e404..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import org.argeo.slc.core.deploy.MultiResourceSet;
-import org.argeo.slc.core.deploy.ResourceSet;
-
-public class DefaultRedhatDeploymentData implements RedhatDeploymentData {
-       private ResourceSet configurationFiles;
-       private String runlevelsScript;
-       private String permissionsScript;
-
-       private RedhatDeploymentData parent;
-
-       public ResourceSet getConfigurationFiles() {
-               if (parent != null && parent.getConfigurationFiles() != null) {
-                       MultiResourceSet mrs = new MultiResourceSet();
-                       mrs.getResourceSets().add(parent.getConfigurationFiles());
-                       mrs.getResourceSets().add(configurationFiles);
-                       return mrs;
-               } else {
-                       return configurationFiles;
-               }
-       }
-
-       public String getRunlevelsScript() {
-               if (parent != null && parent.getRunlevelsScript() != null)
-                       return parent.getRunlevelsScript() + "\n" + runlevelsScript;
-               else
-                       return runlevelsScript;
-       }
-
-       public String getPermissionsScript() {
-               if (parent != null && parent.getPermissionsScript() != null)
-                       return parent.getPermissionsScript() + "\n" + permissionsScript;
-               else
-                       return permissionsScript;
-       }
-
-       public void setRunlevelsScript(String runlevelsScript) {
-               this.runlevelsScript = runlevelsScript;
-       }
-
-       public void setConfigurationFiles(ResourceSet configurationFiles) {
-               this.configurationFiles = configurationFiles;
-       }
-
-       public void setPermissionsScript(String permissionsScript) {
-               this.permissionsScript = permissionsScript;
-       }
-
-       public void setParent(RedhatDeploymentData parentDeploymentData) {
-               this.parent = parentDeploymentData;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRpmDistribution.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DefaultRpmDistribution.java
deleted file mode 100644 (file)
index 0e51a23..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import java.util.List;
-
-public class DefaultRpmDistribution implements RpmDistribution {
-       private List<String> additionalPackages;
-
-       public String getDistributionId() {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       public List<String> getAdditionalPackages() {
-               return additionalPackages;
-       }
-
-       public void setAdditionalPackages(List<String> additionalPackages) {
-               this.additionalPackages = additionalPackages;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DeployLxcContainer.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/DeployLxcContainer.java
deleted file mode 100644 (file)
index 3325dc0..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.argeo.slc.lib.linux;
-
-import java.io.File;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-
-/** Deploy and initialize an LXC container. */
-public class DeployLxcContainer implements Runnable {
-
-       private String chroot;
-
-       private Resource hostScript = new ClassPathResource(
-                       "/org/argeo/slc/lib/linux/lxc-init-host.sh", getClass()
-                                       .getClassLoader());
-       private Resource guestScript = new ClassPathResource(
-                       "/org/argeo/slc/lib/linux/lxc-init-guest.sh", getClass()
-                                       .getClassLoader());;
-
-       // private CallbackHandler callbackHandler;
-
-       private Integer ram = 1024;
-       private Integer vcpu = 2;
-
-       @Override
-       public void run() {
-               if (chroot == null || chroot.trim().equals(""))
-                       throw new SlcException("A chroot directory must be defined");
-
-               File chrootDir = new File(chroot);
-               chrootDir.mkdirs();
-
-               ScriptCall hostCall = new ScriptCall(hostScript);
-               hostCall.setLogCommand(true);
-               hostCall.arg(chroot);
-               // hostCall.getEnvironmentVariables().put("CHROOT", chroot);
-               // hostCall.setSudo("");
-               // hostCall.setCallbackHandler(callbackHandler);
-               hostCall.run();
-
-               ScriptCall guestCall = new ScriptCall(guestScript);
-               guestCall.setLogCommand(true);
-               // guestCall.setSudo("");
-               // guestCall.setCallbackHandler(callbackHandler);
-               guestCall.setChroot(chroot);
-               guestCall.run();
-
-               SystemCall virtInstall = new SystemCall(
-                               "virt-install --connect lxc:/// --name " + chrootDir.getName()
-                                               + " --ram " + ram + " --vcpu " + vcpu
-                                               + " --filesystem " + chrootDir.getAbsolutePath()
-                                               + ",/ --noautoconsole");
-               virtInstall.setLogCommand(true);
-               // virtInstall.setSudo("");
-               virtInstall.run();
-       }
-
-       public void setChroot(String chroot) {
-               this.chroot = chroot;
-       }
-
-       public void setHostScript(Resource hostScript) {
-               this.hostScript = hostScript;
-       }
-
-       public void setGuestScript(Resource guestScript) {
-               this.guestScript = guestScript;
-       }
-
-       // public void setCallbackHandler(CallbackHandler callbackHandler) {
-       // this.callbackHandler = callbackHandler;
-       // }
-
-       public void setRam(Integer ram) {
-               this.ram = ram;
-       }
-
-       public void setVcpu(Integer vcpu) {
-               this.vcpu = vcpu;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatDeploymentData.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatDeploymentData.java
deleted file mode 100644 (file)
index e62bb1c..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import org.argeo.slc.core.deploy.ResourceSet;
-import org.argeo.slc.deploy.DeploymentData;
-
-public interface RedhatDeploymentData extends DeploymentData {
-       public ResourceSet getConfigurationFiles();
-
-       public String getRunlevelsScript();
-
-       public String getPermissionsScript();
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatHostManager.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RedhatHostManager.java
deleted file mode 100644 (file)
index a59b664..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.deploy.LocalFilesDeployment;
-import org.argeo.slc.core.deploy.ResourceSet;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.argeo.slc.jsch.RemoteExec;
-import org.argeo.slc.jsch.SshFilesDeployment;
-import org.argeo.slc.jsch.SshTarget;
-
-public class RedhatHostManager {
-
-       private SimpleLinuxHost host;
-
-       // SSH
-       private Boolean useSsh = true;
-       private SshTarget sshTarget = null;
-
-       public void installPackages() {
-               StringBuffer cmd = new StringBuffer("yum --nogpgcheck -y install");
-               for (String pkg : ((RpmDistribution) host.getDistribution())
-                               .getAdditionalPackages()) {
-                       cmd.append(' ').append(pkg);
-               }
-               executeCommand(cmd.toString());
-
-               RedhatDeploymentData rdd = (RedhatDeploymentData) host
-                               .getDeploymentData();
-               executeCommand(rdd.getRunlevelsScript());
-       }
-
-       public void deployConfig() {
-               RedhatDeploymentData rdd = (RedhatDeploymentData) host
-                               .getDeploymentData();
-               deploy(rdd.getConfigurationFiles());
-               executeCommand(rdd.getPermissionsScript());
-       }
-
-       // GENERIC?
-       protected void deploy(ResourceSet resourceSet) {
-               if (useSsh)
-                       new SshFilesDeployment(getSshTarget(), resourceSet).run();
-               else
-                       new LocalFilesDeployment(resourceSet).run();
-
-       }
-
-       protected void executeCommand(String command) {
-               if (command == null)
-                       return;
-
-               if (useSsh) {
-                       RemoteExec rExec = new RemoteExec(getSshTarget(), command);
-                       rExec.setFailOnBadExitStatus(false);
-                       rExec.run();
-               } else
-                       new SystemCall(command).run();
-       }
-
-       protected SshTarget getSshTarget() {
-               if (sshTarget == null)
-                       throw new SlcException("No SSH target defined");
-               return sshTarget;
-       }
-
-       public void setHost(SimpleLinuxHost host) {
-               this.host = host;
-       }
-
-       public void setUseSsh(Boolean useSsh) {
-               this.useSsh = useSsh;
-       }
-
-       public void setSshTarget(SshTarget sshTarget) {
-               this.sshTarget = sshTarget;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RpmDistribution.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/RpmDistribution.java
deleted file mode 100644 (file)
index 6b4d9b5..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import java.util.List;
-
-import org.argeo.slc.build.Distribution;
-
-public interface RpmDistribution extends Distribution {
-       public List<String> getAdditionalPackages();
-
-       public void setAdditionalPackages(List<String> additionalPackages);
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/ScriptCall.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/ScriptCall.java
deleted file mode 100644 (file)
index d4f664a..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.core.io.Resource;
-
-/** Call to the interpreter of a script language. */
-public class ScriptCall extends SystemCall implements InitializingBean {
-       private Resource script;
-       private List<Object> scriptArgs = new ArrayList<Object>();
-
-       private Boolean localScriptCopy = false;
-
-       /** For use in Spring. */
-       public ScriptCall() {
-               super();
-       }
-
-       /** For use in code ({@link #init()} is called). */
-       public ScriptCall(Resource script) {
-               this.script = script;
-               init();
-       }
-
-       public void init() {
-               initInterpreter();
-               for (Object obj : scriptArgs) {
-                       arg(obj.toString());
-               }
-       }
-
-       public void afterPropertiesSet() throws Exception {
-               init();
-       }
-
-       protected void initInterpreter() {
-               String ext = FilenameUtils.getExtension(script.getFilename());
-
-               if (localScriptCopy) {
-                       File scriptFile = copyScript();
-                       if ("sh".equals(ext))
-                               arg("/bin/sh").arg(scriptFile.getAbsolutePath());
-                       else if ("pl".equals(ext))
-                               arg("/usr/bin/perl").arg(scriptFile.getAbsolutePath());
-                       else if ("py".equals(ext))
-                               arg("/usr/bin/python").arg(scriptFile.getAbsolutePath());
-                       else
-                               throw new SlcException(
-                                               "Cannot initialize script intepreter for " + script);
-               } else {
-                       setStdInFile(script);
-                       if ("sh".equals(ext))
-                               arg("/bin/sh").arg("-s");
-                       else if ("pl".equals(ext))
-                               arg("/usr/bin/perl").arg("/dev/stdin");
-                       else if ("py".equals(ext))
-                               arg("/usr/bin/python").arg("-");
-                       else
-                               throw new SlcException(
-                                               "Cannot initialize script intepreter for " + script);
-               }
-       }
-
-       private File copyScript() {
-               InputStream in = null;
-               OutputStream out = null;
-               try {
-                       File scriptFile = File.createTempFile("script", ".sh");
-                       scriptFile.deleteOnExit();
-                       in = script.getInputStream();
-                       out = new FileOutputStream(scriptFile);
-                       IOUtils.copy(in, out);
-                       return scriptFile;
-               } catch (Exception e) {
-                       throw new SlcException("Cannot copy " + script, e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-               }
-       }
-
-       public void setScript(Resource script) {
-               this.script = script;
-       }
-
-       public void setScriptArgs(List<Object> scriptArgs) {
-               this.scriptArgs = scriptArgs;
-       }
-
-       public void setLocalScriptCopy(Boolean localScriptCopy) {
-               this.localScriptCopy = localScriptCopy;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/SimpleLinuxHost.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/SimpleLinuxHost.java
deleted file mode 100644 (file)
index b25e9f4..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux;
-
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeployedSystem;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.TargetData;
-
-public class SimpleLinuxHost implements DeployedSystem {
-       private DeploymentData deploymentData;
-       private Distribution distribution;
-       private TargetData targetData;
-
-       public String getDeployedSystemId() {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       public DeploymentData getDeploymentData() {
-               return deploymentData;
-       }
-
-       public void setDeploymentData(DeploymentData deploymentData) {
-               this.deploymentData = deploymentData;
-       }
-
-       public Distribution getDistribution() {
-               return distribution;
-       }
-
-       public void setDistribution(Distribution distribution) {
-               this.distribution = distribution;
-       }
-
-       public TargetData getTargetData() {
-               return targetData;
-       }
-
-       public void setTargetData(TargetData targetData) {
-               this.targetData = targetData;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/BuildInMock.java
deleted file mode 100644 (file)
index 1bafe8c..0000000
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.exec.Executor;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-
-/** Rebuild an SRPM in mock. (Historical) Replaces the build-mock.sh script. */
-public class BuildInMock implements Runnable {
-       private final static Log log = LogFactory.getLog(BuildInMock.class);
-
-       /** Mock flavour provided by the EPEL repository */
-       public final static String EPEL = "EPEL";
-       /** Mock flavour provided by CentOS until v5 */
-       public final static String CENTOS = "CENTOS";
-
-       public final static String NOARCH = "noarch";
-
-       private String mockVar = "/var/lib/mock";
-
-       private String mockFlavour = EPEL;
-       private String mockConfig = null;
-
-       private String repository;
-       private String release = null;
-       private String level = null;
-       private String arch = NOARCH;
-
-       private String rpmPackage = null;
-
-       private Boolean mkdirs = true;
-
-       private RpmBuildEnvironment buildEnvironment;
-       private Executor executor;
-
-       private String debuginfoDirName = "debuginfo";
-
-       public void run() {
-               // TODO check if caller is in mock group
-
-               String cfgId = repository + "-" + release + "-" + arch;
-               String cfg = mockConfig != null ? mockConfig : "slc/" + cfgId;
-
-               // prepare mock call
-               SystemCall mock = new SystemCall();
-               if (arch != null)
-                       mock.arg("setarch").arg(arch);
-               mock.arg("mock");
-               if (mockFlavour.equals(EPEL))
-                       mock.arg("-v");
-               else if (mockFlavour.equals(CENTOS))
-                       mock.arg("--debug");
-               if (arch != null)
-                       mock.arg("--arch=" + arch);
-               mock.arg("-r").arg(cfg);
-
-               mock.arg("--scm-enable");
-               mock.arg("--scm-option").arg("package=" + rpmPackage);
-
-               mock.setLogCommand(true);
-
-               // mock command execution
-               mock.setExecutor(executor);
-               mock.run();
-
-               // File repoDir = new File(buildEnvironment.getStagingBase() + "/"
-               // + repository + "/" + level + "/" + release);
-               File repoDir = new File(buildEnvironment.getStagingBase() + "/"
-                               + repository + "-" + release + "-staging");
-               File srpmDir = new File(repoDir, "SRPMS");
-               if (mkdirs)
-                       srpmDir.mkdirs();
-               File archDir = null;
-               File debuginfoDir = null;
-               if (!arch.equals(NOARCH)) {
-                       archDir = new File(repoDir, arch);
-                       debuginfoDir = new File(archDir, debuginfoDirName);
-                       debuginfoDir.mkdirs();
-               }
-
-               // copy RPMs
-               Set<File> reposToRecreate = new HashSet<File>();
-               File resultDir = new File(mockVar + "/" + cfgId + "/result");
-               rpms: for (File file : resultDir.listFiles()) {
-                       if (file.isDirectory())
-                               continue rpms;
-
-                       File[] targetDirs;
-                       if (file.getName().contains(".src.rpm"))
-                               targetDirs = new File[] { srpmDir };
-                       else if (file.getName().contains("-debuginfo-"))
-                               targetDirs = new File[] { debuginfoDir };
-                       else if (!arch.equals(NOARCH)
-                                       && file.getName().contains("." + arch + ".rpm"))
-                               targetDirs = new File[] { archDir };
-                       else if (file.getName().contains(".noarch.rpm")) {
-                               List<File> dirs = new ArrayList<File>();
-                               for (String arch : buildEnvironment.getArchs())
-                                       dirs.add(new File(repoDir, arch));
-                               targetDirs = dirs.toArray(new File[dirs.size()]);
-                       } else if (file.getName().contains(".rpm"))
-                               throw new SlcException("Don't know where to copy " + file);
-                       else {
-                               if (log.isTraceEnabled())
-                                       log.trace("Skip " + file);
-                               continue rpms;
-                       }
-
-                       reposToRecreate.addAll(Arrays.asList(targetDirs));
-                       copyToDirs(file, targetDirs);
-               }
-
-               // recreate changed repos
-               for (File repoToRecreate : reposToRecreate) {
-                       SystemCall createrepo = new SystemCall();
-                       createrepo.arg("createrepo");
-                       // sqllite db
-                       createrepo.arg("-d");
-                       // debuginfo
-                       if (!repoToRecreate.getName().equals(debuginfoDirName))
-                               createrepo.arg("-x").arg(debuginfoDirName + "/*");
-                       // quiet
-                       createrepo.arg("-q");
-                       createrepo.arg(repoToRecreate.getAbsolutePath());
-
-                       createrepo.setExecutor(executor);
-                       createrepo.run();
-                       log.info("Updated repo " + repoToRecreate);
-               }
-       }
-
-       protected void copyToDirs(File file, File[] dirs) {
-               for (File dir : dirs) {
-                       try {
-                               FileUtils.copyFileToDirectory(file, dir);
-                               if (log.isDebugEnabled())
-                                       log.debug(file + " => " + dir);
-                       } catch (IOException e) {
-                               throw new SlcException("Cannot copy " + file + " to " + dir, e);
-                       }
-               }
-       }
-
-       public void setMockFlavour(String mockFlavour) {
-               this.mockFlavour = mockFlavour;
-       }
-
-       public void setMockConfig(String mockConfig) {
-               this.mockConfig = mockConfig;
-       }
-
-       public void setRepository(String repo) {
-               this.repository = repo;
-       }
-
-       public void setRelease(String release) {
-               this.release = release;
-       }
-
-       public void setLevel(String level) {
-               this.level = level;
-       }
-
-       public void setArch(String arch) {
-               this.arch = arch;
-       }
-
-       public void setRpmPackage(String rpmPackage) {
-               this.rpmPackage = rpmPackage;
-       }
-
-       public void setMockVar(String mockVar) {
-               this.mockVar = mockVar;
-       }
-
-       public void setMkdirs(Boolean mkdirs) {
-               this.mkdirs = mkdirs;
-       }
-
-       public void setBuildEnvironment(RpmBuildEnvironment buildEnvironment) {
-               this.buildEnvironment = buildEnvironment;
-       }
-
-       public void setExecutor(Executor executor) {
-               this.executor = executor;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/CreateSrpm.java
deleted file mode 100644 (file)
index b5f7bd0..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.exec.Executor;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.UrlResource;
-
-/** Generates an SRPM from a spec file */
-public class CreateSrpm implements Runnable {
-       private final static Log log = LogFactory.getLog(CreateSrpm.class);
-
-       private File topdir;
-
-       /** Directory where to cache downloaded distributions. */
-       private File distributionCache;
-
-       private Resource specFile;
-
-       private RpmBuildEnvironment rpmBuildEnvironment;
-
-       private Boolean overwriteSources = false;
-
-       private File srpmFile;
-
-       private Executor executor;
-
-       public void run() {
-               File sourcesDir = new File(topdir, "SOURCES");
-               sourcesDir.mkdirs();
-               File specsDir = new File(topdir, "SPECS");
-               File srpmsDir = new File(topdir, "SRPMS");
-
-               try {
-                       // Parse spec file and copy required resources
-                       RpmSpecFile spec = new RpmSpecFile(specFile);
-                       copyToSources(spec, sourcesDir);
-
-                       // Copy spec file
-                       File targetFile = new File(specsDir, specFile.getFilename())
-                                       .getCanonicalFile();
-                       copyResourceToFile(specFile, targetFile);
-
-                       // Generate rpmbuild config files
-                       rpmBuildEnvironment.writeRpmbuildConfigFiles(topdir);
-
-                       // Build SRPM
-                       srpmsDir.mkdirs();
-                       SystemCall packageSrpm = new SystemCall();
-                       packageSrpm.arg("rpmbuild");
-                       packageSrpm.arg("-bs").arg("--nodeps");
-                       packageSrpm.arg("--rcfile=rpmrc");
-                       packageSrpm.arg("--macros=" + RpmBuildEnvironment.defaultMacroFiles
-                                       + ":rpmmacros");
-                       // buildSrpm.arg("-D", "_topdir " + topdir.getCanonicalPath() + "");
-                       packageSrpm.arg("SPECS/" + specFile.getFilename());
-                       packageSrpm.setExecDir(topdir.getCanonicalPath());
-                       packageSrpm.setLogCommand(true);
-
-                       // Execute
-                       packageSrpm.setExecutor(executor);
-                       String answer = packageSrpm.function();
-
-                       // Extract generated SRPM path
-                       // TODO: make it safer
-                       String srpmPath = answer.split(":")[1].trim();
-                       srpmFile = new File(srpmPath);
-               } catch (IOException e) {
-                       throw new SlcException("Cannot generate SRPM from " + specFile, e);
-               }
-
-       }
-
-       protected void copyToSources(RpmSpecFile spec, File sourcesDir) {
-               try {
-                       List<Resource> toCopyToSources = new ArrayList<Resource>();
-                       List<Resource> toDownload = new ArrayList<Resource>();
-                       for (String file : spec.getSources().values()) {
-                               try {
-                                       Resource res;
-                                       try {
-                                               res = specFile.createRelative("../SOURCES/" + file);
-                                               if (!res.exists())
-                                                       res = new UrlResource(file);
-
-                                       } catch (Exception e) {
-                                               res = new UrlResource(file);
-                                               toDownload.add(res);
-                                       }
-                                       toCopyToSources.add(res);
-                               } catch (Exception e) {
-                                       log.error("Cannot interpret " + file, e);
-                               }
-                       }
-                       for (String file : spec.getPatches().values()) {
-                               try {
-                                       Resource res;
-                                       try {
-                                               res = specFile.createRelative("../SOURCES/" + file);
-                                               if (!res.exists()) {
-                                                       res = new UrlResource(file);
-                                               }
-                                       } catch (Exception e) {
-                                               res = new UrlResource(file);
-                                               toDownload.add(res);
-                                       }
-                                       toCopyToSources.add(res);
-                               } catch (Exception e) {
-                                       log.error("Cannot interpret " + file, e);
-                               }
-                       }
-
-                       // FIXME: we may have missed some files here
-                       for (Resource res : toCopyToSources) {
-                               File targetDir;
-                               if (distributionCache != null && toDownload.contains(res)) {
-                                       if (!distributionCache.exists())
-                                               distributionCache.mkdirs();
-                                       targetDir = distributionCache;
-                                       if (log.isDebugEnabled())
-                                               log.debug("Cache " + res + " in " + targetDir);
-                               } else
-                                       targetDir = sourcesDir;
-                               File targetFile = new File(targetDir, res.getFilename())
-                                               .getCanonicalFile();
-                               if (!targetFile.exists() || overwriteSources)
-                                       copyResourceToFile(res, targetFile);
-                               if (!targetDir.equals(sourcesDir)) {
-                                       File fileInSourcesDir = new File(sourcesDir,
-                                                       targetFile.getName());
-                                       if (!fileInSourcesDir.exists()
-                                                       || !(fileInSourcesDir.length() == targetFile
-                                                                       .length()))
-                                               FileUtils.copyFile(targetFile, fileInSourcesDir);
-                               }
-                       }
-               } catch (Exception e) {
-                       throw new SlcException("Cannot copy to " + sourcesDir, e);
-               }
-       }
-
-       private static void copyResourceToFile(Resource res, File targetFile) {
-               try {
-                       if (targetFile.equals(res.getFile())) {
-                               if (log.isDebugEnabled())
-                                       log.debug("Target identical to source, skipping... "
-                                                       + targetFile + " <=> " + res);
-                               return;
-                       }
-               } catch (IOException e1) {
-                       // silent
-               }
-
-               OutputStream out = null;
-               InputStream in = null;
-               try {
-                       out = FileUtils.openOutputStream(targetFile);
-                       in = res.getInputStream();
-                       IOUtils.copy(in, out);
-                       if (log.isDebugEnabled())
-                               log.debug("Copied " + targetFile + " from " + res);
-               } catch (Exception e) {
-                       throw new SlcException("Cannot copy " + res + " to " + targetFile,
-                                       e);
-               } finally {
-                       IOUtils.closeQuietly(in);
-                       IOUtils.closeQuietly(out);
-               }
-
-       }
-
-       public void setSpecFile(Resource specFile) {
-               this.specFile = specFile;
-       }
-
-       public void setTopdir(File topdir) {
-               this.topdir = topdir;
-       }
-
-       public void setOverwriteSources(Boolean overwriteSources) {
-               this.overwriteSources = overwriteSources;
-       }
-
-       public File getSrpmFile() {
-               return srpmFile;
-       }
-
-       public void setRpmBuildEnvironment(RpmBuildEnvironment rpmBuildEnvironment) {
-               this.rpmBuildEnvironment = rpmBuildEnvironment;
-       }
-
-       public void setDistributionCache(File distributionCache) {
-               this.distributionCache = distributionCache;
-       }
-
-       public void setExecutor(Executor executor) {
-               this.executor = executor;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/ImportSrpm.java
deleted file mode 100644 (file)
index cd170e3..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
-
-import java.io.File;
-
-import org.argeo.slc.core.execution.tasks.SystemCall;
-
-/** Install an SRPM into a working copy */
-public class ImportSrpm implements Runnable {
-       private File baseDir;
-       private File srpmFile;
-       private RpmBuildEnvironment rpmBuildEnvironment;
-
-       public void run() {
-               SystemCall rpmQuery = new SystemCall(
-                               "rpm --queryformat '%{NAME}\n' -qp " + srpmFile);
-               String packageName = rpmQuery.function();
-
-               File topdir = new File(baseDir, packageName);
-
-               // prepare SVN
-               // TODO: do it with SVNKit
-               topdir.mkdirs();
-               new SystemCall("svn add " + topdir).run();
-               new SystemCall("svn propset svn:ignore rpm*\nBUILD\nSRPMS\nRPMS " + topdir).run();
-               File sourcesDir = new File(topdir, "SOURCES");
-               sourcesDir.mkdirs();
-               new SystemCall("svn add " + sourcesDir).run();
-               new SystemCall("svn propset svn:ignore *gz\n*bz2\n*.zip\n*.jar " + sourcesDir).run();
-               File specsDir = new File(topdir, "SPECS");
-               specsDir.mkdirs();
-               new SystemCall("svn add " + specsDir).run();
-
-               // Write rpm config files
-               File rpmmacroFile = new File(topdir, "rpmmacros");
-               File rpmrcFile = new File(topdir, "rpmrc");
-               rpmBuildEnvironment.writeRpmbuildConfigFiles(topdir, rpmmacroFile,
-                               rpmrcFile);
-
-               // Install SRPM
-               SystemCall installSrpm = new SystemCall();
-               installSrpm.arg("rpm");
-               installSrpm.arg("-Uvh");
-               installSrpm.arg("--rcfile=" + rpmrcFile.getAbsolutePath());
-               installSrpm.arg(srpmFile.getAbsolutePath());
-               installSrpm.setExecDir(topdir.getAbsolutePath());
-               installSrpm.setLogCommand(true);
-               installSrpm.run();
-       }
-
-       public void setBaseDir(File basedir) {
-               this.baseDir = basedir;
-       }
-
-       public void setSrpmFile(File srpmFile) {
-               this.srpmFile = srpmFile;
-       }
-
-       public void setRpmBuildEnvironment(RpmBuildEnvironment rpmBuildEnvironment) {
-               this.rpmBuildEnvironment = rpmBuildEnvironment;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmBuildEnvironment.java
deleted file mode 100644 (file)
index a5c1fc7..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.io.FileUtils;
-import org.argeo.slc.SlcException;
-
-/**
- * Defines a build environment. This information is typically used by other
- * components performing the various actions related to RPM build.
- */
-public class RpmBuildEnvironment {
-       static String defaultMacroFiles = "/usr/lib/rpm/macros:/usr/lib/rpm/ia32e-linux/macros:/usr/lib/rpm/redhat/macros:/etc/rpm/macros.*:/etc/rpm/macros:/etc/rpm/ia32e-linux/macros:~/.rpmmacros";
-
-       private Map<String, String> rpmmacros = new HashMap<String, String>();
-
-       private List<String> archs = new ArrayList<String>();
-
-       private String stagingBase = "/mnt/slc/repos/rpm";
-
-       /** Write (topdir)/rpmmacros and (topdir)/rpmrc */
-       public void writeRpmbuildConfigFiles(File topdir) {
-               writeRpmbuildConfigFiles(topdir, new File(topdir, "rpmmacros"),
-                               new File(topdir, "rpmrc"));
-       }
-
-       public void writeRpmbuildConfigFiles(File topdir, File rpmmacroFile,
-                       File rpmrcFile) {
-               try {
-                       List<String> macroLines = new ArrayList<String>();
-                       macroLines.add("%_topdir " + topdir.getCanonicalPath());
-                       for (String macroKey : rpmmacros.keySet()) {
-                               macroLines.add(macroKey + " " + rpmmacros.get(macroKey));
-                       }
-                       FileUtils.writeLines(rpmmacroFile, macroLines);
-
-                       List<String> rpmrcLines = new ArrayList<String>();
-                       rpmrcLines.add("include: /usr/lib/rpm/rpmrc");
-                       rpmrcLines.add("macrofiles: " + defaultMacroFiles + ":"
-                                       + rpmmacroFile.getCanonicalPath());
-                       FileUtils.writeLines(rpmrcFile, rpmrcLines);
-               } catch (IOException e) {
-                       throw new SlcException("Cannot write rpmbuild config files", e);
-               }
-
-       }
-
-       public Map<String, String> getRpmmacros() {
-               return rpmmacros;
-       }
-
-       public void setRpmmacros(Map<String, String> rpmmacros) {
-               this.rpmmacros = rpmmacros;
-       }
-
-       public String getDefaultMacroFiles() {
-               return defaultMacroFiles;
-       }
-
-       public void setDefaultMacroFiles(String defaultMacroFiles) {
-               this.defaultMacroFiles = defaultMacroFiles;
-       }
-
-       public void setArchs(List<String> archs) {
-               this.archs = archs;
-       }
-
-       public List<String> getArchs() {
-               return archs;
-       }
-
-       public String getStagingBase() {
-               return stagingBase;
-       }
-
-       public void setStagingBase(String stagingBase) {
-               this.stagingBase = stagingBase;
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/linux/rpmfactory/RpmSpecFile.java
deleted file mode 100644 (file)
index f248654..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.linux.rpmfactory;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.io.IOUtils;
-import org.springframework.core.io.Resource;
-
-public class RpmSpecFile {
-       private Resource specFile;
-
-       private String name;
-       private String version;
-       private String release;
-       private Map<String, String> sources = new HashMap<String, String>();
-       private Map<String, String> patches = new HashMap<String, String>();
-
-       public RpmSpecFile(Resource specFile) {
-               this.specFile = specFile;
-               parseSpecFile();
-       }
-
-       public void init() {
-               parseSpecFile();
-       }
-
-       @SuppressWarnings("unchecked")
-       protected void parseSpecFile() {
-               try {
-                       List<String> lines = (List<String>) IOUtils.readLines(specFile
-                                       .getInputStream());
-
-                       lines: for (String line : lines) {
-                               int indexSemiColon = line.indexOf(':');
-                               if (indexSemiColon <= 0)
-                                       continue lines;
-                               String directive = line.substring(0, indexSemiColon).trim();
-                               String value = line.substring(indexSemiColon + 1).trim();
-                               if ("name".equals(directive.toLowerCase()))
-                                       name = value;
-                               else if ("version".equals(directive.toLowerCase()))
-                                       version = value;
-                               else if ("release".equals(directive.toLowerCase()))
-                                       release = value;
-                               else if (directive.toLowerCase().startsWith("source"))
-                                       sources.put(directive, interpret(value));
-                               else if (directive.toLowerCase().startsWith("patch"))
-                                       patches.put(directive, interpret(value));
-                       }
-
-               } catch (IOException e) {
-                       throw new RuntimeException("Cannot parse spec file " + specFile, e);
-               }
-       }
-
-       protected String interpret(String value) {
-               StringBuffer buf = new StringBuffer(value.length());
-               StringBuffer currKey = null;
-               boolean mayBeKey = false;
-               chars: for (char c : value.toCharArray()) {
-                       if (c == '%')
-                               mayBeKey = true;
-                       else if (c == '{') {
-                               if (mayBeKey)
-                                       currKey = new StringBuffer();
-                       } else if (c == '}') {
-                               if (currKey == null)
-                                       continue chars;
-                               String key = currKey.toString();
-                               if ("name".equals(key.toLowerCase()))
-                                       buf.append(name);
-                               else if ("version".equals(key.toLowerCase()))
-                                       buf.append(version);
-                               else
-                                       buf.append("%{").append(key).append('}');
-                               currKey = null;
-                       } else {
-                               if (currKey != null)
-                                       currKey.append(c);
-                               else
-                                       buf.append(c);
-                       }
-               }
-               return buf.toString();
-       }
-
-       public Resource getSpecFile() {
-               return specFile;
-       }
-
-       public String getName() {
-               return name;
-       }
-
-       public String getVersion() {
-               return version;
-       }
-
-       public String getRelease() {
-               return release;
-       }
-
-       public Map<String, String> getSources() {
-               return sources;
-       }
-
-       public Map<String, String> getPatches() {
-               return patches;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/svn/SvnKitDriver.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/svn/SvnKitDriver.java
deleted file mode 100644 (file)
index e75b199..0000000
+++ /dev/null
@@ -1,182 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.lib.svn;\r
-\r
-import java.io.File;\r
-import java.io.OutputStream;\r
-import java.util.List;\r
-import java.util.Vector;\r
-\r
-import org.apache.commons.logging.Log;\r
-import org.apache.commons.logging.LogFactory;\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.deploy.VersioningDriver;\r
-import org.tmatesoft.svn.core.SVNDepth;\r
-import org.tmatesoft.svn.core.SVNException;\r
-import org.tmatesoft.svn.core.SVNURL;\r
-import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;\r
-import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;\r
-import org.tmatesoft.svn.core.io.SVNRepository;\r
-import org.tmatesoft.svn.core.wc.SVNClientManager;\r
-import org.tmatesoft.svn.core.wc.SVNRevision;\r
-import org.tmatesoft.svn.core.wc.SVNWCUtil;\r
-import org.tmatesoft.svn.core.wc.admin.ISVNChangeEntryHandler;\r
-import org.tmatesoft.svn.core.wc.admin.SVNChangeEntry;\r
-\r
-/** Versioning driver with a Subversion backen, based on SVNKit */\r
-public class SvnKitDriver implements VersioningDriver {\r
-       private final static Log log = LogFactory.getLog(SvnKitDriver.class);\r
-\r
-       private final SVNClientManager manager;\r
-\r
-       public SvnKitDriver() {\r
-               DAVRepositoryFactory.setup();\r
-               FSRepositoryFactory.setup();\r
-               manager = SVNClientManager.newInstance();\r
-       }\r
-\r
-       @SuppressWarnings("deprecation")\r
-       public void updateToHead(File fileOrDir) {\r
-               try {\r
-                       manager.getUpdateClient().doUpdate(fileOrDir, SVNRevision.HEAD,\r
-                                       true);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot update " + fileOrDir, e);\r
-               }\r
-       }\r
-\r
-       @SuppressWarnings("deprecation")\r
-       public void importFileOrDir(String repositoryUrl, File fileOrDir) {\r
-               try {\r
-                       manager.getCommitClient().doImport(fileOrDir,\r
-                                       SVNURL.parseURIDecoded(repositoryUrl),\r
-                                       "Import " + fileOrDir, true);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot import " + repositoryUrl + " to "\r
-                                       + fileOrDir, e);\r
-               }\r
-       }\r
-\r
-       public Boolean checkout(String repositoryUrl, File destDir,\r
-                       Boolean recursive) {\r
-               try {\r
-                       SVNRevision previousRevision = null;\r
-                       if (destDir.exists() && SVNWCUtil.isVersionedDirectory(destDir)) {\r
-                               previousRevision = manager.getWCClient().doInfo(destDir, null)\r
-                                               .getRevision();\r
-                       }\r
-                       if (previousRevision == null && log.isDebugEnabled())\r
-                               log.debug("Checking out " + repositoryUrl + " to " + destDir\r
-                                               + "...");\r
-                       long revision = manager.getUpdateClient().doCheckout(\r
-                                       SVNURL.parseURIDecoded(repositoryUrl), destDir,\r
-                                       SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNDepth.INFINITY,\r
-                                       recursive);\r
-                       if (previousRevision != null\r
-                                       && previousRevision.getNumber() == revision) {\r
-                               if (log.isTraceEnabled())\r
-                                       log.trace(destDir + " already at revision " + revision);\r
-                               return false;\r
-\r
-                       } else {\r
-                               if (log.isDebugEnabled())\r
-                                       if (previousRevision != null)\r
-                                               log.debug(destDir + " updated to revision " + revision\r
-                                                               + " from " + previousRevision.getNumber());\r
-                                       else\r
-                                               log.debug(destDir + " checked out to revision "\r
-                                                               + revision);\r
-                               return true;\r
-                       }\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot checkout " + repositoryUrl + " to "\r
-                                       + destDir, e);\r
-               }\r
-       }\r
-\r
-       public void getFileFromRepository(String repositoryBaseUrl,\r
-                       String location, OutputStream out) {\r
-               try {\r
-                       SVNURL url = SVNURL.parseURIDecoded(repositoryBaseUrl);\r
-                       SVNRepository repo = manager.createRepository(url, true);\r
-                       repo.getFile(location, -1, null, out);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot retrieve file " + location\r
-                                       + " from " + repositoryBaseUrl, e);\r
-               }\r
-\r
-       }\r
-\r
-       public String getRelativePath(String repositoryUrl) {\r
-               try {\r
-                       SVNURL url = SVNURL.parseURIDecoded(repositoryUrl);\r
-                       SVNRepository repo = manager.createRepository(url, true);\r
-                       return repo.getRepositoryPath("");\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot get relative path for "\r
-                                       + repositoryUrl, e);\r
-               }\r
-       }\r
-\r
-       public String getRepositoryRoot(String repositoryUrl) {\r
-               try {\r
-                       SVNURL url = SVNURL.parseURIDecoded(repositoryUrl);\r
-                       SVNRepository repo = manager.createRepository(url, true);\r
-                       return repo.getRepositoryRoot(true).toDecodedString();\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot get repository root for "\r
-                                       + repositoryUrl, e);\r
-               }\r
-       }\r
-\r
-       public List<String> getChangedPaths(File repositoryRoot, Long revision) {\r
-               try {\r
-                       final List<String> paths = new Vector<String>();\r
-                       ISVNChangeEntryHandler handler = new ISVNChangeEntryHandler() {\r
-                               public void handleEntry(SVNChangeEntry entry)\r
-                                               throws SVNException {\r
-                                       paths.add(entry.getPath());\r
-                               }\r
-                       };\r
-                       manager.getLookClient().doGetChanged(repositoryRoot,\r
-                                       SVNRevision.create(revision), handler, false);\r
-                       return paths;\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot get changed paths at "\r
-                                       + repositoryRoot + " for revision " + revision, e);\r
-               }\r
-       }\r
-\r
-       public void createRepository(String filePath) {\r
-               try {\r
-                       manager.getAdminClient().doCreateRepository(new File(filePath),\r
-                                       null, false, false);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot create repository " + filePath, e);\r
-               }\r
-       }\r
-\r
-       @SuppressWarnings("deprecation")\r
-       public void commit(File fileOrDir, String commitMessage) {\r
-               try {\r
-                       manager.getCommitClient().doCommit(new File[] { fileOrDir }, true,\r
-                                       commitMessage, false, true);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot commit " + fileOrDir, e);\r
-               }\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxMachine.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxMachine.java
deleted file mode 100644 (file)
index cf30bbb..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.vbox;
-
-import org.argeo.slc.UnsupportedException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeployedSystem;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.TargetData;
-import org.springframework.beans.factory.BeanNameAware;
-import org.springframework.beans.factory.InitializingBean;
-
-public class VBoxMachine implements DeployedSystem, BeanNameAware,
-               InitializingBean {
-       private String deployedSystemId = null;
-       private String name;
-       private String beanName;
-
-       public String getDeployedSystemId() {
-               return deployedSystemId;
-       }
-
-       public DeploymentData getDeploymentData() {
-               throw new UnsupportedException();
-       }
-
-       public Distribution getDistribution() {
-               throw new UnsupportedException();
-       }
-
-       public TargetData getTargetData() {
-               throw new UnsupportedException();
-       }
-
-       public String getName() {
-               return name;
-       }
-
-       public void setName(String name) {
-               this.name = name;
-       }
-
-       public void setDeployedSystemId(String deployedSystemId) {
-               this.deployedSystemId = deployedSystemId;
-       }
-
-       public void setBeanName(String beanName) {
-               this.beanName = name;
-       }
-
-       public void afterPropertiesSet() throws Exception {
-               if (name == null)
-                       name = beanName;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxManager.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxManager.java
deleted file mode 100644 (file)
index 34e8993..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.vbox;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-import org.springframework.core.io.Resource;
-
-public class VBoxManager {
-       private final static Log log = LogFactory.getLog(VBoxManager.class);
-
-       private VBoxMachine vm;
-       private String executable = "VBoxManage";
-
-       private List<VBoxNat> nats = new ArrayList<VBoxNat>();
-
-       public void importOvf(Resource ovfDefinition) {
-               try {
-                       List<Object> cmd = new ArrayList<Object>();
-                       cmd.add(executable);
-                       cmd.add("import");
-                       cmd.add(ovfDefinition.getFile().getCanonicalPath());
-                       cmd.add("--vsys 0 --vmname <name>");
-                       cmd.add("0");
-                       cmd.add("--vmname");
-                       cmd.add(vm.getName());
-                       new SystemCall(cmd).run();
-               } catch (IOException e) {
-                       throw new SlcException("Cannot import OVF appliance "
-                                       + ovfDefinition, e);
-               }
-       }
-
-       public void startVm() {
-               startVm("gui");
-       }
-
-       public void startVmHeadless() {
-               startVm("vrdp");
-       }
-
-       public void startVm(String type) {
-               List<Object> cmd = new ArrayList<Object>();
-               cmd.add(executable);
-               cmd.add("startvm");
-               cmd.add(vm.getName());
-               cmd.add("--type");
-               cmd.add(type);
-               new SystemCall(cmd).run();
-       }
-
-       public void applyNats() {
-               StringBuffer script = new StringBuffer("");
-               for (VBoxNat vBoxNat : nats) {
-                       for (String id : vBoxNat.getMappings().keySet()) {
-                               VBoxPortMapping mapping = vBoxNat.getMappings().get(id);
-
-                               // Try to delete rule first
-                               try {
-                                       StringBuffer delCmd = new StringBuffer(
-                                                       "VBoxManage modifyvm");
-                                       delCmd.append(" \"").append(vm.getName()).append("\"");
-                                       delCmd.append(" --natpf").append(vBoxNat.getDevice())
-                                                       .append(" ");
-                                       delCmd.append(" delete ");
-                                       delCmd.append("\"").append(id).append("\"");
-                                       new SystemCall(delCmd.toString()).run();
-                                       script.append(delCmd).append("\n");
-                               } catch (Exception e) {
-                                       // silent
-                               }
-
-                               StringBuffer cmd = new StringBuffer("VBoxManage modifyvm");
-                               cmd.append(" \"").append(vm.getName()).append("\"");
-                               cmd.append(" --natpf").append(vBoxNat.getDevice()).append(" ");
-                               cmd.append("\"");
-                               cmd.append(id).append(",");
-                               cmd.append(mapping.getProtocol()).append(",");
-                               cmd.append(",");
-                               cmd.append(mapping.getHostPort()).append(",");
-                               cmd.append(vBoxNat.getGuestIp()).append(",");
-                               cmd.append(mapping.getGuestPort());
-                               cmd.append("\"");
-
-                               new SystemCall(cmd.toString()).run();
-                               script.append(cmd).append("\n");
-
-                               // Older VirtualBox
-                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
-                               // "Protocol", mapping.getProtocol(), script)).run();
-                               // script.append('\n');
-                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
-                               // "GuestPort", mapping.getGuest(), script)).run();
-                               // script.append('\n');
-                               // new SystemCall(createNatCommand(id, vBoxNat.getDevice(),
-                               // "HostPort", mapping.getHost(), script)).run();
-                               // script.append('\n');
-                               // script.append('\n');
-                       }
-                       script.append('\n');
-               }
-
-               if (log.isDebugEnabled())
-                       log.debug("Port setting script:\n" + script);
-       }
-
-       protected List<Object> createNatCommand(String id, String device,
-                       String cfgKey, String value, StringBuffer script) {
-               List<Object> cmd = new ArrayList<Object>();
-               cmd.add(executable);
-               cmd.add("setextradata");
-               cmd.add(vm.getName());
-               cmd.add("VBoxInternal/Devices/" + device + "/0/LUN#0/Config/" + id
-                               + "/" + cfgKey);
-               cmd.add(value);
-
-               for (Object arg : cmd) {
-                       script.append(arg).append(' ');
-               }
-
-               return cmd;
-       }
-
-       public String getExecutable() {
-               return executable;
-       }
-
-       public void setExecutable(String executable) {
-               this.executable = executable;
-       }
-
-       public List<VBoxNat> getNats() {
-               return nats;
-       }
-
-       public void setNats(List<VBoxNat> boxNats) {
-               nats = boxNats;
-       }
-
-       public void setVm(VBoxMachine vm) {
-               this.vm = vm;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxNat.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxNat.java
deleted file mode 100644 (file)
index e69eba1..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.vbox;
-
-import java.util.Map;
-
-/** The NAT mapping table */
-public class VBoxNat {
-       private String device = "1";
-       private String guestIp = "";
-       private Map<String, VBoxPortMapping> mappings;
-
-       public String getDevice() {
-               return device;
-       }
-
-       public void setDevice(String device) {
-               this.device = device;
-       }
-
-       public Map<String, VBoxPortMapping> getMappings() {
-               return mappings;
-       }
-
-       public void setMappings(Map<String, VBoxPortMapping> mappings) {
-               this.mappings = mappings;
-       }
-
-       public String getGuestIp() {
-               return guestIp;
-       }
-
-       public void setGuestIp(String guestIp) {
-               this.guestIp = guestIp;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxPortMapping.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/lib/vbox/VBoxPortMapping.java
deleted file mode 100644 (file)
index dc9783f..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.lib.vbox;
-
-/** The mapping of one port. */
-public class VBoxPortMapping {
-       private String protocol = "TCP";
-       private String guestPort;
-       private String hostPort;
-
-       public String getProtocol() {
-               return protocol;
-       }
-
-       public void setProtocol(String type) {
-               this.protocol = type;
-       }
-
-       public String getGuestPort() {
-               return guestPort;
-       }
-
-       public void setGuestPort(String guestPort) {
-               this.guestPort = guestPort;
-       }
-
-       public String getHostPort() {
-               return hostPort;
-       }
-
-       public void setHostPort(String hostPort) {
-               this.hostPort = hostPort;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/log4j/SlcExecutionAppender.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/log4j/SlcExecutionAppender.java
deleted file mode 100644 (file)
index 190a0b6..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.log4j;
-
-import java.util.Date;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.log4j.AppenderSkeleton;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.log4j.spi.LoggingEvent;
-import org.argeo.slc.core.execution.ExecutionThread;
-import org.argeo.slc.core.execution.ProcessThreadGroup;
-import org.argeo.slc.execution.ExecutionStep;
-
-/** Not meant to be used directly in standard log4j config */
-public class SlcExecutionAppender extends AppenderSkeleton {
-
-       private Boolean disabled = false;
-
-       private String level = null;
-
-       private Level log4jLevel = null;
-
-       /** Marker to prevent stack overflow */
-       private ThreadLocal<Boolean> dispatching = new ThreadLocal<Boolean>() {
-
-               @Override
-               protected Boolean initialValue() {
-                       return false;
-               }
-       };
-
-       // private Layout layout = null;
-       // private String pattern = "%m - %c%n";
-       private Boolean onlyExecutionThread = false;
-
-       public void init() {
-               // if (layout != null)
-               // setLayout(layout);
-               // else
-               // setLayout(new PatternLayout(pattern));
-               Logger.getRootLogger().addAppender(this);
-       }
-
-       @Override
-       protected void append(LoggingEvent event) {
-               if (disabled)
-                       return;
-
-               if (dispatching.get())
-                       return;
-
-               if (level != null && !level.trim().equals("")) {
-                       if (log4jLevel == null || !log4jLevel.toString().equals(level))
-                               try {
-                                       log4jLevel = Level.toLevel(level);
-                               } catch (Exception e) {
-                                       System.err
-                                                       .println("Log4j level could not be set for level '"
-                                                                       + level + "', resetting it to null.");
-                                       e.printStackTrace();
-                                       level = null;
-                               }
-
-                       if (log4jLevel != null
-                                       && !event.getLevel().isGreaterOrEqual(log4jLevel)) {
-                               return;
-                       }
-               }
-
-               // Check whether we are within an executing process
-               Thread currentThread = Thread.currentThread();
-               if (currentThread.getThreadGroup() instanceof ProcessThreadGroup) {
-                       if (onlyExecutionThread
-                                       && !(currentThread instanceof ExecutionThread))
-                               return;
-
-                       final String type;
-                       if (event.getLevel().equals(Level.ERROR)
-                                       || event.getLevel().equals(Level.FATAL))
-                               type = ExecutionStep.ERROR;
-                       else if (event.getLevel().equals(Level.WARN))
-                               type = ExecutionStep.WARNING;
-                       else if (event.getLevel().equals(Level.INFO))
-                               type = ExecutionStep.INFO;
-                       else if (event.getLevel().equals(Level.DEBUG))
-                               type = ExecutionStep.DEBUG;
-                       else if (event.getLevel().equals(Level.TRACE))
-                               type = ExecutionStep.TRACE;
-                       else
-                               type = ExecutionStep.INFO;
-
-                       ExecutionStep step = new ExecutionStep(event.getLoggerName(),
-                                       new Date(event.getTimeStamp()), type, event.getMessage()
-                                                       .toString());
-
-                       try {
-                               dispatching.set(true);
-                               BlockingQueue<ExecutionStep> steps = ((ProcessThreadGroup) currentThread
-                                               .getThreadGroup()).getSteps();
-                               if (steps.remainingCapacity() == 0) {
-                                       stdOut("WARNING: execution steps queue is full, skipping step: "
-                                                       + step);
-                                       // FIXME understand why it block indefinitely: the queue
-                                       // should be emptied by the logging thread
-                               } else {
-                                       steps.add(step);
-                               }
-                       } finally {
-                               dispatching.set(false);
-                       }
-               }
-       }
-
-       public void destroy() throws Exception {
-               Logger.getRootLogger().removeAppender(this);
-       }
-
-       public void close() {
-       }
-
-       public boolean requiresLayout() {
-               return false;
-       }
-
-       // public void setLayout(Layout layout) {
-       // this.layout = layout;
-       // }
-
-       /** For development purpose, since using regular logging is not easy here */
-       static void stdOut(Object obj) {
-               System.out.println(obj);
-       }
-
-       // public void setPattern(String pattern) {
-       // this.pattern = pattern;
-       // }
-
-       public void setOnlyExecutionThread(Boolean onlyExecutionThread) {
-               this.onlyExecutionThread = onlyExecutionThread;
-       }
-
-       public void setDisabled(Boolean disabled) {
-               this.disabled = disabled;
-       }
-
-       public void setLevel(String level) {
-               this.level = level;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/mail/SendMail.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/mail/SendMail.java
deleted file mode 100644 (file)
index d2e2780..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.mail;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.mail.Message;
-import javax.mail.Session;
-import javax.mail.Transport;
-import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeMessage;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.tasks.SystemCall;
-
-/** Sends a mail via JavaMail, local mail command or Google Mail. */
-public class SendMail implements Runnable {
-       // See:
-       // http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#JavaMailUsage
-       // http://java.sun.com/products/javamail/FAQ.html#gmail
-
-       private final static Log log = LogFactory.getLog(SendMail.class);
-
-       private String host;
-       private String from;
-       private String to;
-       private String subject;
-       private String text;
-       private String username;
-       private String password;
-       private Map<String, String> javaMailProperties = new HashMap<String, String>();
-
-       public void run() {
-               if ("local".equals(host))
-                       sendWithMailCommand();
-               else if ("smtp.gmail.com".equals(host))
-                       sendWithGMail();
-               else
-                       sendWithJavaMail();
-       }
-
-       protected void sendWithMailCommand() {
-               SystemCall mail = new SystemCall("mail");
-               mail.arg("-s", subject).arg(to);
-               mail.run();
-               if (log.isDebugEnabled())
-                       log.debug("Sent mail to " + to + " with OS mail command");
-       }
-
-       protected void sendWithJavaMail() {
-               try {
-                       // Get system properties
-                       Properties props = System.getProperties();
-
-                       // Setup mail server
-                       props.put("mail.smtp.host", host);
-
-                       for (String key : javaMailProperties.keySet())
-                               props.put(key, javaMailProperties.get(key));
-
-                       // Get session
-                       Session session = Session.getDefaultInstance(props, null);
-
-                       // Define message
-                       MimeMessage message = new MimeMessage(session);
-                       buildJavaMailMessage(message);
-
-                       // Send message
-                       Transport.send(message);
-                       if (log.isDebugEnabled())
-                               log.debug("Sent mail to " + to + " with JavaMail");
-               } catch (Exception e) {
-                       throw new SlcException("Cannot send message.", e);
-               }
-       }
-
-       protected void sendWithGMail() {
-               try {
-                       Properties props = new Properties();
-                       props.put("mail.smtps.auth", "true");
-                       props.put("mail.smtps.host", host);
-                       Session session = Session.getDefaultInstance(props, null);
-                       MimeMessage message = new MimeMessage(session);
-                       buildJavaMailMessage(message);
-                       Transport t = session.getTransport("smtps");
-                       try {
-                               t.connect(host, username, password);
-                               t.sendMessage(message, message.getAllRecipients());
-                       } finally {
-                               t.close();
-                       }
-                       if (log.isDebugEnabled())
-                               log.debug("Sent mail to " + to + " with Google Mail");
-               } catch (Exception e) {
-                       throw new SlcException("Cannot send message.", e);
-               }
-       }
-
-       protected void buildJavaMailMessage(Message message) throws Exception {
-               message.setFrom(new InternetAddress(from));
-               message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
-               message.setSubject(subject);
-               message.setText(text);
-       }
-
-       public void setHost(String host) {
-               this.host = host;
-       }
-
-       public void setFrom(String from) {
-               this.from = from;
-       }
-
-       public void setTo(String to) {
-               this.to = to;
-       }
-
-       public void setSubject(String subject) {
-               this.subject = subject;
-       }
-
-       public void setText(String text) {
-               this.text = text;
-       }
-
-       public void setJavaMailProperties(Map<String, String> javaMailProperties) {
-               this.javaMailProperties = javaMailProperties;
-       }
-
-       public void setUsername(String username) {
-               this.username = username;
-       }
-
-       public void setPassword(String password) {
-               this.password = password;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationDeployment.java
deleted file mode 100644 (file)
index d7489ee..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.io.File;\r
-\r
-import org.apache.commons.logging.Log;\r
-import org.apache.commons.logging.LogFactory;\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.build.Distribution;\r
-import org.argeo.slc.deploy.DeployEnvironment;\r
-import org.argeo.slc.deploy.DeployedSystem;\r
-import org.argeo.slc.deploy.Deployment;\r
-import org.argeo.slc.deploy.DeploymentData;\r
-import org.argeo.slc.deploy.TargetData;\r
-\r
-public class HttpdApplicationDeployment implements Deployment {\r
-       private static final Log log = LogFactory\r
-                       .getLog(HttpdApplicationDeployment.class);\r
-\r
-       private HttpdApplicationTargetData targetData;\r
-       private DeploymentData deploymentData;\r
-       private SimpleHttpdApplication deployedSystem;\r
-       private Distribution distribution;\r
-\r
-       private DeployEnvironment deployEnvironment;\r
-\r
-       public void run() {\r
-               try {\r
-                       deployEnvironment.unpackTo(distribution, targetData\r
-                                       .getTargetRootLocation(), null);\r
-\r
-                       // FIXME: make it generic\r
-                       String deployDataPath = targetData.getTargetRootLocation()\r
-                                       .getCanonicalPath();\r
-\r
-                       deployEnvironment.unpackTo(deploymentData,\r
-                                       new File(deployDataPath), null);\r
-                       deployedSystem = new SimpleHttpdApplication();\r
-                       deployedSystem.setTargetData(targetData);\r
-\r
-                       log.info("Deployed " + distribution + " to " + targetData);\r
-               } catch (Exception e) {\r
-                       throw new SlcException("Cannot deploy " + distribution + " to "\r
-                                       + targetData, e);\r
-               }\r
-\r
-       }\r
-\r
-       public void setTargetData(TargetData targetData) {\r
-               this.targetData = (HttpdApplicationTargetData) targetData;\r
-       }\r
-\r
-       public void setDeploymentData(DeploymentData deploymentData) {\r
-               this.deploymentData = deploymentData;\r
-       }\r
-\r
-       public DeployedSystem getDeployedSystem() {\r
-               return deployedSystem;\r
-       }\r
-\r
-       public void setDistribution(Distribution distribution) {\r
-               this.distribution = distribution;\r
-       }\r
-\r
-       public void setDeployEnvironment(DeployEnvironment deployEnvironment) {\r
-               this.deployEnvironment = deployEnvironment;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdApplicationTargetData.java
deleted file mode 100644 (file)
index 3bc08c7..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.io.File;\r
-import java.net.MalformedURLException;\r
-import java.net.URL;\r
-\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.deploy.TargetData;\r
-\r
-public class HttpdApplicationTargetData implements TargetData {\r
-       private HttpdServer webServer;\r
-       private String relativePath;\r
-       private String targetRootPath;\r
-\r
-       public HttpdServer getWebServer() {\r
-               return webServer;\r
-       }\r
-\r
-       public void setWebServer(HttpdServer webServer) {\r
-               this.webServer = webServer;\r
-       }\r
-\r
-       public String getRelativePath() {\r
-               return relativePath;\r
-       }\r
-\r
-       /**\r
-        * If targetRootLocation not set, used to build the targetRootLocation,\r
-        * relative to the webserver base.\r
-        */\r
-       public void setRelativePath(String relativePath) {\r
-               this.relativePath = relativePath;\r
-       }\r
-\r
-       public String getTargetRootPath() {\r
-               return targetRootPath;\r
-       }\r
-\r
-       public void setTargetRootPath(String targetRootPath) {\r
-               this.targetRootPath = targetRootPath;\r
-       }\r
-\r
-       public URL getTargetBaseUrl() {\r
-               try {\r
-                       URL wsUrl = getWebServer().getBaseUrl();\r
-                       // TODO: use URI\r
-                       return new URL(wsUrl, wsUrl.getFile() + '/' + relativePath);\r
-               } catch (MalformedURLException e) {\r
-                       throw new SlcException("Cannot get base url for " + relativePath, e);\r
-               }\r
-       }\r
-\r
-       public File getTargetRootLocation() {\r
-               if (targetRootPath != null && !targetRootPath.equals("")) {\r
-                       return new File(targetRootPath);\r
-               } else {\r
-                       HttpdServerTargetData targetData = (HttpdServerTargetData) getWebServer()\r
-                                       .getTargetData();\r
-                       String path = targetData.getServerRoot() + File.separator\r
-                                       + getRelativePath();\r
-                       return new File(path);\r
-               }\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServer.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServer.java
deleted file mode 100644 (file)
index 9416f21..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.io.IOException;\r
-import java.net.URL;\r
-\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.build.Distribution;\r
-import org.argeo.slc.deploy.DeploymentData;\r
-import org.argeo.slc.deploy.TargetData;\r
-\r
-public class HttpdServer implements WebServer {\r
-       private HttpdServerTargetData targetData;\r
-       private HttpdServerDeploymentData deploymentData;\r
-\r
-       public URL getBaseUrl() {\r
-               try {\r
-                       return new URL("http://localhost:" + targetData.getPort());\r
-               } catch (IOException e) {\r
-                       throw new SlcException("Cannot get url for Httpd server "\r
-                                       + getDeployedSystemId(), e);\r
-               }\r
-       }\r
-\r
-       public String getDeployedSystemId() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       public Distribution getDistribution() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       public DeploymentData getDeploymentData() {\r
-               return deploymentData;\r
-       }\r
-\r
-       public TargetData getTargetData() {\r
-               return targetData;\r
-       }\r
-\r
-       public void setTargetData(TargetData targetData) {\r
-               this.targetData = (HttpdServerTargetData)targetData;\r
-       }\r
-\r
-       public void setDeploymentData(DeploymentData deploymentData) {\r
-               this.deploymentData = (HttpdServerDeploymentData)deploymentData;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeployment.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeployment.java
deleted file mode 100644 (file)
index f7915d8..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy;
-
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeployedSystem;
-import org.argeo.slc.deploy.Deployment;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.TargetData;
-
-public class HttpdServerDeployment implements Deployment {
-//     private HttpdServerTargetData targetData;
-
-       public void run() {
-               // TODO Auto-generated method stub
-
-       }
-
-       public DeployedSystem getDeployedSystem() {
-               // TODO Auto-generated method stub
-               return null;
-       }
-
-       public void setDeploymentData(DeploymentData deploymentData) {
-               // TODO Auto-generated method stub
-
-       }
-
-       public void setDistribution(Distribution distribution) {
-       }
-
-       public void setTargetData(TargetData targetData) {
-//             this.targetData = (HttpdServerTargetData) targetData;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerDeploymentData.java
deleted file mode 100644 (file)
index fd9b681..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy;
-
-import org.argeo.slc.deploy.DeploymentData;
-
-public class HttpdServerDeploymentData implements DeploymentData {
-       private String configFile;
-
-       public String getConfigFile() {
-               return configFile;
-       }
-
-       public void setConfigFile(String configFile) {
-               this.configFile = configFile;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerManager.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerManager.java
deleted file mode 100644 (file)
index 3fd76ed..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Arrays;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.deploy.DeployedSystemManager;
-
-public class HttpdServerManager implements DeployedSystemManager<HttpdServer> {
-       private final static Log log = LogFactory.getLog(HttpdServerManager.class);
-
-       private HttpdServer httpdServer;
-
-       public void start() {
-               runProcessAsync(createCommandLine("start"));
-               log.info("Started httpd server with root "
-                               + getHttpdServerTargetData().getServerRoot());
-       }
-
-       public void stop() {
-               runProcessAsync(createCommandLine("stop"));
-               log.info("Stopped httpd server with root "
-                               + getHttpdServerTargetData().getServerRoot());
-       }
-
-       protected String[] createCommandLine(String action) {
-               String httpdPath = getHttpdServerTargetData().getExecutables()
-                               .getExecutablePath("httpd");
-               String[] cmd = { httpdPath, "-d",
-                               getHttpdServerTargetData().getServerRoot(), "-f",
-                               getHttpdServerDeploymentData().getConfigFile(), "-k", action };
-               if (log.isDebugEnabled())
-                       log.debug("Command line: " + Arrays.asList(cmd));
-               return cmd;
-       }
-
-       protected static void runProcessAsync(String... command) {
-               ProcessBuilder procBuilder = new ProcessBuilder(command);
-               procBuilder.redirectErrorStream(true);
-               try {
-                       Process proc = procBuilder.start();
-                       final InputStream in = proc.getInputStream();
-                       Thread logThread = new Thread() {
-
-                               @Override
-                               public void run() {
-                                       BufferedReader reader = new BufferedReader(
-                                                       new InputStreamReader(in));
-                                       String line = null;
-                                       try {
-                                               while ((line = reader.readLine()) != null)
-                                                       log.info(line);
-                                       } catch (IOException e) {
-                                               log.error("Failed to read stdout", e);
-                                       }
-                               }
-                       };
-
-                       logThread.start();
-               } catch (IOException e) {
-                       throw new SlcException("Could not run command", e);
-               }
-       }
-
-       public void setDeployedSystem(HttpdServer httpdServer) {
-               this.httpdServer = httpdServer;
-       }
-
-       protected HttpdServerDeploymentData getHttpdServerDeploymentData() {
-               return (HttpdServerDeploymentData) httpdServer.getDeploymentData();
-       }
-
-       protected HttpdServerTargetData getHttpdServerTargetData() {
-               return (HttpdServerTargetData) httpdServer.getTargetData();
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerTargetData.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/HttpdServerTargetData.java
deleted file mode 100644 (file)
index fa4e3f9..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy;
-
-import org.argeo.slc.deploy.InstalledExecutables;
-import org.argeo.slc.deploy.TargetData;
-
-public class HttpdServerTargetData implements TargetData {
-       private String serverRoot;
-       private Integer port;
-       private InstalledExecutables executables;
-
-       public String getServerRoot() {
-               return serverRoot;
-       }
-
-       public void setServerRoot(String serverRoot) {
-               this.serverRoot = serverRoot;
-       }
-
-       public Integer getPort() {
-               return port;
-       }
-
-       public void setPort(Integer port) {
-               this.port = port;
-       }
-
-       public InstalledExecutables getExecutables() {
-               return executables;
-       }
-
-       public void setExecutables(InstalledExecutables executables) {
-               this.executables = executables;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/SimpleHttpdApplication.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/SimpleHttpdApplication.java
deleted file mode 100644 (file)
index 45c67f4..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.io.File;\r
-import java.net.URL;\r
-\r
-import org.argeo.slc.build.Distribution;\r
-import org.argeo.slc.deploy.DeploymentData;\r
-\r
-public class SimpleHttpdApplication implements WebApplication {\r
-       private HttpdApplicationTargetData targetData;\r
-       private Distribution distribution;\r
-\r
-       public void setDistribution(Distribution distribution) {\r
-               this.distribution = distribution;\r
-       }\r
-\r
-       public URL getBaseUrl() {\r
-               return targetData.getTargetBaseUrl();\r
-       }\r
-\r
-       public File getRootLocation() {\r
-               return targetData.getTargetRootLocation();\r
-       }\r
-\r
-       public String getDeployedSystemId() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       public HttpdApplicationTargetData getTargetData() {\r
-               return targetData;\r
-       }\r
-\r
-       public void setTargetData(HttpdApplicationTargetData targetData) {\r
-               this.targetData = targetData;\r
-       }\r
-\r
-       public Distribution getDistribution() {\r
-               return distribution;\r
-       }\r
-\r
-       public DeploymentData getDeploymentData() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebApplication.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebApplication.java
deleted file mode 100644 (file)
index 6d1b38d..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.io.File;\r
-import java.net.URL;\r
-\r
-import org.argeo.slc.deploy.DeployedSystem;\r
-\r
-public interface WebApplication extends DeployedSystem {\r
-       public URL getBaseUrl();\r
-\r
-       public File getRootLocation();\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebServer.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/WebServer.java
deleted file mode 100644 (file)
index f1dbc10..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- *         http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.support.deploy;\r
-\r
-import java.net.URL;\r
-\r
-import org.argeo.slc.deploy.DeployedSystem;\r
-\r
-public interface WebServer extends DeployedSystem {\r
-       public URL getBaseUrl();\r
-}\r
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/DbModel.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/DbModel.java
deleted file mode 100644 (file)
index 49f651b..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy.db;
-
-import java.sql.Connection;
-
-public interface DbModel {
-       public void createSchema(Connection connection);
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/JdbcAware.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/JdbcAware.java
deleted file mode 100644 (file)
index 5c10939..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy.db;
-
-import javax.sql.DataSource;
-
-public interface JdbcAware {
-       public DataSource getDataSource();
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/support/deploy/db/SimpleJdbcDatabase.java
deleted file mode 100644 (file)
index e04a3e5..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.support.deploy.db;
-
-import javax.sql.DataSource;
-
-import org.argeo.slc.deploy.AbstractDeployedSystem;
-
-public class SimpleJdbcDatabase extends AbstractDeployedSystem implements
-               JdbcAware {
-       private DataSource dataSource;
-
-       public String getDeployedSystemId() {
-               return dataSource.toString();
-       }
-
-       public DataSource getDataSource() {
-               return dataSource;
-       }
-
-       public void setDataSource(DataSource dataSource) {
-               this.dataSource = dataSource;
-       }
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResource.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResource.java
deleted file mode 100644 (file)
index df4a233..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.vfs;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-
-import org.apache.commons.io.IOExceptionWithCause;
-import org.apache.commons.vfs.FileObject;
-import org.apache.commons.vfs.FileSystemException;
-import org.apache.commons.vfs.NameScope;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-
-public class VfsResource implements Resource {
-       private FileObject fileObject;
-
-       public VfsResource(FileObject fileObject) {
-               this.fileObject = fileObject;
-       }
-
-       public Resource createRelative(String relativePath) throws IOException {
-               return new VfsResource(fileObject.resolveFile(relativePath,
-                               NameScope.DESCENDENT_OR_SELF));
-       }
-
-       public boolean exists() {
-               try {
-                       return fileObject.exists();
-               } catch (FileSystemException e) {
-                       throw new SlcException("Cannot find out whether " + fileObject
-                                       + " exists", e);
-               }
-       }
-
-       public String getDescription() {
-               return "VFS resource " + fileObject;
-       }
-
-       public File getFile() throws IOException {
-               throw new IOException("Cannot access " + getDescription()
-                               + " as a local file");
-               // TODO: access local files
-               // if(fileObject instanceof LocalFile){
-               // ((LocalFile)fileObject).
-               // }
-               // return null;
-       }
-
-       public String getFilename() {
-               return fileObject.getName().getBaseName();
-       }
-
-       public URI getURI() throws IOException {
-               try {
-                       return new URI(fileObject.getName().getURI());
-               } catch (URISyntaxException e) {
-                       throw new IOExceptionWithCause(e);
-               }
-       }
-
-       public URL getURL() throws IOException {
-               return fileObject.getURL();
-       }
-
-       public boolean isOpen() {
-               return fileObject.isContentOpen();
-       }
-
-       public boolean isReadable() {
-               try {
-                       return fileObject.isReadable();
-               } catch (FileSystemException e) {
-                       throw new SlcException("Cannot find out whether " + fileObject
-                                       + " is readable", e);
-               }
-       }
-
-       public long lastModified() throws IOException {
-               return fileObject.getContent().getLastModifiedTime();
-       }
-
-       public InputStream getInputStream() throws IOException {
-               return fileObject.getContent().getInputStream();
-       }
-
-       public FileObject getFileObject() {
-               return fileObject;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceFactory.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceFactory.java
deleted file mode 100644 (file)
index d401658..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.vfs;
-
-import org.apache.commons.vfs.CacheStrategy;
-import org.apache.commons.vfs.FileSystemManager;
-import org.apache.commons.vfs.impl.StandardFileSystemManager;
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.core.io.Resource;
-
-public class VfsResourceFactory implements FactoryBean, InitializingBean {
-       private String url;
-       private FileSystemManager fileSystemManager;
-
-       public Object getObject() throws Exception {
-               return new VfsResource(fileSystemManager.resolveFile(url));
-       }
-
-       public Class<?> getObjectType() {
-               return Resource.class;
-       }
-
-       public boolean isSingleton() {
-               return false;
-       }
-
-       public void afterPropertiesSet() throws Exception {
-               if (fileSystemManager == null) {
-                       fileSystemManager = new StandardFileSystemManager();
-                       ((StandardFileSystemManager) fileSystemManager)
-                                       .setCacheStrategy(CacheStrategy.ON_RESOLVE);
-                       ((StandardFileSystemManager) fileSystemManager).init();
-               }
-
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceSet.java b/runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/vfs/VfsResourceSet.java
deleted file mode 100644 (file)
index d8d79fe..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.vfs;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.vfs.FileObject;
-import org.apache.commons.vfs.FileSystemException;
-import org.apache.commons.vfs.FileSystemManager;
-import org.apache.commons.vfs.VFS;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.deploy.ResourceSet;
-import org.springframework.core.io.Resource;
-
-public class VfsResourceSet implements ResourceSet {
-       private String base;
-
-       public Map<String, Resource> listResources() {
-               try {
-                       FileSystemManager fileSystemManager = VFS.getManager();
-                       FileObject fileObject = fileSystemManager.resolveFile(base);
-                       Map<String, Resource> map = new HashMap<String, Resource>();
-                       addToMap(map, "", fileObject);
-
-                       // TODO: add filters
-                       return map;
-               } catch (FileSystemException e) {
-                       throw new SlcException("Cannot list VFS resources from " + base, e);
-               }
-       }
-
-       /** recursive */
-       protected void addToMap(Map<String, Resource> map, String parentPath,
-                       FileObject fileObject) {
-               try {
-                       String newParentPath = parentPath
-                                       + fileObject.getName().getBaseName() + '/';
-                       if (fileObject.getType().hasChildren()) {
-                               for (FileObject child : fileObject.getChildren()) {
-                                       addToMap(map, newParentPath, child);
-                               }
-                       } else {
-                               map.put(parentPath + fileObject.getName().getBaseName(),
-                                               new VfsResource(fileObject));
-                       }
-               } catch (FileSystemException e) {
-                       throw new SlcException("Cannot add children from " + parentPath, e);
-               }
-       }
-
-       public void setBase(String base) {
-               this.base = base;
-       }
-
-}
diff --git a/runtime/org.argeo.slc.support.simple/src/test/java/org/argeo/slc/diff/LineTokenizerTest.java b/runtime/org.argeo.slc.support.simple/src/test/java/org/argeo/slc/diff/LineTokenizerTest.java
deleted file mode 100644 (file)
index 4c7c858..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed 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 org.argeo.slc.diff;
-
-import java.util.List;
-
-import junit.framework.TestCase;
-
-public class LineTokenizerTest extends TestCase {
-       public void testSimple() throws Exception {
-               testAndAssert("a,b,c", new String[] { "a", "b", "c" });
-               testAndAssert("hello,bonjour,hallo,priviet", new String[] { "hello",
-                               "bonjour", "hallo", "priviet" });
-       }
-
-       public void testTricky() throws Exception {
-               testAndAssert("alone", new String[] { "alone" });
-               testAndAssert("", new String[] { "" });
-
-               testAndAssert(",hello,bonjour,hallo,priviet", new String[] { "",
-                               "hello", "bonjour", "hallo", "priviet" });
-               testAndAssert("hello,bonjour,,hallo,priviet", new String[] { "hello",
-                               "bonjour", "", "hallo", "priviet" });
-               testAndAssert("hello,bonjour,hallo,priviet,", new String[] { "hello",
-                               "bonjour", "hallo", "priviet", "" });
-               testAndAssert(",hello,,bonjour,hallo,,,,priviet,", new String[] { "",
-                               "hello", "", "bonjour", "hallo", "", "", "", "priviet", "" });
-
-               testAndAssert(",,,", new String[] { "", "", "", "" });
-       }
-
-       public void testComplex() throws Exception {
-               testAndAssert("a#b#c", '#', "", new String[] { "a", "b", "c" });
-               testAndAssert("hello!bonjour!hallo!priviet", '!', "", new String[] {
-                               "hello", "bonjour", "hallo", "priviet" });
-
-               testAndAssert("hello,,bonjour,,hallo,priviet", ',', "<EMPTY>",
-                               new String[] { "hello", "<EMPTY>", "bonjour", "<EMPTY>",
-                                               "hallo", "priviet" });
-       }
-
-       private void testAndAssert(String str, String[] expected) {
-               testAndAssert(str, ',', "", expected);
-       }
-
-       private void testAndAssert(String str, Character sep, String noValueStr,
-                       String[] expected) {
-               List<String> res = LineTokenizer.tokenize(str, sep, noValueStr);
-               assertEquals("Size", expected.length, res.size());
-               for (int i = 0; i < res.size(); i++) {
-                       String token = res.get(i);
-                       assertEquals("Value@" + i, expected[i], token);
-               }
-       }
-}