+++ /dev/null
--include: ../../cnf/maven.bnd
\ No newline at end of file
+++ /dev/null
--include: ../../cnf/maven.bnd
\ No newline at end of file
+++ /dev/null
-/target/
-/feature.xml
-/modularDistribution.csv
-/*-maven.target
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-bin.includes = feature.xml,\
- modularDistribution.csv
+++ /dev/null
-properties.1.name=org.eclipse.equinox.p2.type.category
-properties.1.value=true
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<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.legacy.commons</groupId>
- <artifactId>legacy-dep</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.dep.cms.platform</artifactId>
- <name>CMS Platform (Legacy)</name>
- <dependencies>
-
- <!-- Parent dependencies -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.dep.cms.node</artifactId>
- <version>${version.argeo-commons}</version>
- <type>pom</type>
- </dependency>
-
- <!-- RWT -->
- <dependency>
- <groupId>org.argeo.tp.rap.e4</groupId>
- <artifactId>org.eclipse.rap.rwt</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.e4</groupId>
- <artifactId>org.eclipse.core.commands</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.e4</groupId>
- <artifactId>org.eclipse.rap.jface</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.e4</groupId>
- <artifactId>org.eclipse.rap.filedialog</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.e4</groupId>
- <artifactId>org.eclipse.rap.fileupload</artifactId>
- </dependency>
-
- <!-- Argeo Commons UI -->
-<!-- <dependency> -->
-<!-- <groupId>org.argeo.commons</groupId> -->
-<!-- <artifactId>org.argeo.eclipse.ui</artifactId> -->
-<!-- <version>${version.argeo-commons}</version> -->
-<!-- </dependency> -->
- <dependency>
- <groupId>org.argeo.commons.rap</groupId>
- <artifactId>org.argeo.swt.specific.rap</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.swt</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.ui</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-<!-- <dependency> -->
-<!-- <groupId>org.argeo.commons</groupId> -->
-<!-- <artifactId>org.argeo.cms.ui.theme</artifactId> -->
-<!-- <version>${version.argeo-commons}</version> -->
-<!-- </dependency> -->
-
- <!-- Eclipse 3 specific -->
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench.rap</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.ext.rap.ui.workbench</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Misc Third Parties -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.apache</groupId> -->
- <!-- <artifactId>org.apache.tika.parser</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.bouncycastle</groupId> -->
- <!-- <artifactId>bcmail</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.bouncycastle</groupId> -->
- <!-- <artifactId>bcpg</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.misc</groupId> -->
- <!-- <artifactId>org.quartz-scheduler.quartz</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.misc</groupId> -->
- <!-- <artifactId>org.quartz-scheduler.quartz.jobs</artifactId> -->
- <!-- </dependency> -->
-
- <!-- Base Spring dependency -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.beans</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.core</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.javax</groupId> -->
- <!-- <artifactId>javax.el</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.gemini</groupId> -->
- <!-- <artifactId>org.eclipse.gemini.blueprint.core</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.gemini</groupId> -->
- <!-- <artifactId>org.eclipse.gemini.blueprint.extender</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.gemini</groupId> -->
- <!-- <artifactId>org.eclipse.gemini.blueprint.io</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.misc</groupId> -->
- <!-- <artifactId>org.aspectj.weaver</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.misc</groupId> -->
- <!-- <artifactId>org.aopalliance</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.aop</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.context</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.expression</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.instrument</artifactId> -->
- <!-- </dependency> -->
-
- <!-- Spring -->
-
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.aspects</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.context.support</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.jdbc</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.tx</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.web</artifactId> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.tp.spring</groupId> -->
- <!-- <artifactId>org.springframework.web.servlet</artifactId> -->
- <!-- </dependency> -->
-
- <!-- Equinox HTTP registry is required by Eclipse 3 but causes problem
- with Eclipse 4 -->
- <dependency>
- <groupId>org.argeo.tp.equinox</groupId>
- <artifactId>org.eclipse.equinox.http.registry</artifactId>
- </dependency>
-
- <!-- Eclipse Core -->
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.databinding</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.databinding.beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.runtime</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.databinding.property</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>com.ibm.icu</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.contenttype</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.rwt.osgi</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.jface.databinding</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.jobs</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.expressions</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.core.databinding.observable</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.help</artifactId>
- </dependency>
-
- <!-- RAP Workbench -->
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.ui</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.ui.forms</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.ui.views</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.rap.platform</groupId>
- <artifactId>org.eclipse.rap.ui.workbench</artifactId>
- </dependency>
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <profiles>
- <profile>
- <id>rpmbuild</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-source</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <descriptorRefs>
- <descriptorRef>a2-source</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>rpm-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rpm-argeo</id>
- <phase>package</phase>
- <goals>
- <goal>rpm</goal>
- </goals>
- <configuration>
- <name>argeo-cms-platform${argeo.rpm.suffix}</name>
- <version>${project.version}</version>
- <mappings>
- <mapping>
- <directory>/usr/share/osgi</directory>
- <username>root</username>
- <groupname>root</groupname>
- <filemode>644</filemode>
- <directoryIncluded>false</directoryIncluded>
- <sources>
- <source>
- <location>${project.build.directory}/${project.artifactId}-${project.version}-a2-source</location>
- <includes>
- <include>**/*.jar</include>
- </includes>
- </source>
- </sources>
- </mapping>
- </mappings>
- <requires>
- <require>argeo-cms-node${argeo.rpm.suffix}</require>
- <require>argeo-cms-platform-tp${argeo.rpm.suffix}</require>
- </requires>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- <profile>
- <id>rpmbuild-tp</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-source-tp</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <descriptorRefs>
- <descriptorRef>a2-source-tp</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>rpm-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rpm-tp</id>
- <phase>package</phase>
- <goals>
- <goal>rpm</goal>
- </goals>
- <configuration>
- <name>argeo-cms-platform-tp${argeo.rpm.suffix}</name>
- <projversion>${version.argeo-tp}</projversion>
- <release>${argeo.rpm.release.tp}</release>
- <mappings>
- <mapping>
- <directory>/usr/share/osgi</directory>
- <username>root</username>
- <groupname>root</groupname>
- <filemode>644</filemode>
- <directoryIncluded>false</directoryIncluded>
- <sources>
- <source>
- <location>${project.build.directory}/${project.artifactId}-${project.version}-a2-source-tp</location>
- <includes>
- <include>**/*.jar</include>
- </includes>
- </source>
- </sources>
- </mapping>
- </mappings>
- <requires>
- <require>argeo-cms-node-tp${argeo.rpm.suffix}</require>
- </requires>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<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.legacy.commons</groupId>
- <artifactId>argeo-commons-legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>legacy-dep</artifactId>
- <name>Commons Modular Distributions (Legacy)</name>
- <packaging>pom</packaging>
- <modules>
- <module>org.argeo.dep.cms.platform</module>
- </modules>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <SLC-ModularDistribution>default</SLC-ModularDistribution>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>properties-maven-plugin</artifactId>
- <configuration>
- <quiet>true</quiet>
- <files>
- <file>../../../../cnf/${version.context}.bnd</file>
- </files>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.argeo.maven.plugins</groupId>
- <artifactId>argeo-osgi-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-descriptors</id>
- <goals>
- <goal>descriptors</goal>
- </goals>
- <phase>generate-resources</phase>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <attach>false</attach>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.tp.equinox</groupId>
- <artifactId>org.eclipse.osgi</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.sdk</groupId>
- <artifactId>org.junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <profiles>
- <profile>
- <id>check-osgi</id>
- <build>
- <plugins>
- <plugin>
- <groupId>org.argeo.maven.plugins</groupId>
- <artifactId>argeo-osgi-plugin</artifactId>
- <executions>
- <execution>
- <id>check-osgi</id>
- <phase>test</phase>
- <goals>
- <goal>equinox</goal>
- </goals>
- <configuration>
- <onlyCheck>true</onlyCheck>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.init</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src" />
- <classpathentry kind="con"
- path="org.eclipse.pde.core.requiredPlugins" />
- <classpathentry kind="con"
- path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11" />
- <classpathentry kind="output" path="bin" />
-</classpath>
+++ /dev/null
-/bin/
-/target/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.cms.ui.workbench.rap</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <bean id="org.argeo.cms.ui.workbench.rap.openChangePasswordDialog"
- class="org.argeo.cms.ui.workbench.commands.OpenChangePasswordDialog"
- scope="prototype">
- <property name="userAdmin" ref="userAdmin" />
- <property name="userTransaction" ref="userTransaction" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <!-- RAP Specific command and corresponding service to enable open file -->
- <bean id="org.argeo.cms.ui.workbench.openFile" class="org.argeo.eclipse.ui.specific.OpenFile"
- scope="prototype">
- <property name="openFileServiceId"
- value="org.argeo.security.ui.specific.openFileService" />
- </bean>
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:osgi="http://www.springframework.org/schema/osgi"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"\r
- osgi:default-timeout="30000">\r
-\r
- <reference id="userAdmin" interface="org.osgi.service.useradmin.UserAdmin" />\r
- <reference id="userTransaction" interface="org.argeo.osgi.transaction.WorkTransaction" />\r
- <reference id="keyring" interface="org.argeo.cms.security.CryptoKeyring" />\r
-</beans:beans>\r
+++ /dev/null
-changePassword=Change password
\ No newline at end of file
+++ /dev/null
-changePassword=Passwort ändern
\ No newline at end of file
+++ /dev/null
-changePassword=Changer de mot de passe
\ No newline at end of file
+++ /dev/null
-changePassword=\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u043F\u0430\u0440\u043E\u043B\u044C
+++ /dev/null
-Bundle-SymbolicName: org.argeo.cms.ui.workbench.rap;singleton:=true
-Bundle-Activator: org.argeo.cms.ui.workbench.rap.SecureRapActivator
-Bundle-ActivationPolicy: lazy
-
-Require-Bundle: org.eclipse.rap.ui,org.eclipse.core.runtime
-
-Import-Package: org.argeo.cms,\
-org.argeo.cms.auth,\
-org.argeo.cms.ui.workbench,\
-org.argeo.cms.ui.workbench.commands,\
-org.argeo.eclipse.ui.specific,\
-org.argeo.eclipse.spring,\
-*
+++ /dev/null
-<html>
-<head></head>
-<body>
-<center>
-<table height="100%">
-<tr>
- <td style="vertical-align:middle">
- <a
- style="font-family:sans-serif;color:#0066CC;text-decoration:none;"
- href="node"
- title="Click to log in"
- >Login...</a>
- </td>
-</tr>
-</table>
-</center>
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-<html>
-<head></head>
-<body>
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-<html>
-<head></head>
-<body>
-<center>
-<table height="100%">
-<tr>
- <td style="vertical-align:middle">
- <a
- style="font-family:sans-serif;color:#0066CC;text-decoration:none;"
- href="javascript:location.reload(true);"
- title="Click to log in"
- >Login...</a>
- </td>
-</tr>
-</table>
-</center>
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-<html>
-<head></head>
-<body>
-<center>
-<table height="100%">
-<tr>
- <td style="vertical-align:middle">
- <a
- style="font-family:sans-serif;color:#0066CC;text-decoration:none;"
- href="javascript:location.reload(true);"
- title="Refresh"
- >Refresh...</a>
- </td>
-</tr>
-</table>
-</center>
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-source.. = src/
-bin.includes = OSGI-INF/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.rap.ui.entrypoint">
- <entrypoint
- id="org.argeo.cms.ui.workbench.rap.secureEntryPoint"
- class="org.argeo.cms.ui.workbench.rap.RapWorkbenchLogin"
- path="/node"
- brandingId="org.argeo.cms.ui.workbench.rap.defaultBranding">
- </entrypoint>
- <entrypoint
- id="org.argeo.cms.ui.workbench.rap.anonymousEntryPoint"
- class="org.argeo.cms.ui.workbench.rap.AnonymousEntryPoint"
- path="/public"
- brandingId="org.argeo.cms.ui.workbench.rap.defaultBranding">
- </entrypoint>
- <entrypoint
- brandingId="org.argeo.cms.ui.workbench.rap.defaultBranding"
- class="org.argeo.cms.ui.workbench.rap.SpnegoWorkbenchLogin"
- id="org.argeo.cms.ui.workbench.rap.loginEntryPoint"
- path="/login">
- </entrypoint>
-<!-- <entrypoint
- id="org.argeo.cms.ui.workbench.rap.secureEntryPoint"
- class="org.argeo.security.ui.rap.RapWorkbenchLogin"
- path="/login"
- brandingId="org.argeo.cms.ui.workbench.rap.defaultBranding">
- </entrypoint> -->
- </extension>
-
- <!-- COMMANDS -->
- <extension point="org.eclipse.ui.commands">
- <command
- id="org.argeo.cms.ui.workbench.rap.mainMenuCommand"
- defaultHandler="org.argeo.cms.ui.workbench.rap.commands.OpenHome"
- name="Main">
- </command>
- <command
- id="org.argeo.cms.ui.workbench.rap.openChangePasswordDialog"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="%changePassword">
- </command>
- <!-- Enable an "open file" action in a single sourced application -->
- <command
- id="org.argeo.cms.ui.workbench.openFile"
- defaultHandler="org.argeo.eclipse.spring.SpringExtensionFactory"
- name="OpenFile">
- <commandParameter
- id="param.fileName"
- name="The name of the file to open (optional)">
- </commandParameter>
- <commandParameter
- id="param.fileURI"
- name="The URI of this file on the server">
- </commandParameter>
- </command>
- </extension>
-
- <!-- MENUS -->
- <extension point="org.eclipse.ui.menus">
- <!-- Main tool bar menu -->
- <!--
- <menuContribution locationURI="toolbar:org.eclipse.ui.main.toolbar">
- <toolbar id="org.argeo.cms.ui.workbench.rap.userToolbar">
- <command
- commandId="org.argeo.cms.ui.workbench.rap.mainMenuCommand"
- icon="icons/home.gif"
- id="org.argeo.cms.ui.workbench.rap.mainMenu"
- style="pulldown">
- </command>
- <command commandId="org.eclipse.ui.file.save"/>
- <command commandId="org.eclipse.ui.file.saveAll"/>
- </toolbar>
- </menuContribution>
- -->
- <menuContribution locationURI="toolbar:org.eclipse.ui.main.toolbar">
- <toolbar id="org.argeo.cms.ui.workbench.userToolbar">
- <command
- commandId="org.argeo.cms.ui.workbench.rap.mainMenuCommand"
- icon="icons/home.png"
- id="org.argeo.cms.ui.workbench.rap.mainMenu"
- style="pulldown">
- </command>
- <command commandId="org.eclipse.ui.file.save" icon="icons/save.png"/>
- <command commandId="org.eclipse.ui.file.saveAll" icon="icons/save-all.png"/>
- </toolbar>
- </menuContribution>
-
- <!-- User drop down default menu -->
- <menuContribution locationURI="menu:org.argeo.cms.ui.workbench.rap.mainMenu">
- <!-- Managed programmatically in the RapActionBarAdvisor to enable
- the display of the current logged-in user id -->
- <command
- commandId="org.argeo.cms.ui.workbench.rap.userMenuCommand"
- icon="icons/person-logged-in.png"
- id="org.argeo.cms.ui.workbench.rap.userMenu">
- </command>
- <!-- Still unused
- <command
- commandId="org.eclipse.ui.window.preferences"
- icon="icons/preferences.png"/> -->
- <command
- commandId="org.argeo.cms.ui.workbench.rap.openChangePasswordDialog"
- icon="icons/security.gif"
- label="%changePassword"/>
- <separator
- name="org.argeo.cms.ui.workbench.rap.beforeFile"
- visible="true">
- </separator>
- <command commandId="org.eclipse.ui.file.closeAll" icon="icons/close-all.png"/>
- <command commandId="org.eclipse.ui.file.save" icon="icons/save.png"/>
- <command commandId="org.eclipse.ui.file.saveAll" icon="icons/save-all.png"/>
-
- <!--<command commandId="org.eclipse.ui.views.showView"/>-->
- <command commandId="org.eclipse.ui.perspectives.showPerspective"/>
- <separator
- name="org.argeo.cms.ui.workbench.rap.beforeExit"
- visible="true">
- </separator>
- <command commandId="org.eclipse.ui.file.exit" icon="icons/exit.png"/>
- </menuContribution>
- </extension>
-
- <!-- SERVICE HANDLERS -->
- <extension point="org.eclipse.rap.ui.serviceHandler">
- <!-- Rap specific service handler to enable file download over the internet-->
- <serviceHandler
- class="org.argeo.eclipse.ui.specific.OpenFileService"
- id="org.argeo.security.ui.specific.openFileService">
- </serviceHandler>
- </extension>
-
- <!-- ACTIVITIES -->
- <extension
- point="org.eclipse.ui.activities">
- <activity
- description="Anonymous"
- id="org.argeo.cms.ui.workbench.rap.anonymousActivity"
- name="Anonymous">
- <enabledWhen>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=anonymous,ou=roles,ou=node" />
- </iterate>
- </with>
- </enabledWhen>
- </activity>
- <activity
- description="Not anonymous"
- id="org.argeo.cms.ui.workbench.rap.notAnonymousActivity"
- name="NotAnonymous">
- <enabledWhen>
- <not>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=anonymous,ou=roles,ou=node" />
- </iterate>
- </with>
- </not>
- </enabledWhen>
- </activity>
- <activityPatternBinding
- activityId="org.argeo.cms.ui.workbench.rap.notAnonymousActivity"
- pattern="org.argeo.cms.ui.workbench.rap/org.argeo.cms.ui.workbench.rap.userMenuCommand"/>
- <activityPatternBinding
- activityId="org.argeo.cms.ui.workbench.rap.notAnonymousActivity"
- pattern="org.argeo.cms.ui.workbench.rap/org.eclipse.ui.window.preferences"/>
- <activityPatternBinding
- activityId="org.argeo.cms.ui.workbench.rap.notAnonymousActivity"
- pattern="org.argeo.cms.ui.workbench.rap/org.argeo.cms.ui.workbench.rap.openChangePasswordDialog"/>
- </extension>
-
- <!-- BRANDINGS -->
- <extension
- point="org.eclipse.rap.ui.branding">
- <branding
- id="org.argeo.cms.ui.workbench.rap.defaultBranding"
- themeId="org.eclipse.rap.rwt.theme.Default"
- title="Argeo Web UI"
- favicon="branding/favicon.ico">
- </branding>
- <!-- we need a servlet with this name j_spring_security_logout
- for the logout filter -->
- <branding
- id="org.argeo.cms.ui.workbench.rap.logoutBranding"
- title="Argeo Logout"
- favicon="branding/favicon.ico"
- body="branding/empty.html">
- </branding>
- </extension>
-</plugin>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<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.legacy.commons</groupId>
- <artifactId>argeo-commons-legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.cms.ui.workbench.rap</artifactId>
- <name>CMS Workbench RAP</name>
- <packaging>jar</packaging>
- <dependencies>
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <!-- RAP specific -->
- <dependency>
- <groupId>org.argeo.commons.rap</groupId>
- <artifactId>org.argeo.swt.specific.rap</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import java.security.PrivilegedAction;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.application.EntryPoint;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * RAP entry point which authenticates the subject as anonymous, for public
- * unauthenticated access.
- */
-public class AnonymousEntryPoint implements EntryPoint {
- private final static CmsLog log = CmsLog.getLog(AnonymousEntryPoint.class);
-
- /**
- * How many seconds to wait before invalidating the session if the user has
- * not yet logged in.
- */
- private Integer sessionTimeout = 5 * 60;
-
- @Override
- public int createUI() {
- RWT.getRequest().getSession().setMaxInactiveInterval(sessionTimeout);
-
- // if (log.isDebugEnabled())
- // log.debug("Anonymous THREAD=" + Thread.currentThread().getId()
- // + ", sessionStore=" + RWT.getSessionStore().getId());
-
- final Display display = PlatformUI.createDisplay();
- Subject subject = new Subject();
-
- final LoginContext loginContext;
- try {
- loginContext = new LoginContext(CmsAuth.LOGIN_CONTEXT_ANONYMOUS,
- subject);
- loginContext.login();
- } catch (LoginException e1) {
- throw new CmsException("Cannot initialize login context", e1);
- }
-
- // identify after successful login
- if (log.isDebugEnabled())
- log.debug("Authenticated " + subject);
- final String username = subject.getPrincipals().iterator().next()
- .getName();
-
- // Logout callback when the display is disposed
- display.disposeExec(new Runnable() {
- public void run() {
- log.debug("Display disposed");
- logout(loginContext, username);
- }
- });
-
- //
- // RUN THE WORKBENCH
- //
- Integer returnCode = null;
- try {
- returnCode = Subject.doAs(subject, new PrivilegedAction<Integer>() {
- public Integer run() {
- RapWorkbenchAdvisor workbenchAdvisor = new RapWorkbenchAdvisor(
- null);
- int result = PlatformUI.createAndRunWorkbench(display,
- workbenchAdvisor);
- return new Integer(result);
- }
- });
- logout(loginContext, username);
- if (log.isTraceEnabled())
- log.trace("Return code " + returnCode);
- } finally {
- display.dispose();
- }
- return 1;
- }
-
- private void logout(LoginContext loginContext, String username) {
- try {
- loginContext.logout();
- log.info("Logged out " + (username != null ? username : "")
- + " (THREAD=" + Thread.currentThread().getId() + ")");
- } catch (LoginException e) {
- log.error("Erorr when logging out", e);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import java.util.Locale;
-import java.util.UUID;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.servlet.http.HttpServletRequest;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsImageManager;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.api.cms.CmsView;
-import org.argeo.api.cms.UxContext;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.swt.CmsSwtUtils;
-import org.argeo.cms.swt.SimpleSwtUxContext;
-import org.argeo.cms.swt.auth.CmsLogin;
-import org.argeo.cms.swt.auth.CmsLoginShell;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.application.EntryPoint;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-
-public class LoginEntryPoint implements EntryPoint, CmsView {
- protected final static String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
- protected final static String HEADER_AUTHORIZATION = "Authorization";
- private final static CmsLog log = CmsLog.getLog(LoginEntryPoint.class);
- private LoginContext loginContext;
- private UxContext uxContext = null;
- private String uid;
-
- @Override
- public int createUI() {
- uid = UUID.randomUUID().toString();
- final Display display = createDisplay();
-// UiContext.setData(CmsView.KEY, this);
-
- CmsLoginShell loginShell = createCmsLoginShell();
- CmsSwtUtils.registerCmsView(loginShell.getShell(), this);
- try {
- // try pre-auth
- loginContext = new LoginContext(CmsAuth.LOGIN_CONTEXT_USER, loginShell);
- loginContext.login();
- } catch (LoginException e) {
- loginShell.createUi();
- loginShell.open();
-
- // HttpServletRequest request = RWT.getRequest();
- // String authorization = request.getHeader(HEADER_AUTHORIZATION);
- // if (authorization == null ||
- // !authorization.startsWith("Negotiate")) {
- // HttpServletResponse response = RWT.getResponse();
- // response.setStatus(401);
- // response.setHeader(HEADER_WWW_AUTHENTICATE, "Negotiate");
- // response.setDateHeader("Date", System.currentTimeMillis());
- // response.setDateHeader("Expires", System.currentTimeMillis() +
- // (24 * 60 * 60 * 1000));
- // response.setHeader("Accept-Ranges", "bytes");
- // response.setHeader("Connection", "Keep-Alive");
- // response.setHeader("Keep-Alive", "timeout=5, max=97");
- // // response.setContentType("text/html; charset=UTF-8");
- // }
-
- while (!loginShell.getShell().isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
-
- if (CurrentUser.getUsername(getSubject()) == null)
- return -1;
- uxContext = new SimpleSwtUxContext();
- return postLogin();
- }
-
- protected Display createDisplay() {
- return new Display();
- }
-
- protected int postLogin() {
- return 0;
- }
-
- protected HttpServletRequest getRequest() {
- return RWT.getRequest();
- }
-
- protected CmsLoginShell createCmsLoginShell() {
- return new CmsLoginShell(this, null) {
-
- @Override
- public void createContents(Composite parent) {
- LoginEntryPoint.this.createLoginPage(parent, this);
- }
-
- @Override
- protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
- SelectionListener loginSelectionListener) {
- LoginEntryPoint.this.extendsCredentialsBlock(credentialsBlock, selectedLocale, loginSelectionListener);
- }
-
- };
- }
-
- /**
- * To be overridden. CmsLogin#createCredentialsBlock() should be called at some
- * point in order to create the credentials composite. In order to use the
- * default layout, call CmsLogin#defaultCreateContents() but <b>not</b>
- * CmsLogin#createContent(), since it would lead to a stack overflow.
- */
- protected void createLoginPage(Composite parent, CmsLogin login) {
- login.defaultCreateContents(parent);
- }
-
- protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
- SelectionListener loginSelectionListener) {
-
- }
-
- @Override
- public String getUid() {
- return uid;
- }
-
- @Override
- public void navigateTo(String state) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void authChange(LoginContext loginContext) {
- if (loginContext == null)
- throw new CmsException("Login context cannot be null");
- // logout previous login context
- if (this.loginContext != null)
- try {
- this.loginContext.logout();
- } catch (LoginException e1) {
- log.warn("Could not log out: " + e1);
- }
- this.loginContext = loginContext;
- }
-
- @Override
- public void logout() {
- if (loginContext == null)
- throw new CmsException("Login context should not bet null");
- try {
- CurrentUser.logoutCmsSession(loginContext.getSubject());
- loginContext.logout();
- } catch (LoginException e) {
- throw new CmsException("Cannot log out", e);
- }
- }
-
- @Override
- public void exception(Throwable e) {
- // TODO Auto-generated method stub
-
- }
-
- // @Override
- // public LoginContext getLoginContext() {
- // return loginContext;
- // }
-
- protected Subject getSubject() {
- return loginContext.getSubject();
- }
-
- @Override
- public boolean isAnonymous() {
- return CurrentUser.isAnonymous(getSubject());
- }
-
- public CmsImageManager getImageManager() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public UxContext getUxContext() {
- return uxContext;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.ui.workbench.commands.OpenHomePerspective;
-import org.eclipse.core.commands.Category;
-import org.eclipse.core.commands.Command;
-import org.eclipse.jface.action.ICoolBarManager;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.commands.ICommandService;
-
-/** Eclipse rap specific action bar advisor */
-public class RapActionBarAdvisor extends ActionBarAdvisor {
- private final static String ID_BASE = SecureRapActivator.ID;
- // private final static CmsLog log = CmsLog
- // .getLog(SecureActionBarAdvisor.class);
-
- /** Null means anonymous */
- private String username = null;
-
- // private IAction logoutAction;
- // private IWorkbenchAction openPerspectiveDialogAction;
- // private IWorkbenchAction showViewMenuAction;
- // private IWorkbenchAction preferences;
- private IWorkbenchAction saveAction;
- private IWorkbenchAction saveAllAction;
-
- // private IWorkbenchAction closeAllAction;
-
- public RapActionBarAdvisor(IActionBarConfigurer configurer, String username) {
- super(configurer);
- this.username = username;
- }
-
- protected void makeActions(IWorkbenchWindow window) {
- // preferences = ActionFactory.PREFERENCES.create(window);
- // register(preferences);
- // openPerspectiveDialogAction = ActionFactory.OPEN_PERSPECTIVE_DIALOG
- // .create(window);
- // register(openPerspectiveDialogAction);
- // showViewMenuAction = ActionFactory.SHOW_VIEW_MENU.create(window);
- // register(showViewMenuAction);
- //
- // // logout
- // logoutAction = ActionFactory.QUIT.create(window);
- // // logoutAction = createLogoutAction();
- // register(logoutAction);
- //
- // Save semantics
- saveAction = ActionFactory.SAVE.create(window);
- register(saveAction);
- saveAllAction = ActionFactory.SAVE_ALL.create(window);
- register(saveAllAction);
- // closeAllAction = ActionFactory.CLOSE_ALL.create(window);
- // register(closeAllAction);
-
- }
-
- protected void fillMenuBar(IMenuManager menuBar) {
- // MenuManager fileMenu = new MenuManager("&File",
- // IWorkbenchActionConstants.M_FILE);
- // MenuManager editMenu = new MenuManager("&Edit",
- // IWorkbenchActionConstants.M_EDIT);
- // MenuManager windowMenu = new MenuManager("&Window",
- // IWorkbenchActionConstants.M_WINDOW);
- //
- // menuBar.add(fileMenu);
- // menuBar.add(editMenu);
- // menuBar.add(windowMenu);
- // // Add a group marker indicating where action set menus will appear.
- // menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- //
- // // File
- // fileMenu.add(saveAction);
- // fileMenu.add(saveAllAction);
- // fileMenu.add(closeAllAction);
- // fileMenu.add(new
- // GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- // fileMenu.add(new Separator());
- // fileMenu.add(logoutAction);
- //
- // // Edit
- // editMenu.add(preferences);
- //
- // // Window
- // windowMenu.add(openPerspectiveDialogAction);
- // windowMenu.add(showViewMenuAction);
- }
-
- @Override
- protected void fillCoolBar(ICoolBarManager coolBar) {
- // Add a command which label is the display name of the current
- // logged-in user
- if (username != null) {
- ICommandService cmdService = (ICommandService) getActionBarConfigurer()
- .getWindowConfigurer().getWorkbenchConfigurer()
- .getWorkbench().getService(ICommandService.class);
- Category userMenus = cmdService.getCategory(ID_BASE + ".userMenus");
- if (!userMenus.isDefined())
- userMenus.define("User Menus", "User related menus");
- Command userMenu = cmdService.getCommand(ID_BASE
- + ".userMenuCommand");
- if (userMenu.isDefined())
- userMenu.undefine();
- userMenu.define(CurrentUser.getDisplayName(), "User menu actions",
- userMenus);
- // userMenu.define(username, "User menu actions", userMenus);
-
- userMenu.setHandler(new OpenHomePerspective());
-
- // userToolbar.add(new UserMenuAction());
- // coolBar.add(userToolbar);
- } else {// anonymous
- IToolBarManager userToolbar = new ToolBarManager(SWT.FLAT
- | SWT.RIGHT);
- // userToolbar.add(logoutAction);
- coolBar.add(userToolbar);
- }
- // IToolBarManager saveToolbar = new ToolBarManager(SWT.FLAT |
- // SWT.RIGHT);
- // saveToolbar.add(saveAction);
- // saveToolbar.add(saveAllAction);
- // coolBar.add(saveToolbar);
- }
-
- // class UserMenuAction extends Action implements IWorkbenchAction {
- //
- // public UserMenuAction() {
- // super(username, IAction.AS_DROP_DOWN_MENU);
- // // setMenuCreator(new UserMenu());
- // }
- //
- // @Override
- // public String getId() {
- // return "org.argeo.cms.ui.workbench.rap.userMenu";
- // }
- //
- // @Override
- // public void dispose() {
- // }
- //
- // }
-
- // class UserMenu implements IMenuCreator {
- // private Menu menu;
- //
- // public Menu getMenu(Control parent) {
- // Menu menu = new Menu(parent);
- // addActionToMenu(menu, logoutAction);
- // return menu;
- // }
- //
- // private void addActionToMenu(Menu menu, IAction action) {
- // ActionContributionItem item = new ActionContributionItem(action);
- // item.fill(menu, -1);
- // }
- //
- // public void dispose() {
- // if (menu != null) {
- // menu.dispose();
- // }
- // }
- //
- // public Menu getMenu(Menu parent) {
- // // Not use
- // return null;
- // }
- //
- // }
-
- // protected IAction createLogoutAction() {
- // Subject subject = Subject.getSubject(AccessController.getContext());
- // final String username = subject.getPrincipals().iterator().next()
- // .getName();
- //
- // IAction logoutAction = new Action() {
- // public String getId() {
- // return SecureRapActivator.ID + ".logoutAction";
- // }
- //
- // public String getText() {
- // return "Logout " + username;
- // }
- //
- // public void run() {
- // // try {
- // // Subject subject = SecureRapActivator.getLoginContext()
- // // .getSubject();
- // // String subjectStr = subject.toString();
- // // subject.getPrincipals().clear();
- // // SecureRapActivator.getLoginContext().logout();
- // // log.info(subjectStr + " logged out");
- // // } catch (LoginException e) {
- // // log.error("Error when logging out", e);
- // // }
- // // SecureEntryPoint.logout(username);
- // // PlatformUI.getWorkbench().close();
- // // try {
- // // RWT.getRequest().getSession().setMaxInactiveInterval(1);
- // // } catch (Exception e) {
- // // if (log.isTraceEnabled())
- // // log.trace("Error when invalidating session", e);
- // // }
- // }
- //
- // };
- // return logoutAction;
- // }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-/** Eclipse RAP specific window advisor */
-public class RapWindowAdvisor extends WorkbenchWindowAdvisor {
-
- private String username;
-
- public RapWindowAdvisor(IWorkbenchWindowConfigurer configurer,
- String username) {
- super(configurer);
- this.username = username;
- }
-
- @Override
- public ActionBarAdvisor createActionBarAdvisor(
- IActionBarConfigurer configurer) {
- return new RapActionBarAdvisor(configurer, username);
- }
-
- public void preWindowOpen() {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- configurer.setShowCoolBar(true);
- configurer.setShowMenuBar(false);
- configurer.setShowStatusLine(false);
- configurer.setShowPerspectiveBar(true);
- configurer.setTitle("Argeo Web UI"); //$NON-NLS-1$
- // Full screen, see
- // http://wiki.eclipse.org/RAP/FAQ#How_to_create_a_fullscreen_application
- configurer.setShellStyle(SWT.NO_TRIM);
- Rectangle bounds = Display.getCurrent().getBounds();
- configurer.setInitialSize(new Point(bounds.width, bounds.height));
-
- // Handle window resize in Rap 2.1+ see
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=417254
- Display.getCurrent().addListener(SWT.Resize, new Listener() {
- private static final long serialVersionUID = 2970912561866704526L;
-
- @Override
- public void handleEvent(Event event) {
- Rectangle bounds = event.display.getBounds();
- IWorkbenchWindow iww = getWindowConfigurer().getWindow()
- .getWorkbench().getActiveWorkbenchWindow();
- iww.getShell().setBounds(bounds);
- }
- });
- }
-
- @Override
- public void postWindowCreate() {
- Shell shell = getWindowConfigurer().getWindow().getShell();
- shell.setMaximized(true);
- }
-
- @Override
- public void postWindowOpen() {
- String defaultPerspective = getWindowConfigurer()
- .getWorkbenchConfigurer().getWorkbench()
- .getPerspectiveRegistry().getDefaultPerspective();
- if (defaultPerspective == null) {
- IWorkbenchWindow window = getWindowConfigurer().getWindow();
- if (window == null)
- return;
-
- IWorkbenchAction openPerspectiveDialogAction = ActionFactory.OPEN_PERSPECTIVE_DIALOG
- .create(window);
- openPerspectiveDialogAction.run();
- }
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import org.eclipse.ui.IPerspectiveDescriptor;
-import org.eclipse.ui.application.IWorkbenchConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchAdvisor;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-/** Eclipse RAP specific workbench advisor */
-public class RapWorkbenchAdvisor extends WorkbenchAdvisor {
- public final static String INITIAL_PERSPECTIVE_PROPERTY = "org.argeo.security.ui.initialPerspective";
- public final static String SAVE_AND_RESTORE_PROPERTY = "org.argeo.security.ui.saveAndRestore";
-
- private String initialPerspective = System.getProperty(
- INITIAL_PERSPECTIVE_PROPERTY, null);
-
- private String username;
-
- public RapWorkbenchAdvisor(String username) {
- this.username = username;
- }
-
- @Override
- public void initialize(IWorkbenchConfigurer configurer) {
- super.initialize(configurer);
- Boolean saveAndRestore = Boolean.parseBoolean(System.getProperty(
- SAVE_AND_RESTORE_PROPERTY, "false"));
- configurer.setSaveAndRestore(saveAndRestore);
- }
-
- public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
- return new RapWindowAdvisor(configurer, username);
- }
-
- public String getInitialWindowPerspectiveId() {
- if (initialPerspective != null) {
- // check whether this user can see the declared perspective
- // (typically the perspective won't be listed if this user doesn't
- // have the right to see it)
- IPerspectiveDescriptor pd = getWorkbenchConfigurer().getWorkbench()
- .getPerspectiveRegistry()
- .findPerspectiveWithId(initialPerspective);
- if (pd == null)
- return null;
- }
- return initialPerspective;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import java.security.PrivilegedAction;
-import java.util.Locale;
-
-import javax.security.auth.Subject;
-import javax.security.auth.x500.X500Principal;
-
-import org.argeo.cms.auth.CurrentUser;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.client.service.JavaScriptExecutor;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-public class RapWorkbenchLogin extends LoginEntryPoint {
- // private final static Log log =
- // LogFactory.getLog(RapWorkbenchLogin.class);
-
- /** Override to provide an application specific workbench advisor */
- protected RapWorkbenchAdvisor createRapWorkbenchAdvisor(String username) {
- return new RapWorkbenchAdvisor(username);
- }
-
- @Override
- public int createUI() {
- JavaScriptExecutor jsExecutor = RWT.getClient().getService(JavaScriptExecutor.class);
- int returnCode;
- try {
- returnCode = super.createUI();
- } finally {
- // always reload
- // TODO optimise?
- jsExecutor.execute("location.reload()");
- }
- return returnCode;
- }
-
- @Override
- protected int postLogin() {
- Subject subject = getSubject();
- final Display display = Display.getCurrent();
- if (subject.getPrincipals(X500Principal.class).isEmpty()) {
- RWT.getClient().getService(JavaScriptExecutor.class).execute("location.reload()");
- }
- //
- // RUN THE WORKBENCH
- //
- Integer returnCode = null;
- try {
- returnCode = Subject.doAs(subject, new PrivilegedAction<Integer>() {
- public Integer run() {
- int result = createAndRunWorkbench(display, CurrentUser.getUsername(subject));
- return new Integer(result);
- }
- });
- // explicit workbench closing
- logout();
- } finally {
- display.dispose();
- }
- return returnCode;
- }
-
- protected int createAndRunWorkbench(Display display, String username) {
- RapWorkbenchAdvisor workbenchAdvisor = createRapWorkbenchAdvisor(username);
- return PlatformUI.createAndRunWorkbench(display, workbenchAdvisor);
- }
-
- @Override
- protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
- SelectionListener loginSelectionListener) {
-// Button loginButton = new Button(credentialsBlock, SWT.PUSH);
-// loginButton.setText(CmsMsg.login.lead(selectedLocale));
-// loginButton.setLayoutData(CmsUtils.fillWidth());
-// loginButton.addSelectionListener(loginSelectionListener);
- }
-
- @Override
- protected Display createDisplay() {
- return PlatformUI.createDisplay();
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/** Configure Equinox login context from the bundle context. */
-public class SecureRapActivator implements BundleActivator {
- public final static String ID = "org.argeo.cms.ui.workbench.rap";
-
- private static BundleContext bundleContext;
-
- public void start(BundleContext bc) throws Exception {
- bundleContext = bc;
- }
-
- public void stop(BundleContext context) throws Exception {
- bundleContext = null;
- }
-
- public static BundleContext getBundleContext() {
- return bundleContext;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap;
-
-import java.security.PrivilegedAction;
-import java.util.Locale;
-
-import javax.security.auth.Subject;
-import javax.security.auth.x500.X500Principal;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.argeo.cms.auth.CurrentUser;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.client.service.JavaScriptExecutor;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-public class SpnegoWorkbenchLogin extends LoginEntryPoint {
- // private final static Log log =
- // LogFactory.getLog(RapWorkbenchLogin.class);
-
- /** Override to provide an application specific workbench advisor */
- protected RapWorkbenchAdvisor createRapWorkbenchAdvisor(String username) {
- return new RapWorkbenchAdvisor(username);
- }
-
- @Override
- public int createUI() {
- HttpServletRequest request = RWT.getRequest();
- String authorization = request.getHeader(HEADER_AUTHORIZATION);
- if (authorization == null || !authorization.startsWith("Negotiate")) {
- HttpServletResponse response = RWT.getResponse();
- response.setStatus(401);
- response.setHeader(HEADER_WWW_AUTHENTICATE, "Negotiate");
- response.setDateHeader("Date", System.currentTimeMillis());
- response.setDateHeader("Expires", System.currentTimeMillis() + (24 * 60 * 60 * 1000));
- response.setHeader("Accept-Ranges", "bytes");
- response.setHeader("Connection", "Keep-Alive");
- response.setHeader("Keep-Alive", "timeout=5, max=97");
- // response.setContentType("text/html; charset=UTF-8");
- }
-
- int returnCode;
- returnCode = super.createUI();
- return returnCode;
- }
-
- @Override
- protected int postLogin() {
- Subject subject = getSubject();
- final Display display = Display.getCurrent();
- if (subject.getPrincipals(X500Principal.class).isEmpty()) {
- RWT.getClient().getService(JavaScriptExecutor.class).execute("location.reload()");
- }
- //
- // RUN THE WORKBENCH
- //
- Integer returnCode = null;
- try {
- returnCode = Subject.doAs(subject, new PrivilegedAction<Integer>() {
- public Integer run() {
- int result = createAndRunWorkbench(display, CurrentUser.getUsername(subject));
- return new Integer(result);
- }
- });
- // explicit workbench closing
- logout();
- } finally {
- display.dispose();
- }
- return returnCode;
- }
-
- protected int createAndRunWorkbench(Display display, String username) {
- RapWorkbenchAdvisor workbenchAdvisor = createRapWorkbenchAdvisor(username);
- return PlatformUI.createAndRunWorkbench(display, workbenchAdvisor);
- }
-
- @Override
- protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
- SelectionListener loginSelectionListener) {
-// Button loginButton = new Button(credentialsBlock, SWT.PUSH);
-// loginButton.setText(CmsMsg.login.lead(selectedLocale));
-// loginButton.setLayoutData(CmsUtils.fillWidth());
-// loginButton.addSelectionListener(loginSelectionListener);
- }
-
- @Override
- protected Display createDisplay() {
- return PlatformUI.createDisplay();
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap.commands;
-
-import org.argeo.cms.ui.workbench.UserHomePerspective;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Default action of the user menu */
-public class OpenHome extends AbstractHandler {
- private final static String PROP_OPEN_HOME_CMD_ID = "org.argeo.ui.openHomeCommandId";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String defaultCmdId = System.getProperty(PROP_OPEN_HOME_CMD_ID, "");
- if (!"".equals(defaultCmdId.trim()))
- CommandUtils.callCommand(defaultCmdId);
- else {
- try {
- String defaultPerspective = HandlerUtil.getActiveWorkbenchWindow(event).getWorkbench()
- .getPerspectiveRegistry().getDefaultPerspective();
- HandlerUtil.getActiveSite(event).getWorkbenchWindow()
- .openPage(defaultPerspective != null ? defaultPerspective : UserHomePerspective.ID, null);
- } catch (WorkbenchException e) {
- ErrorFeedback.show("Cannot open home perspective", e);
- }
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.rap.commands;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-/** Default action of the user menu */
-public class UserMenu extends AbstractHandler {
-
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- return null;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src" />
- <classpathentry kind="con"
- path="org.eclipse.pde.core.requiredPlugins" />
- <classpathentry kind="con"
- path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11" />
- <classpathentry kind="output" path="bin" />
-</classpath>
+++ /dev/null
-/bin/
-/target/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.cms.ui.workbench</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <!-- USERS CRUDS -->
- <bean id="newUser" class="org.argeo.cms.ui.workbench.internal.useradmin.commands.NewUser"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
- <bean id="deleteUsers"
- class="org.argeo.cms.ui.workbench.internal.useradmin.commands.DeleteUsers"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
- <bean id="userBatchUpdate"
- class="org.argeo.cms.ui.workbench.internal.useradmin.commands.UserBatchUpdate"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
- <!-- GROUPS CRUDS -->
- <bean id="newGroup" class="org.argeo.cms.ui.workbench.internal.useradmin.commands.NewGroup"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
- <bean id="deleteGroups"
- class="org.argeo.cms.ui.workbench.internal.useradmin.commands.DeleteGroups"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
-
- <!-- TRANSACTIONS -->
- <bean id="userTransactionHandler"
- class="org.argeo.cms.ui.workbench.internal.useradmin.commands.UserTransactionHandler"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
-
- <!-- DATA EXPLORER -->
- <bean id="addRemoteRepository"
- class="org.argeo.cms.ui.workbench.internal.jcr.commands.AddRemoteRepository">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <bean id="addPrivileges" class="org.argeo.cms.ui.workbench.internal.jcr.commands.AddPrivileges">
- <property name="userAdmin" ref="userAdmin" />
- </bean>
- <bean id="removePrivileges"
- class="org.argeo.cms.ui.workbench.internal.jcr.commands.RemovePrivileges">
- <!-- <property name="userAdmin" ref="userAdmin" /> -->
- </bean>
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean id="userTransactionProvider"\r
- class="org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTransactionProvider"\r
- scope="singleton" lazy-init="false">\r
- <property name="userTransaction" ref="userTransaction" />\r
- </bean>\r
-\r
- <bean id="userAdminWrapper"\r
- class="org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper"\r
- scope="singleton" lazy-init="false">\r
- <property name="userTransaction" ref="userTransaction" />\r
- <property name="userAdmin" ref="userAdmin" />\r
- <property name="userAdminServiceReference" ref="userAdmin" />\r
- </bean>\r
-\r
- <bean id="repositoryRegister" class="org.argeo.cms.ui.jcr.DefaultRepositoryRegister" />\r
-\r
-</beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:osgi="http://www.springframework.org/schema/osgi"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"\r
- osgi:default-timeout="30000">\r
-\r
- <!-- JCR -->\r
- <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
- <reference id="keyring" interface="org.argeo.cms.security.CryptoKeyring" />\r
- <list id="repositories" interface="javax.jcr.Repository"\r
- cardinality="0..N">\r
- <listener ref="repositoryRegister" bind-method="register"\r
- unbind-method="unregister" />\r
- </list>\r
-\r
- <reference id="nodeRepository" interface="javax.jcr.Repository"\r
- filter="(cn=ego)" />\r
- \r
- <reference id="nodeInstance" interface="org.argeo.api.cms.CmsContext" />\r
-\r
- <reference id="nodeFileSystemProvider" interface="java.nio.file.spi.FileSystemProvider"\r
- filter="(service.pid=org.argeo.api.fsProvider)" />\r
-\r
- <!-- UserAdmin -->\r
- <reference id="userAdmin" interface="org.osgi.service.useradmin.UserAdmin" />\r
- <reference id="userTransaction" interface="org.argeo.osgi.transaction.WorkTransaction" />\r
-\r
-\r
- <reference id="defaultCallbackHandler" interface="javax.security.auth.callback.CallbackHandler" />\r
-\r
-</beans:beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <!-- SECURITY -->
- <!-- Editors -->
- <bean id="userEditor"
- class="org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
-
- <bean id="groupEditor"
- class="org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- <property name="repository" ref="nodeRepository" />
- <property name="nodeInstance" ref="nodeInstance" />
- </bean>
-
- <!-- Views -->
- <bean id="usersView"
- class="org.argeo.cms.ui.workbench.internal.useradmin.parts.UsersView"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
- <bean id="groupsView"
- class="org.argeo.cms.ui.workbench.internal.useradmin.parts.GroupsView"
- scope="prototype">
- <property name="userAdminWrapper" ref="userAdminWrapper" />
- </bean>
-
-
- <!-- DATA EXPLORER -->
- <!-- Editors -->
- <bean id="genericJcrQueryEditor" class="org.argeo.cms.ui.workbench.jcr.GenericJcrQueryEditor"
- scope="prototype">
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
- <bean id="defaultNodeEditor" class="org.argeo.cms.ui.workbench.jcr.DefaultNodeEditor"
- scope="prototype">
- </bean>
- <!-- Views -->
- <bean id="jcrBrowserView" class="org.argeo.cms.ui.workbench.jcr.JcrBrowserView"
- scope="prototype">
- <property name="repositoryRegister" ref="repositoryRegister" />
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </bean>
- <bean id="nodeFsBrowserView" class="org.argeo.cms.ui.workbench.jcr.NodeFsBrowserView"
- scope="prototype">
- <property name="nodeFileSystemProvider" ref="nodeFileSystemProvider" />
- <!-- <property name="keyring" ref="keyring" /> -->
- </bean>
-
- <!-- LOGGERS -->
- <bean id="logView" class="org.argeo.cms.ui.workbench.useradmin.LogView"
- scope="prototype">
- <property name="argeoLogger" ref="secureLogger" />
- </bean>
- <bean id="adminLogView" class="org.argeo.cms.ui.workbench.useradmin.AdminLogView"
- scope="prototype">
- <property name="argeoLogger" ref="secureLogger" />
- </bean>
-</beans>
+++ /dev/null
-search=Finden
\ No newline at end of file
+++ /dev/null
-search=Search
\ No newline at end of file
+++ /dev/null
-Bundle-SymbolicName: org.argeo.cms.ui.workbench;singleton:=true
-Bundle-Activator: org.argeo.cms.ui.workbench.WorkbenchUiPlugin
-Bundle-ActivationPolicy: lazy
-
-Require-Bundle: org.eclipse.core.runtime,\
-org.eclipse.core.commands
-
-Import-Package: org.argeo.cms.auth,\
-org.argeo.api.cms,\
-org.argeo.cms,\
-org.argeo.cms.ui,\
-org.argeo.eclipse.spring,\
-org.argeo.eclipse.ui.util,\
-org.eclipse.core.runtime.jobs,\
-org.eclipse.jface.window,\
-org.eclipse.swt,\
-org.eclipse.swt.widgets,\
-org.eclipse.ui.services,\
-org.osgi.*;version=0.0.0,\
-org.springframework.core,\
-org.springframework.beans.factory,\
-org.springframework.core.io.support,\
-!org.eclipse.core.runtime,\
-*
-
-
-# org.argeo.eclipse.ui.workbench;resolution:=optional,\
+++ /dev/null
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- icons/,\
- plugin.xml
-additional.bundles = org.apache.commons.httpclient
+++ /dev/null
-argeo.keyring.secreteKeyLength=256
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- id="org.argeo.cms.ui.workbench.adminSecurityPerspective"
- class="org.argeo.cms.ui.workbench.SecurityAdminPerspective"
- icon="platform:/plugin/org.argeo.cms.ui.theme/platform:/plugin/org.argeo.cms.ui.theme/icons/group.png"
- name="Security">
- </perspective>
- <perspective
- id="org.argeo.cms.ui.workbench.userHomePerspective"
- class="org.argeo.cms.ui.workbench.UserHomePerspective"
- icon="platform:/plugin/org.argeo.cms.ui.theme/platform:/plugin/org.argeo.cms.ui.theme/icons/home.png"
- name="Home">
- </perspective>
- <perspective
- id="org.argeo.cms.ui.workbench.adminMaintenancePerspective"
- class="org.argeo.cms.ui.workbench.MaintenancePerspective"
- icon="platform:/plugin/org.argeo.cms.ui.theme/platform:/plugin/org.argeo.cms.ui.theme/icons/maintenance.gif"
- name="Maintenance">
- </perspective>
- <perspective
- id="org.argeo.cms.ui.workbench.osgiPerspective"
- class="org.argeo.cms.ui.workbench.OsgiExplorerPerspective"
- name="Monitoring"
- icon="platform:/plugin/org.argeo.cms.ui.theme/platform:/plugin/org.argeo.cms.ui.theme/icons/osgi_explorer.gif">
- </perspective>
- <perspective
- id="org.argeo.cms.ui.workbench.jcrBrowserPerspective"
- class="org.argeo.cms.ui.workbench.JcrBrowserPerspective"
- name="Data Explorer"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/nodes.gif">
- </perspective>
- </extension>
-
- <!-- Definition of the OSGI perspective -->
- <extension point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension targetID="org.argeo.cms.ui.workbench.osgiPerspective">
- <view
- id="org.argeo.cms.ui.workbench.cmsSessionsView"
- minimized="false"
- ratio="0.5"
- relationship="left"
- relative="org.eclipse.ui.editorss"/>
- <view
- id="org.argeo.cms.ui.workbench.modulesView"
- minimized="false"
- relationship="stack"
- relative="org.argeo.cms.ui.workbench.cmsSessionsView"/>
- <view
- id="org.argeo.cms.ui.workbench.bundlesView"
- minimized="false"
- relationship="stack"
- relative="org.argeo.cms.ui.workbench.modulesView"/>
- <view
- id="org.argeo.cms.ui.workbench.multiplePackagesView"
- minimized="false"
- relationship="stack"
- relative="org.argeo.cms.ui.workbench.bundlesView"/>
- </perspectiveExtension>
- </extension>
-
-
- <!-- VIEWS -->
- <extension
- point="org.eclipse.ui.views">
- <!-- Security -->
- <view
- id="org.argeo.cms.ui.workbench.usersView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/person.png"
- name="Users"
- restorable="true">
- </view>
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/group.png"
- id="org.argeo.cms.ui.workbench.groupsView"
- name="Groups"
- restorable="false">
- </view>
- <!-- Home -->
- <view
- id="org.argeo.cms.ui.workbench.userProfile"
- class="org.argeo.cms.ui.workbench.useradmin.UserProfile"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/person-logged-in.png"
- name="Profile"
- restorable="true">
- </view>
- <!-- Maintenance -->
- <view
- id="org.argeo.cms.ui.workbench.logView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- name="Log"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/log.gif"
- restorable="true">
- </view>
- <view
- id="org.argeo.cms.ui.workbench.adminLogView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- name="Admin Log"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/adminLog.gif"
- restorable="true">
- </view>
- <!-- OSGi Monitor -->
- <view
- name="Modules"
- id="org.argeo.cms.ui.workbench.modulesView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/service_published.gif"
- class="org.argeo.cms.ui.workbench.osgi.ModulesView">
- </view>
- <view
- name="CMS Session"
- id="org.argeo.cms.ui.workbench.cmsSessionsView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/service_published.gif"
- class="org.argeo.cms.ui.workbench.osgi.CmsSessionsView">
- </view>
- <view
- name="Bundles"
- id="org.argeo.cms.ui.workbench.bundlesView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/bundles.gif"
- class="org.argeo.cms.ui.workbench.osgi.BundlesView">
- </view>
- <view
- name="Multiple Packages"
- id="org.argeo.cms.ui.workbench.multiplePackagesView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/node.gif"
- class="org.argeo.cms.ui.workbench.osgi.MultiplePackagesView">
- </view>
- <!-- Data Explorer -->
- <view
- name="JCR"
- id="org.argeo.cms.ui.workbench.jcrBrowserView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/browser.gif"
- class="org.argeo.eclipse.spring.SpringExtensionFactory">
- </view>
- <view
- name="Files"
- id="org.argeo.cms.ui.workbench.nodeFsBrowserView"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/browser.gif"
- class="org.argeo.eclipse.spring.SpringExtensionFactory">
- </view>
- </extension>
-
- <!-- EDITORS -->
- <extension
- point="org.eclipse.ui.editors">
- <!-- Security -->
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.cms.ui.workbench.userEditor"
- name="User"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/person.png"
- default="false">
- </editor>
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.cms.ui.workbench.groupEditor"
- name="User"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/group.png"
- default="false">
- </editor>
- <!-- Data Explorer -->
- <editor
- name="JCR Query"
- id="org.argeo.cms.ui.workbench.genericJcrQueryEditor"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/query.png"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- default="false">
- </editor>
- <editor
- name="Node Editor"
- id="org.argeo.cms.ui.workbench.defaultNodeEditor"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/query.png"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- default="false">
- </editor>
- </extension>
-
- <extension
- point="org.eclipse.ui.commands">
- <!-- User CRUD -->
- <command
- id="org.argeo.cms.ui.workbench.newUser"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="New User">
- </command>
- <command
- id="org.argeo.cms.ui.workbench.deleteUsers"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Delete User">
- </command>
- <command
- id="org.argeo.cms.ui.workbench.userBatchUpdate"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="User batch update">
- </command>
- <!-- Group CRUD -->
- <command
- id="org.argeo.cms.ui.workbench.newGroup"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="New Group">
- </command>
- <command
- id="org.argeo.cms.ui.workbench.deleteGroups"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Delete Group">
- </command>
- <!-- Transaction -->
- <command
- id="org.argeo.cms.ui.workbench.userTransactionHandler"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Manage a user transaction">
- <commandParameter
- id="param.commandId"
- name="begin, commit or rollback">
- </commandParameter>
- </command>
- <!-- Force the refresh when the various listener are not enough -->
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.useradmin.commands.ForceRefresh"
- id="org.argeo.cms.ui.workbench.forceRefresh"
- name="Force Refresh">
- </command>
- <!-- Data Explorer -->
- <command
- defaultHandler="org.argeo.cms.ui.workbench.commands.OpenEditor"
- id="org.argeo.cms.ui.workbench.openEditor"
- name="Open an editor given its ID">
- <commandParameter
- id="param.jcrNodePath"
- name="Node path">
- </commandParameter>
- <!-- The path to the corresponding node if needed. -->
- <commandParameter
- id="param.jcrNodePath"
- name="Node path">
- </commandParameter>
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.GetNodeSize"
- id="org.argeo.cms.ui.workbench.getNodeSize"
- name="Get node size">
- </command>
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.cms.ui.workbench.addRemoteRepository"
- name="Add remote JCR repository">
- <!-- <commandParameter
- id="param.repositoryUri"
- name="Repository URI">
- </commandParameter> -->
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.RemoveRemoteRepository"
- id="org.argeo.cms.ui.workbench.removeRemoteRepository"
- name="Remove remote JCR repository">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.AddFolderNode"
- id="org.argeo.cms.ui.workbench.addFolderNode"
- name="Create a new folder">
- </command>
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.cms.ui.workbench.addPrivileges"
- name="Add Privileges">
- </command>
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.cms.ui.workbench.removePrivileges"
- name="Remove Privileges">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.CreateWorkspace"
- id="org.argeo.cms.ui.workbench.createWorkspace"
- name="Create a new workspace">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.Refresh"
- id="org.argeo.cms.ui.workbench.refresh"
- name="Refresh">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.DeleteNodes"
- id="org.argeo.cms.ui.workbench.deleteNodes"
- name="Delete nodes">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.UploadFiles"
- id="org.argeo.cms.ui.workbench.uploadFiles"
- name="Upload files">
- </command>
- <!-- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.cms.ui.workbench.openFile"
- name="Open current file">
- </command> -->
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.DumpNode"
- id="org.argeo.cms.ui.workbench.dumpNode"
- name="Dump Current Selected Node">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.RenameNode"
- id="org.argeo.cms.ui.workbench.renameNode"
- name="Rename Current Selected Node">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.ConfigurableNodeDump"
- id="org.argeo.cms.ui.workbench.nodeConfigurableDump"
- name="Configurable dump of the selected Node">
- </command>
- <command
- defaultHandler="org.argeo.cms.ui.workbench.internal.jcr.commands.SortChildNodes"
- id="org.argeo.cms.ui.workbench.sortChildNodes"
- name="Sort node tree">
- <!-- FIXME: default value does not work -->
- <state
- id="org.argeo.cms.ui.workbench.sortChildNodes.toggleState"
- class="org.eclipse.ui.handlers.RegistryToggleState:true" >
- <!-- <class class="org.eclipse.jface.commands.ToggleState">
- <parameter
- name="default"
- value="true" />
- </class> -->
- </state>
- </command>
- <!-- Utility to provide sub menues when we don't want to define a default command for this menu -->
- <command
- id="org.argeo.cms.ui.workbench.doNothing"
- defaultHandler="org.argeo.cms.ui.workbench.commands.DoNothing"
- name="Open menu">
- </command>
- </extension>
-
- <!-- MENU CONTRIBUTIONS -->
- <extension
- point="org.eclipse.ui.menus">
- <!-- Main tool bar menu
- <menuContribution locationURI="toolbar:org.eclipse.ui.main.toolbar">
- <toolbar id="org.argeo.cms.ui.workbench.userToolbar">
- <command
- commandId="org.argeo.cms.ui.workbench.rap.mainMenuCommand"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/home.png"
- id="org.argeo.cms.ui.workbench.rap.mainMenu"
- style="pulldown">
- </command>
- <command commandId="org.eclipse.ui.file.save" icon="platform:/plugin/org.argeo.cms.ui.theme/icons/save.png"/>
- <command commandId="org.eclipse.ui.file.saveAll" icon="platform:/plugin/org.argeo.cms.ui.theme/icons/save-all.png"/>
- </toolbar>
- </menuContribution>
- -->
- <menuContribution
- locationURI="toolbar:org.argeo.cms.ui.workbench.userToolbar?after=org.eclipse.ui.file.saveAll">
- <!-- Transaction management -->
- <command
- commandId="org.argeo.cms.ui.workbench.userTransactionHandler"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/commit.gif"
- label="Commit Transaction"
- style="push"
- tooltip="Commit a user transaction">
- <parameter name="param.commandId" value="transaction.commit" />
- <visibleWhen>
- <with variable="org.argeo.cms.ui.workbench.userTransactionState">
- <equals value="status.active" />
- </with>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.userTransactionHandler"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/rollback.gif"
- label="Rollback Transaction"
- style="push"
- tooltip="Abandon current changes and rollback to the latest commited version">
- <parameter name="param.commandId" value="transaction.rollback" />
- <visibleWhen>
- <with variable="org.argeo.cms.ui.workbench.userTransactionState">
- <equals value="status.active" />
- </with>
- </visibleWhen>
- </command>
- </menuContribution>
-
- <!-- UsersView specific toolbar menu -->
- <menuContribution
- locationURI="toolbar:org.argeo.cms.ui.workbench.usersView">
- <command
- commandId="org.argeo.cms.ui.workbench.deleteUsers"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/delete.png"
- label="Delete"
- tooltip="Delete selected users">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.forceRefresh"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/refresh.png"
- label="Refresh"
- tooltip="Force the full refresh of the user list">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.newUser"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/add.png"
- label="Add"
- tooltip="Create a new user">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.userBatchUpdate"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/batch.gif"
- label="Update users"
- tooltip="Perform maintenance activities on a list of chosen users">
- </command>
- </menuContribution>
-
- <!-- GroupsView specific toolbar menu -->
- <menuContribution
- locationURI="toolbar:org.argeo.cms.ui.workbench.groupsView">
- <command
- commandId="org.argeo.cms.ui.workbench.deleteGroups"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/delete.png"
- label="Delete Group"
- tooltip="Delete selected groups">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.forceRefresh"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/refresh.png"
- label="Refresh list"
- tooltip="Force the full refresh of the group list">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.newGroup"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/add.png"
- label="Add Group"
- tooltip="Create a new group">
- </command>
- </menuContribution>
-
- <!-- Browser view specific menu -->
- <menuContribution
- locationURI="menu:org.argeo.cms.ui.workbench.jcrBrowserView">
- <!-- See bug 149 -->
- <!-- <command
- commandId="org.argeo.cms.ui.workbench.openGenericJcrQueryEditor"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/query.png"
- style="push">
- </command> -->
- <command
- commandId="org.argeo.cms.ui.workbench.addRemoteRepository"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/addRepo.gif"
- style="push">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.sortChildNodes"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/sort.gif"
- style="toggle"
- label="Sort child nodes"
- tooltip="NOTE: displaying unsorted nodes will enhance overall performances">
- </command>
- </menuContribution>
- <!-- Browser view popup context menu -->
- <menuContribution
- locationURI="popup:org.argeo.cms.ui.workbench.jcrBrowserView">
- <command
- commandId="org.argeo.cms.ui.workbench.refresh"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/refresh.png"
- style="push">
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.addFolderNode"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/addFolder.gif"
- label="Add Folder..."
- style="push">
- <visibleWhen>
- <iterate>
- <and>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem">
- </instanceof>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem">
- </instanceof>
- </or>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.addPrivileges"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/addPrivileges.gif"
- label="Add Privileges..."
- style="push">
- <visibleWhen>
- <iterate>
- <and>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem">
- </instanceof>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem">
- </instanceof>
- </or>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.removePrivileges"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/removePrivileges.gif"
- label="Remove Privileges..."
- style="push">
- <visibleWhen>
- <iterate>
- <and>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem">
- </instanceof>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem">
- </instanceof>
- </or>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.createWorkspace"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/addWorkspace.png"
- label="Create Workspace..."
- style="push">
- <visibleWhen>
- <iterate>
- <and>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.RepositoryElem">
- </instanceof>
- </or>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.deleteNodes"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/remove.gif"
- label="Delete Nodes"
- style="push">
- <visibleWhen>
- <iterate>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem" />
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem" />
- </or>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.uploadFiles"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/import_fs.png"
- style="push"
- tooltip="Upload files from the local file sytem">
- <visibleWhen>
- <iterate>
- <and>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem" />
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem" />
- </or>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.addRemoteRepository"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/addRepo.gif"
- style="push">
- <visibleWhen>
- <iterate>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.RepositoriesElem" />
- <instanceof
- value="org.argeo.cms.ui.jcr.model.RepositoryElem" />
- </or>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.removeRemoteRepository"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/remove.gif"
- style="push">
- <visibleWhen>
- <iterate>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.RemoteRepositoryElem" />
- </or>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.getNodeSize"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/getSize.gif"
- style="push">
- <visibleWhen>
- <iterate>
- <or>
- <instanceof
- value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem" />
- <instanceof
- value="org.argeo.cms.ui.jcr.model.WorkspaceElem" />
- </or>
- </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.dumpNode"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/dumpNode.gif"
- label="Dump Node"
- style="push">
- <visibleWhen>
- <iterate> <and>
- <instanceof value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem"></instanceof>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and> </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.renameNode"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/rename.gif"
- label="Rename..."
- style="push">
- <visibleWhen>
- <iterate> <and>
- <instanceof value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem"></instanceof>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and> </iterate>
- </visibleWhen>
- </command>
- <command
- commandId="org.argeo.cms.ui.workbench.nodeConfigurableDump"
- icon="platform:/plugin/org.argeo.cms.ui.theme/icons/dumpNode.gif"
- label="Configurable dump..."
- style="push">
- <visibleWhen>
- <iterate>
- <and>
- <instanceof value="org.argeo.cms.ui.jcr.model.SingleJcrNodeElem"></instanceof>
- <with variable="activeMenuSelection"><count value="1"/></with>
- </and>
- </iterate>
- </visibleWhen>
- </command>
- </menuContribution>
-
- </extension>
-
- <!-- SERVICES -->
- <extension
- point="org.eclipse.ui.services">
- <sourceProvider
- id="org.argeo.cms.ui.workbench.userTransactionProvider"
- provider="org.argeo.eclipse.spring.SpringExtensionFactory" >
- <variable
- name="org.argeo.cms.ui.workbench.userTransactionState"
- priorityLevel="workbench">
- </variable>
- </sourceProvider>
- <sourceProvider
- provider="org.argeo.cms.ui.workbench.util.RolesSourceProvider">
- <variable
- name="org.argeo.cms.ui.workbench.rolesVariable"
- priorityLevel="workbench">
- </variable>
- </sourceProvider>
- </extension>
-
- <!-- ACTIVITIES -->
- <extension
- point="org.eclipse.ui.activities">
-
- <!-- Admin -->
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.osgiPerspective"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.adminActivity">
- </activityPatternBinding>
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.jcrBrowserPerspective"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.adminActivity">
- </activityPatternBinding>
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.adminMaintenancePerspective"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.adminActivity">
- </activityPatternBinding>
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.adminLogView"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.adminActivity">
- </activityPatternBinding>
-
- <!-- UserAdmin -->
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.adminSecurityPerspective"
- activityId="org.argeo.cms.ui.workbench.userAdminActivity"
- isEqualityPattern="true">
- </activityPatternBinding>
-
- <!-- Users -->
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.userHomePerspective"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.userActivity">
- </activityPatternBinding>
- <activityPatternBinding
- pattern="org.argeo.cms.ui.workbench/org.argeo.cms.ui.workbench.userProfile"
- isEqualityPattern="true"
- activityId="org.argeo.cms.ui.workbench.userActivity">
- </activityPatternBinding>
-
-
- <!-- Activity declaration -->
- <activity
- description="Authenticated users"
- id="org.argeo.cms.ui.workbench.userActivity"
- name="User">
- <enabledWhen>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=user,ou=roles,ou=node" />
- </iterate>
- </with>
- </enabledWhen>
- </activity>
- <activity
- description="Admins"
- id="org.argeo.cms.ui.workbench.adminActivity"
- name="Admin">
- <enabledWhen>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=admin,ou=roles,ou=node" />
- </iterate>
- </with>
- </enabledWhen>
- </activity>
- <activity
- description="User Admins"
- id="org.argeo.cms.ui.workbench.userAdminActivity"
- name="User Admin">
- <enabledWhen>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=userAdmin,ou=roles,ou=node" />
- </iterate>
- </with>
- </enabledWhen>
- </activity>
- <activity
- description="Non admins"
- id="org.argeo.cms.ui.workbench.notAdminActivity"
- name="Not Admin">
- <enabledWhen>
- <not>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=admin,ou=roles,ou=node" />
- </iterate>
- </with>
- </not>
- </enabledWhen>
- </activity>
- <activity
- description="Non remote"
- id="org.argeo.cms.ui.workbench.notRemoteActivity"
- name="NonRemote">
- <enabledWhen>
- <not>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="ROLE_REMOTE" />
- </iterate>
- </with>
- </not>
- </enabledWhen>
- </activity>
- </extension>
-
- <!-- STARTUP -->
- <extension point="org.eclipse.ui.startup">
- <startup class="org.argeo.cms.ui.workbench.internal.useradmin.PartStateChanged"/>
- </extension>
-</plugin>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<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.legacy.commons</groupId>
- <artifactId>argeo-commons-legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.cms.ui.workbench</artifactId>
- <name>CMS Workbench</name>
- <packaging>jar</packaging>
- <dependencies>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.ui</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- <dependency>
- <groupId>org.argeo.commons.rap</groupId>
- <artifactId>org.argeo.swt.specific.rap</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- Spring -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.core</artifactId>
- </dependency>
-
- <!-- Eclipse 3 -->
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.spring;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-
-/** Provides base method for executing code with system authorization. */
-abstract class AbstractSystemExecution {
- private final static CmsLog log = CmsLog.getLog(AbstractSystemExecution.class);
- private final Subject subject = new Subject();
-
- /** Authenticate the calling thread */
- protected void authenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.login();
- } catch (LoginException e) {
- throw new CmsException("Cannot login as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- if (log.isTraceEnabled())
- log.trace("System authenticated");
- }
-
- protected void deauthenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.logout();
- } catch (LoginException e) {
- throw new CmsException("Cannot logout as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- }
-
- protected Subject getSubject() {
- return subject;
- }
-}
+++ /dev/null
-package org.argeo.cms.spring;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.support.AbstractBeanFactory;
-import org.springframework.beans.factory.support.SecurityContextProvider;
-import org.springframework.beans.factory.support.SimpleSecurityContextProvider;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-/**
- * Executes with a system authentication the instantiation and initialization
- * methods of the application context where it has been defined.
- */
-public class AuthenticatedApplicationContextInitialization extends
- AbstractSystemExecution implements
- DependencyInitializationAwareBeanPostProcessor, ApplicationContextAware {
- /** If non empty, restricts to these beans */
- private List<String> beanNames = new ArrayList<String>();
-
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- authenticateAsSystem();
- return bean;
- }
-
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- deauthenticateAsSystem();
- return bean;
- }
-
- public void setBeanNames(List<String> beanNames) {
- this.beanNames = beanNames;
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- if (applicationContext.getAutowireCapableBeanFactory() instanceof AbstractBeanFactory) {
- final AbstractBeanFactory beanFactory = ((AbstractBeanFactory) applicationContext
- .getAutowireCapableBeanFactory());
- // retrieve subject's access control context
- // and set it as the bean factory security context
- Subject.doAs(getSubject(), new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- SecurityContextProvider scp = new SimpleSecurityContextProvider(
- AccessController.getContext());
- beanFactory.setSecurityContextProvider(scp);
- return null;
- }
- });
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.spring;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.UserAdmin;
-
-/**
- * Register one or many roles via a user admin service. Does nothing if the role
- * is already registered.
- */
-public class SimpleRoleRegistration implements Runnable {
- private final static CmsLog log = CmsLog.getLog(SimpleRoleRegistration.class);
-
- private String role;
- private List<String> roles = new ArrayList<String>();
- private UserAdmin userAdmin;
- private WorkTransaction userTransaction;
-
- @Override
- public void run() {
- try {
- userTransaction.begin();
- if (role != null && !roleExists(role))
- newRole(toDn(role));
-
- for (String r : roles)
- if (!roleExists(r))
- newRole(toDn(r));
- userTransaction.commit();
- } catch (Exception e) {
- try {
- userTransaction.rollback();
- } catch (Exception e1) {
- log.error("Cannot rollback", e1);
- }
- throw new CmsException("Cannot add roles", e);
- }
- }
-
- private boolean roleExists(String role) {
- return userAdmin.getRole(toDn(role).toString()) != null;
- }
-
- protected void newRole(LdapName r) {
- userAdmin.createRole(r.toString(), Role.GROUP);
- log.info("Added role " + r + " required by application.");
- }
-
- public void register(UserAdmin userAdminService, Map<?, ?> properties) {
- this.userAdmin = userAdminService;
- run();
- }
-
- protected LdapName toDn(String name) {
- try {
- return new LdapName("cn=" + name + ",ou=roles,ou=node");
- } catch (InvalidNameException e) {
- throw new CmsException("Badly formatted role name " + name, e);
- }
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public void setRoles(List<String> roles) {
- this.roles = roles;
- }
-
- public void setUserAdmin(UserAdmin userAdminService) {
- this.userAdmin = userAdminService;
- }
-
- public void setUserTransaction(WorkTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.spring.osgi;
-
-import org.argeo.api.cms.CmsLog;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-
-/**
- * Logs the name and version of an OSGi bundle based on its
- * {@link BundleContext}.
- */
-public class OsgiModuleLabel {
- private final static CmsLog log = CmsLog.getLog(OsgiModuleLabel.class);
-
- private Bundle bundle;
-
- public OsgiModuleLabel() {
- }
-
- /** Sets without logging. */
- public OsgiModuleLabel(Bundle bundle) {
- this.bundle = bundle;
- }
-
- /**
- * Retrieved bundle from a bundle context and logs it. Typically to be set
- * as a Spring bean.
- */
- public void setBundleContext(BundleContext bundleContext) {
- this.bundle = bundleContext.getBundle();
- log.info(msg());
- }
-
- public String msg() {
- String name = bundle.getHeaders().get(Constants.BUNDLE_NAME).toString();
- String symbolicName = bundle.getSymbolicName();
- String version = bundle.getVersion().toString();
- return name + " v" + version + " (" + symbolicName + ")";
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-
-import org.argeo.api.cms.CmsLog;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.TrayDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.operation.ModalContext;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.osgi.framework.FrameworkUtil;
-
-/** Base for login dialogs */
-@Deprecated
-public abstract class AbstractLoginDialog extends TrayDialog implements CallbackHandler {
- private static final long serialVersionUID = -8046708963512717709L;
-
- private final static CmsLog log = CmsLog.getLog(AbstractLoginDialog.class);
-
- private Thread modalContextThread = null;
- boolean processCallbacks = false;
- boolean isCancelled = false;
- Callback[] callbackArray;
-
- protected final Callback[] getCallbacks() {
- return this.callbackArray;
- }
-
- public abstract void internalHandle();
-
- public boolean isCancelled() {
- return isCancelled;
- }
-
- protected AbstractLoginDialog(Shell parentShell) {
- super(parentShell);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * javax.security.auth.callback.CallbackHandler#handle(javax.security.auth
- * .callback.Callback[])
- */
- public void handle(final Callback[] callbacks) throws IOException {
- // clean previous usage
- if (processCallbacks) {
- // this handler was already used
- processCallbacks = false;
- }
-
- if (modalContextThread != null) {
- try {
- modalContextThread.join(1000);
- } catch (InterruptedException e) {
- // silent
- }
- modalContextThread = null;
- }
-
- // initialize
- this.callbackArray = callbacks;
- final Display display = Display.getDefault();
- display.syncExec(new Runnable() {
-
- public void run() {
- isCancelled = false;
- setBlockOnOpen(false);
- open();
-
- final Button okButton = getButton(IDialogConstants.OK_ID);
- okButton.setText("Login");
- okButton.addSelectionListener(new SelectionListener() {
- private static final long serialVersionUID = -200281625679096775L;
-
- public void widgetSelected(final SelectionEvent event) {
- processCallbacks = true;
- }
-
- public void widgetDefaultSelected(final SelectionEvent event) {
- // nothing to do
- }
- });
- final Button cancel = getButton(IDialogConstants.CANCEL_ID);
- cancel.addSelectionListener(new SelectionListener() {
- private static final long serialVersionUID = -3826030278084915815L;
-
- public void widgetSelected(final SelectionEvent event) {
- isCancelled = true;
- processCallbacks = true;
- }
-
- public void widgetDefaultSelected(final SelectionEvent event) {
- // nothing to do
- }
- });
- }
- });
- try {
- ModalContext.setAllowReadAndDispatch(true); // Works for now.
- ModalContext.run(new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor monitor) {
- modalContextThread = Thread.currentThread();
- // Wait here until OK or cancel is pressed, then let it rip.
- // The event
- // listener
- // is responsible for closing the dialog (in the
- // loginSucceeded
- // event).
- while (!processCallbacks && (modalContextThread != null)
- && (modalContextThread == Thread.currentThread())
- && FrameworkUtil.getBundle(AbstractLoginDialog.class).getBundleContext() != null) {
- // Note: SecurityUiPlugin.getDefault() != null is false
- // when the OSGi runtime is shut down
- try {
- Thread.sleep(100);
- // if (display.isDisposed()) {
- // log.warn("Display is disposed, killing login
- // dialog thread");
- // throw new ThreadDeath();
- // }
- } catch (final Exception e) {
- // do nothing
- }
- }
- processCallbacks = false;
- // Call the adapter to handle the callbacks
- if (!isCancelled())
- internalHandle();
- else
- // clear callbacks are when cancelling
- for (Callback callback : callbacks)
- if (callback instanceof PasswordCallback) {
- char[] arr = ((PasswordCallback) callback).getPassword();
- if (arr != null) {
- Arrays.fill(arr, '*');
- ((PasswordCallback) callback).setPassword(null);
- }
- } else if (callback instanceof NameCallback)
- ((NameCallback) callback).setName(null);
- }
- }, true, new NullProgressMonitor(), Display.getDefault());
- } catch (ThreadDeath e) {
- isCancelled = true;
- log.debug("Thread " + Thread.currentThread().getId() + " died");
- throw e;
- } catch (Exception e) {
- isCancelled = true;
- IOException ioe = new IOException("Unexpected issue in login dialog, see root cause for more details");
- ioe.initCause(e);
- throw ioe;
- } finally {
- // so that the modal thread dies
- processCallbacks = true;
- // try {
- // // wait for the modal context thread to gracefully exit
- // modalContextThread.join();
- // } catch (InterruptedException ie) {
- // // silent
- // }
- modalContextThread = null;
- }
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Authentication");
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-/** Centralize the declaration of Workbench specific CSS Styles */
-public interface CmsWorkbenchStyles {
-
- // Specific People layouting
- String WORKBENCH_FORM_TEXT = "workbench_form_text";
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import javax.security.auth.callback.CallbackHandler;
-
-import org.argeo.cms.swt.auth.CompositeCallbackHandler;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-
-/** Default authentication dialog, to be used as {@link CallbackHandler}. */
-@Deprecated
-public class DefaultLoginDialog extends AbstractLoginDialog {
- private static final long serialVersionUID = -8551827590693035734L;
-
- public DefaultLoginDialog() {
- this(Display.getCurrent().getActiveShell());
- }
-
- public DefaultLoginDialog(Shell parentShell) {
- super(parentShell);
- }
-
- protected Point getInitialSize() {
- return new Point(350, 180);
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Control control = super.createContents(parent);
- parent.pack();
-
- // Move the dialog to the center of the top level shell.
- Rectangle shellBounds;
- if (Display.getCurrent().getActiveShell() != null) // RCP
- shellBounds = Display.getCurrent().getActiveShell().getBounds();
- else
- shellBounds = Display.getCurrent().getBounds();// RAP
- Point dialogSize = parent.getSize();
- int x = shellBounds.x + (shellBounds.width - dialogSize.x) / 2;
- int y = shellBounds.y + (shellBounds.height - dialogSize.y) / 2;
- parent.setLocation(x, y);
- return control;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- CompositeCallbackHandler composite = new CompositeCallbackHandler(
- dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- composite.createCallbackHandlers(getCallbacks());
- return composite;
- }
-
- public void internalHandle() {
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.cms.ui.workbench.jcr.NodeFsBrowserView;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Base perspective for the Jcr browser */
-public class JcrBrowserPerspective implements IPerspectiveFactory {
-
- public void createInitialLayout(IPageLayout layout) {
- layout.setEditorAreaVisible(true);
- IFolderLayout upperLeft = layout.createFolder(WorkbenchUiPlugin.PLUGIN_ID + ".upperLeft", IPageLayout.LEFT,
- 0.4f, layout.getEditorArea());
- upperLeft.addView(JcrBrowserView.ID);
- upperLeft.addView(NodeFsBrowserView.ID);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import org.argeo.cms.ui.workbench.useradmin.AdminLogView;
-import org.argeo.cms.ui.workbench.useradmin.UserProfile;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** First draft of a maintenance perspective. Not yet used */
-public class MaintenancePerspective implements IPerspectiveFactory {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".adminMaintenancePerspective";
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout bottom = layout.createFolder("bottom",
- IPageLayout.BOTTOM, 0.50f, editorArea);
- bottom.addView(AdminLogView.ID);
-
- IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT,
- 0.30f, editorArea);
- left.addView(UserProfile.ID);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** OSGi explorer perspective (to be enriched declaratively) */
-public class OsgiExplorerPerspective implements IPerspectiveFactory {
-
- public void createInitialLayout(IPageLayout layout) {
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.GroupsView;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UsersView;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Default perspective to manage users and groups */
-public class SecurityAdminPerspective implements IPerspectiveFactory {
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT, 0.3f, editorArea);
- IFolderLayout right = layout.createFolder("right", IPageLayout.RIGHT, 0.5f, editorArea);
- left.addView(UsersView.ID);
- right.addView(GroupsView.ID);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import org.argeo.cms.ui.workbench.jcr.NodeFsBrowserView;
-import org.argeo.cms.ui.workbench.useradmin.UserProfile;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Home perspective for the current user */
-public class UserHomePerspective implements IPerspectiveFactory {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".userHomePerspective";
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT, 0.40f, editorArea);
- left.addView(NodeFsBrowserView.ID);
- left.addView(UserProfile.ID);
- // left.addView(LogView.ID);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench;
-
-import java.io.IOException;
-import java.util.ResourceBundle;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.eclipse.core.runtime.ILogListener;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/** The activator class controls the plug-in life cycle */
-public class WorkbenchUiPlugin extends AbstractUIPlugin implements ILogListener {
- private final static CmsLog log = CmsLog.getLog(WorkbenchUiPlugin.class);
-
- // The plug-in ID
- public final static String PLUGIN_ID = "org.argeo.cms.ui.workbench"; //$NON-NLS-1$
- public final static String THEME_PLUGIN_ID = "org.argeo.cms.ui.theme"; //$NON-NLS-1$
-
- private ResourceBundle messages;
- private static BundleContext bundleContext;
-
- public static InheritableThreadLocal<Display> display = new InheritableThreadLocal<Display>() {
-
- @Override
- protected Display initialValue() {
- return Display.getCurrent();
- }
- };
-
- final static String CONTEXT_KEYRING = "KEYRING";
-
- private CallbackHandler defaultCallbackHandler;
- private ServiceRegistration<CallbackHandler> defaultCallbackHandlerReg;
-
- // The shared instance
- private static WorkbenchUiPlugin plugin;
-
- public void start(BundleContext context) throws Exception {
- super.start(context);
- bundleContext = context;
- defaultCallbackHandler = new DefaultCallbackHandler();
- defaultCallbackHandlerReg = context.registerService(CallbackHandler.class, defaultCallbackHandler, null);
-
- plugin = this;
- messages = ResourceBundle.getBundle(PLUGIN_ID + ".messages");
- Platform.addLogListener(this);
- if (log.isTraceEnabled())
- log.trace("Eclipse logging now directed to standard logging");
- }
-
- public void stop(BundleContext context) throws Exception {
- bundleContext = null;
- defaultCallbackHandlerReg.unregister();
- }
-
- public static BundleContext getBundleContext() {
- return bundleContext;
- }
-
- /*
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static WorkbenchUiPlugin getDefault() {
- return plugin;
- }
-
- protected class DefaultCallbackHandler implements CallbackHandler {
- public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
-
- // if (display != null) // RCP
- Display displayToUse = display.get();
- if (displayToUse == null)// RCP
- displayToUse = Display.getDefault();
- displayToUse.syncExec(new Runnable() {
- public void run() {
- DefaultLoginDialog dialog = new DefaultLoginDialog(display.get().getActiveShell());
- try {
- dialog.handle(callbacks);
- } catch (IOException e) {
- throw new CmsException("Cannot open dialog", e);
- }
- }
- });
- // else {// RAP
- // DefaultLoginDialog dialog = new DefaultLoginDialog();
- // dialog.handle(callbacks);
- // }
- }
-
- }
-
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(THEME_PLUGIN_ID, path);
- }
-
- /** Returns the internationalized label for the given key */
- public static String getMessage(String key) {
- try {
- return getDefault().messages.getString(key);
- } catch (NullPointerException npe) {
- log.warn(key + " not found.");
- return key;
- }
- }
-
- /**
- * Gives access to the internationalization message bundle. Returns null in case
- * this UiPlugin is not started (for JUnit tests, by instance)
- */
- public static ResourceBundle getMessagesBundle() {
- if (getDefault() != null)
- // To avoid NPE
- return getDefault().messages;
- else
- return null;
- }
-
- public void logging(IStatus status, String plugin) {
- CmsLog pluginLog = CmsLog.getLog(plugin);
- Integer severity = status.getSeverity();
- if (severity == IStatus.ERROR)
- pluginLog.error(status.getMessage(), status.getException());
- else if (severity == IStatus.WARNING)
- pluginLog.warn(status.getMessage(), status.getException());
- else if (severity == IStatus.INFO)
- pluginLog.info(status.getMessage(), status.getException());
- else if (severity == IStatus.CANCEL)
- if (pluginLog.isDebugEnabled())
- pluginLog.debug(status.getMessage(), status.getException());
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.commands;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-/** Utilitary command to enable sub menus in various toolbars. Does nothing */
-public class DoNothing extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".doNothing";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.commands;
-
-import static org.argeo.cms.CmsMsg.changePassword;
-import static org.argeo.cms.CmsMsg.currentPassword;
-import static org.argeo.cms.CmsMsg.newPassword;
-import static org.argeo.cms.CmsMsg.passwordChanged;
-import static org.argeo.cms.CmsMsg.repeatNewPassword;
-import static org.eclipse.jface.dialogs.IMessageProvider.INFORMATION;
-
-import java.security.AccessController;
-import java.util.Arrays;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-import javax.security.auth.Subject;
-import javax.security.auth.x500.X500Principal;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.security.CryptoKeyring;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-
-/** Open the change password dialog */
-public class OpenChangePasswordDialog extends AbstractHandler {
- private final static CmsLog log = CmsLog.getLog(OpenChangePasswordDialog.class);
- private UserAdmin userAdmin;
- private WorkTransaction userTransaction;
- private CryptoKeyring keyring = null;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ChangePasswordDialog dialog = new ChangePasswordDialog(HandlerUtil.getActiveShell(event), userAdmin);
- if (dialog.open() == Dialog.OK) {
- MessageDialog.openInformation(HandlerUtil.getActiveShell(event), passwordChanged.lead(),
- passwordChanged.lead());
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- protected void changePassword(char[] oldPassword, char[] newPassword) {
- Subject subject = Subject.getSubject(AccessController.getContext());
- String name = subject.getPrincipals(X500Principal.class).iterator().next().toString();
- LdapName dn;
- try {
- dn = new LdapName(name);
- } catch (InvalidNameException e) {
- throw new CmsException("Invalid user dn " + name, e);
- }
- User user = (User) userAdmin.getRole(dn.toString());
- if (!user.hasCredential(null, oldPassword))
- throw new CmsException("Invalid password");
- if (Arrays.equals(newPassword, new char[0]))
- throw new CmsException("New password empty");
- try {
- userTransaction.begin();
- user.getCredentials().put(null, newPassword);
- if (keyring != null) {
- keyring.changePassword(oldPassword, newPassword);
- // TODO change secret keys in the CMS session
- }
- userTransaction.commit();
- } catch (Exception e) {
- try {
- userTransaction.rollback();
- } catch (Exception e1) {
- log.error("Could not roll back", e1);
- }
- if (e instanceof RuntimeException)
- throw (RuntimeException) e;
- else
- throw new CmsException("Cannot change password", e);
- }
- }
-
- class ChangePasswordDialog extends TitleAreaDialog {
- private static final long serialVersionUID = -6963970583882720962L;
- private Text oldPassword, newPassword1, newPassword2;
-
- public ChangePasswordDialog(Shell parentShell, UserAdmin securityService) {
- super(parentShell);
- }
-
- protected Point getInitialSize() {
- return new Point(400, 450);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- oldPassword = createLP(composite, currentPassword.lead());
- newPassword1 = createLP(composite, newPassword.lead());
- newPassword2 = createLP(composite, repeatNewPassword.lead());
-
- setMessage(changePassword.lead(), INFORMATION);
- parent.pack();
- oldPassword.setFocus();
- return composite;
- }
-
- @Override
- protected void okPressed() {
- try {
- if (!newPassword1.getText().equals(newPassword2.getText()))
- throw new CmsException("New passwords are different");
- changePassword(oldPassword.getTextChars(), newPassword1.getTextChars());
- close();
- } catch (Exception e) {
- ErrorFeedback.show("Cannot change password", e);
- }
- }
-
- /** Creates label and password. */
- protected Text createLP(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.PASSWORD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- return text;
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText(changePassword.lead());
- }
- }
-
- public void setUserAdmin(UserAdmin userAdmin) {
- this.userAdmin = userAdmin;
- }
-
- public void setUserTransaction(WorkTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-
- public void setKeyring(CryptoKeyring keyring) {
- this.keyring = keyring;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.commands;
-
-import javax.jcr.Node;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.JcrQueryEditorInput;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.NodeEditorInput;
-import org.argeo.cms.ui.workbench.jcr.DefaultNodeEditor;
-import org.argeo.cms.ui.workbench.jcr.GenericJcrQueryEditor;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Open a {@link Node} editor of a specific type given the node path */
-public class OpenEditor extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".openEditor";
-
- public final static String PARAM_PATH = "param.jcrNodePath";
- public final static String PARAM_EDITOR_ID = "param.editorId";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String editorId = event.getParameter(PARAM_EDITOR_ID);
- try {
- IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow(
- event).getActivePage();
- if (DefaultNodeEditor.ID.equals(editorId)) {
- String path = event.getParameter(PARAM_PATH);
- NodeEditorInput nei = new NodeEditorInput(path);
- activePage.openEditor(nei, DefaultNodeEditor.ID);
- } else if (GenericJcrQueryEditor.ID.equals(editorId)) {
- JcrQueryEditorInput editorInput = new JcrQueryEditorInput(
- GenericJcrQueryEditor.ID, null);
- activePage.openEditor(editorInput, editorId);
- }
- } catch (PartInitException e) {
- throw new EclipseUiException(
- "Cannot open editor of ID " + editorId, e);
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.commands;
-
-import org.argeo.cms.ui.workbench.UserHomePerspective;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Default action of the user menu */
-public class OpenHomePerspective extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- HandlerUtil.getActiveSite(event).getWorkbenchWindow()
- .openPage(UserHomePerspective.ID, null);
- } catch (WorkbenchException e) {
- ErrorFeedback.show("Cannot open home perspective", e);
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal;
-
-/** Constants used across the application. */
-@Deprecated
-public interface WorkbenchConstants {
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Adds a node of type nt:folder, only on {@link SingleJcrNodeElem} and
- * {@link WorkspaceElem} TreeObject types.
- *
- * This handler assumes that a selection provider is available and picks only
- * first selected item. It is UI's job to enable the command only when the
- * selection contains one and only one element. Thus no parameter is passed
- * through the command.
- */
-public class AddFolderNode extends AbstractHandler {
-
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".addFolderNode";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
-
- JcrBrowserView view = (JcrBrowserView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(HandlerUtil.getActivePartId(event));
-
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
- TreeParent treeParentNode = null;
- Node jcrParentNode = null;
-
- if (obj instanceof SingleJcrNodeElem) {
- treeParentNode = (TreeParent) obj;
- jcrParentNode = ((SingleJcrNodeElem) treeParentNode).getNode();
- } else if (obj instanceof WorkspaceElem) {
- treeParentNode = (TreeParent) obj;
- jcrParentNode = ((WorkspaceElem) treeParentNode).getRootNode();
- } else
- return null;
-
- String folderName = SingleValue.ask("Folder name",
- "Enter folder name");
- if (folderName != null) {
- try {
- jcrParentNode.addNode(folderName, NodeType.NT_FOLDER);
- jcrParentNode.getSession().save();
- view.nodeAdded(treeParentNode);
- } catch (RepositoryException e) {
- ErrorFeedback.show("Cannot create folder " + folderName
- + " under " + treeParentNode, e);
- }
- }
- } else {
- ErrorFeedback.show(WorkbenchUiPlugin
- .getMessage("errorUnvalidNtFolderNodeType"));
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.AddPrivilegeWizard;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.UserAdmin;
-
-/** Open a dialog to add privileges on the selected node to a chosen group */
-public class AddPrivileges extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".addPrivileges";
-
- /* DEPENDENCY INJECTION */
- private UserAdmin userAdmin;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
- TreeParent treeParentNode = null;
- Node jcrParentNode = null;
-
- if (obj instanceof SingleJcrNodeElem) {
- treeParentNode = (TreeParent) obj;
- jcrParentNode = ((SingleJcrNodeElem) treeParentNode).getNode();
- } else if (obj instanceof WorkspaceElem) {
- treeParentNode = (TreeParent) obj;
- jcrParentNode = ((WorkspaceElem) treeParentNode).getRootNode();
- } else
- return null;
-
- try {
- String targetPath = jcrParentNode.getPath();
- AddPrivilegeWizard wizard = new AddPrivilegeWizard(
- jcrParentNode.getSession(), targetPath, userAdmin);
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- dialog.open();
- return null;
- } catch (RepositoryException re) {
- throw new EclipseUiException("Unable to retrieve "
- + "path or JCR session to add privilege on "
- + jcrParentNode, re);
- }
- } else {
- ErrorFeedback.show("Cannot add privileges");
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdmin(UserAdmin userAdmin) {
- this.userAdmin = userAdmin;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.net.URI;
-import java.util.Hashtable;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.security.Keyring;
-import org.argeo.cms.ui.workbench.internal.WorkbenchConstants;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Connect to a remote repository and, if successful publish it as an OSGi
- * service.
- */
-public class AddRemoteRepository extends AbstractHandler implements WorkbenchConstants, ArgeoNames {
-
- private RepositoryFactory repositoryFactory;
- private Repository nodeRepository;
- private Keyring keyring;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- RemoteRepositoryLoginDialog dlg = new RemoteRepositoryLoginDialog(Display.getDefault().getActiveShell());
- if (dlg.open() == Dialog.OK) {
- CommandUtils.callCommand(Refresh.ID);
- }
- return null;
- }
-
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-
- class RemoteRepositoryLoginDialog extends TitleAreaDialog {
- private static final long serialVersionUID = 2234006887750103399L;
- private Text name;
- private Text uri;
- private Text username;
- private Text password;
- private Button saveInKeyring;
-
- public RemoteRepositoryLoginDialog(Shell parentShell) {
- super(parentShell);
- }
-
- protected Point getInitialSize() {
- return new Point(600, 400);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- setMessage("Login to remote repository", IMessageProvider.NONE);
- name = createLT(composite, "Name", "remoteRepository");
- uri = createLT(composite, "URI", "http://localhost:7070/jcr/node");
- username = createLT(composite, "User", "");
- password = createLP(composite, "Password");
-
- saveInKeyring = createLC(composite, "Remember password", false);
- parent.pack();
- return composite;
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- Button test = createButton(parent, 2, "Test", false);
- test.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -1829962269440419560L;
-
- public void widgetSelected(SelectionEvent arg0) {
- testConnection();
- }
- });
- }
-
- void testConnection() {
- Session session = null;
- try {
- URI checkedUri = new URI(uri.getText());
- String checkedUriStr = checkedUri.toString();
-
- Hashtable<String, String> params = new Hashtable<String, String>();
- params.put(CmsConstants.LABELED_URI, checkedUriStr);
- Repository repository = repositoryFactory.getRepository(params);
- if (username.getText().trim().equals("")) {// anonymous
- // FIXME make it more generic
- session = repository.login("main");
- } else {
- // FIXME use getTextChars() when upgrading to 3.7
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=297412
- char[] pwd = password.getText().toCharArray();
- SimpleCredentials sc = new SimpleCredentials(username.getText(), pwd);
- session = repository.login(sc, "main");
- MessageDialog.openInformation(getParentShell(), "Success",
- "Connection to '" + uri.getText() + "' successful");
- }
- } catch (Exception e) {
- ErrorFeedback.show("Connection test failed for " + uri.getText(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- }
-
- @Override
- protected void okPressed() {
- Session nodeSession = null;
- try {
- nodeSession = nodeRepository.login();
- Node home = CmsJcrUtils.getUserHome(nodeSession);
-
- Node remote = home.hasNode(ARGEO_REMOTE) ? home.getNode(ARGEO_REMOTE) : home.addNode(ARGEO_REMOTE);
- if (remote.hasNode(name.getText()))
- throw new EclipseUiException("There is already a remote repository named " + name.getText());
- Node remoteRepository = remote.addNode(name.getText(), ArgeoTypes.ARGEO_REMOTE_REPOSITORY);
- remoteRepository.setProperty(ARGEO_URI, uri.getText());
- remoteRepository.setProperty(ARGEO_USER_ID, username.getText());
- nodeSession.save();
- if (saveInKeyring.getSelection()) {
- String pwdPath = remoteRepository.getPath() + '/' + ARGEO_PASSWORD;
- keyring.set(pwdPath, password.getText().toCharArray());
- }
- nodeSession.save();
- MessageDialog.openInformation(getParentShell(), "Repository Added",
- "Remote repository '" + username.getText() + "@" + uri.getText() + "' added");
-
- super.okPressed();
- } catch (Exception e) {
- ErrorFeedback.show("Cannot add remote repository", e);
- } finally {
- JcrUtils.logoutQuietly(nodeSession);
- }
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label, String initial) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- text.setText(initial);
- return text;
- }
-
- /** Creates label and check. */
- protected Button createLC(Composite parent, String label, Boolean initial) {
- new Label(parent, SWT.NONE).setText(label);
- Button check = new Button(parent, SWT.CHECK);
- check.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- check.setSelection(initial);
- return check;
- }
-
- protected Text createLP(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.PASSWORD);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return text;
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.GregorianCalendar;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * First draft of a wizard that enable configurable recursive dump of the
- * current selected Node (Only one at a time). Enable among other to export
- * children Nodes and to choose to export binaries or not. It is useful to
- * retrieve business data from live systems to prepare migration or test locally
- */
-public class ConfigurableNodeDump extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".nodeConfigurableDump";
-
- private final static DateFormat df = new SimpleDateFormat(
- "yyyy-MM-dd_HH-mm");
-
- public final static int EXPORT_NODE = 0;
- public final static int EXPORT_CHILDREN = 1;
- public final static int EXPORT_GRAND_CHILDREN = 2;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
- if (selection == null || !(selection instanceof IStructuredSelection))
- return null;
-
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();
- if (lst.hasNext()) {
- Object element = lst.next();
- if (element instanceof SingleJcrNodeElem) {
- SingleJcrNodeElem sjn = (SingleJcrNodeElem) element;
- Node node = sjn.getNode();
-
- ConfigureDumpWizard wizard = new ConfigureDumpWizard(
- HandlerUtil.getActiveShell(event),
- "Import Resource CSV");
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- int result = dialog.open();
-
- if (result == Window.OK) {
-
- String dateVal = df.format(new GregorianCalendar()
- .getTime());
- try {
-
- Path tmpDirPath = Files.createTempDirectory(dateVal
- + "-NodeDump-");
- List<Node> toExport = retrieveToExportNodes(node,
- wizard.currExportType);
-
- for (Node currNode : toExport) {
- FileOutputStream fos;
- String fileName = wizard.prefix
- + JcrUtils.replaceInvalidChars(currNode
- .getName()) + "_" + dateVal
- + ".xml";
- File currFile = new File(tmpDirPath.toString()
- + "/" + fileName);
- currFile.createNewFile();
- fos = new FileOutputStream(currFile);
- node.getSession().exportSystemView(
- currNode.getPath(), fos,
- !wizard.includeBinaries, false);
- fos.flush();
- fos.close();
- }
- } catch (RepositoryException e) {
- throw new EclipseUiException(
- "Unable to perform SystemExport on " + node, e);
- } catch (IOException e) {
- throw new EclipseUiException("Unable to SystemExport "
- + node, e);
- }
- }
- }
- }
- return null;
- }
-
- private List<Node> retrieveToExportNodes(Node node, int currExportType)
- throws RepositoryException {
- List<Node> nodes = new ArrayList<Node>();
- switch (currExportType) {
- case EXPORT_NODE:
- nodes.add(node);
- return nodes;
- case EXPORT_CHILDREN:
- return JcrUtils.nodeIteratorToList(node.getNodes());
- case EXPORT_GRAND_CHILDREN:
- NodeIterator nit = node.getNodes();
- while (nit.hasNext())
- nodes.addAll(JcrUtils.nodeIteratorToList(nit.nextNode()
- .getNodes()));
- return nodes;
-
- default:
- return nodes;
- }
- }
-
- // private synchronized void openGeneratedFile(String path, String fileName)
- // {
- // Map<String, String> params = new HashMap<String, String>();
- // params.put(OpenFile.PARAM_FILE_NAME, fileName);
- // params.put(OpenFile.PARAM_FILE_URI, "file://" + path);
- // CommandUtils.callCommand("org.argeo.security.ui.specific.openFile",
- // params);
- // }
-
- private class ConfigureDumpWizard extends Wizard {
-
- // parameters
- protected String prefix;
- protected int currExportType = EXPORT_NODE;
- protected boolean includeBinaries = false;
-
- // UI Objects
- private BasicPage page;
- private Text prefixTxt;
- private Button includeBinaryBtn;
- private Button b1, b2, b3;
-
- public ConfigureDumpWizard(Shell parentShell, String title) {
- setWindowTitle(title);
- }
-
- @Override
- public void addPages() {
- try {
- page = new BasicPage("Main page");
- addPage(page);
- } catch (Exception e) {
- throw new EclipseUiException("Cannot add page to wizard", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- prefix = prefixTxt.getText();
- if (b1.getSelection())
- currExportType = EXPORT_NODE;
- else if (b2.getSelection())
- currExportType = EXPORT_CHILDREN;
- else if (b3.getSelection())
- currExportType = EXPORT_GRAND_CHILDREN;
- includeBinaries = includeBinaryBtn.getSelection();
- return true;
- }
-
- @Override
- public boolean performCancel() {
- return true;
- }
-
- @Override
- public boolean canFinish() {
- String errorMsg = "No prefix defined.";
- if ("".equals(prefixTxt.getText().trim())) {
- page.setErrorMessage(errorMsg);
- return false;
- } else {
- page.setErrorMessage(null);
- return true;
- }
- }
-
- protected class BasicPage extends WizardPage {
- private static final long serialVersionUID = 1L;
-
- public BasicPage(String pageName) {
- super(pageName);
- setTitle("Configure dump before launching");
- setMessage("Define the parameters of the dump to launch");
- }
-
- public void createControl(Composite parent) {
- parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- // Main Layout
- Composite mainCmp = new Composite(parent, SWT.NONE);
- mainCmp.setLayout(new GridLayout(2, false));
- mainCmp.setLayoutData(EclipseUiUtils.fillAll());
-
- // The path
- createBoldLabel(mainCmp, "Prefix");
- prefixTxt = new Text(mainCmp, SWT.SINGLE | SWT.BORDER);
- prefixTxt.setLayoutData(EclipseUiUtils.fillAll());
- prefixTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- if (prefixTxt.getText() != null)
- getWizard().getContainer().updateButtons();
- }
- });
-
- new Label(mainCmp, SWT.SEPARATOR | SWT.HORIZONTAL)
- .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- false, 2, 1));
-
- // Which node to export
- Label typeLbl = new Label(mainCmp, SWT.RIGHT);
- typeLbl.setText(" Type");
- typeLbl.setFont(EclipseUiUtils.getBoldFont(mainCmp));
- typeLbl.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false,
- false, 1, 3));
-
- b1 = new Button(mainCmp, SWT.RADIO);
- b1.setText("Export this node");
- b1.setSelection(true);
- b2 = new Button(mainCmp, SWT.RADIO);
- b2.setText("Export children nodes");
- b3 = new Button(mainCmp, SWT.RADIO);
- b3.setText("Export grand-children nodes");
-
- new Label(mainCmp, SWT.SEPARATOR | SWT.HORIZONTAL)
- .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- false, 2, 1));
-
- createBoldLabel(mainCmp, "Files and images");
- includeBinaryBtn = new Button(mainCmp, SWT.CHECK);
- includeBinaryBtn.setText("Include binaries");
-
- prefixTxt.setFocus();
- setControl(mainCmp);
- }
- }
- }
-
- private Label createBoldLabel(Composite parent, String value) {
- Label label = new Label(parent, SWT.RIGHT);
- label.setText(" " + value);
- label.setFont(EclipseUiUtils.getBoldFont(parent));
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- return label;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.Arrays;
-
-import org.argeo.cms.ui.jcr.model.RepositoryElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Create a new JCR workspace */
-public class CreateWorkspace extends AbstractHandler {
-
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".addFolderNode";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
-
- JcrBrowserView view = (JcrBrowserView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(HandlerUtil.getActivePartId(event));
-
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
- if (!(obj instanceof RepositoryElem))
- return null;
-
- RepositoryElem repositoryNode = (RepositoryElem) obj;
- String workspaceName = SingleValue.ask("Workspace name",
- "Enter workspace name");
- if (workspaceName != null) {
- if (Arrays.asList(repositoryNode.getAccessibleWorkspaceNames())
- .contains(workspaceName)) {
- ErrorFeedback.show("Workspace " + workspaceName
- + " already exists.");
- } else {
- repositoryNode.createWorkspace(workspaceName);
- view.nodeAdded(repositoryNode);
- }
- }
- } else {
- ErrorFeedback.show("Cannot create workspace");
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.Iterator;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Delete the selected nodes: both in the JCR repository and in the UI view.
- * Warning no check is done, except implementation dependent native checks,
- * handle with care.
- *
- * This handler is still 'hard linked' to a GenericJcrBrowser view to enable
- * correct tree refresh when a node is added. This must be corrected in future
- * versions.
- */
-public class DeleteNodes extends AbstractHandler {
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
- if (selection == null || !(selection instanceof IStructuredSelection))
- return null;
-
- JcrBrowserView view = (JcrBrowserView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(HandlerUtil.getActivePartId(event));
-
- // confirmation
- StringBuffer buf = new StringBuffer("");
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();
- while (lst.hasNext()) {
- SingleJcrNodeElem sjn = ((SingleJcrNodeElem) lst.next());
- buf.append(sjn.getName()).append(' ');
- }
- Boolean doRemove = MessageDialog.openConfirm(
- HandlerUtil.getActiveShell(event), "Confirm deletion",
- "Do you want to delete " + buf + "?");
-
- // operation
- if (doRemove) {
- Iterator<?> it = ((IStructuredSelection) selection).iterator();
- Object obj = null;
- SingleJcrNodeElem ancestor = null;
- WorkspaceElem rootAncestor = null;
- try {
- while (it.hasNext()) {
- obj = it.next();
- if (obj instanceof SingleJcrNodeElem) {
- // Cache objects
- SingleJcrNodeElem sjn = (SingleJcrNodeElem) obj;
- TreeParent tp = (TreeParent) sjn.getParent();
- Node node = sjn.getNode();
-
- // Jcr Remove
- node.remove();
- node.getSession().save();
- // UI remove
- tp.removeChild(sjn);
-
- // Check if the parent is the root node
- if (tp instanceof WorkspaceElem)
- rootAncestor = (WorkspaceElem) tp;
- else
- ancestor = getOlder(ancestor, (SingleJcrNodeElem) tp);
- }
- }
- if (rootAncestor != null)
- view.nodeRemoved(rootAncestor);
- else if (ancestor != null)
- view.nodeRemoved(ancestor);
- } catch (Exception e) {
- ErrorFeedback.show("Cannot delete selected node ", e);
- }
- }
- return null;
- }
-
- private SingleJcrNodeElem getOlder(SingleJcrNodeElem A, SingleJcrNodeElem B) {
- try {
- if (A == null)
- return B == null ? null : B;
- // Todo enhanced this method
- else
- return A.getNode().getDepth() <= B.getNode().getDepth() ? A : B;
- } catch (RepositoryException re) {
- throw new EclipseUiException("Cannot find ancestor", re);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import static org.argeo.cms.ui.workbench.legacy.rap.SingleSourcingConstants.FILE_SCHEME;
-import static org.argeo.cms.ui.workbench.legacy.rap.SingleSourcingConstants.SCHEME_HOST_SEPARATOR;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.legacy.rap.OpenFile;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Canonically call JCR Session#exportSystemView() on the first element returned
- * by HandlerUtil#getActiveWorkbenchWindow()
- * (...getActivePage().getSelection()), if it is a {@link SingleJcrNodeElem},
- * with both skipBinary and noRecurse boolean flags set to false.
- *
- * Resulting stream is saved in a tmp file and opened via the {@link OpenFile}
- * single-sourced command.
- */
-public class DumpNode extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".dumpNode";
-
- private final static DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
- if (selection == null || !(selection instanceof IStructuredSelection))
- return null;
-
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();
- if (lst.hasNext()) {
- Object element = lst.next();
- if (element instanceof SingleJcrNodeElem) {
- SingleJcrNodeElem sjn = (SingleJcrNodeElem) element;
- Node node = sjn.getNode();
-
- // TODO add a dialog to configure the export and ask for
- // confirmation
- // Boolean ok = MessageDialog.openConfirm(
- // HandlerUtil.getActiveShell(event), "Confirm dump",
- // "Do you want to dump " + buf + "?");
-
- File tmpFile;
- FileOutputStream fos;
- try {
- tmpFile = File.createTempFile("JcrExport", ".xml");
- tmpFile.deleteOnExit();
- fos = new FileOutputStream(tmpFile);
- String dateVal = df.format(new GregorianCalendar().getTime());
- node.getSession().exportSystemView(node.getPath(), fos, true, false);
- openGeneratedFile(tmpFile.getAbsolutePath(),
- "Dump-" + JcrUtils.replaceInvalidChars(node.getName()) + "-" + dateVal + ".xml");
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to perform SystemExport on " + node, e);
- } catch (IOException e) {
- throw new EclipseUiException("Unable to SystemExport " + node, e);
- }
- }
- }
- return null;
- }
-
- private synchronized void openGeneratedFile(String path, String fileName) {
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenFile.PARAM_FILE_NAME, fileName);
- params.put(OpenFile.PARAM_FILE_URI, FILE_SCHEME + SCHEME_HOST_SEPARATOR + path);
- CommandUtils.callCommand(OpenFile.ID, params);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Property;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.cms.ui.workbench.internal.jcr.parts.NodeEditorInput;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Generic command to open a Node in an editor. */
-public class EditNode extends AbstractHandler {
- public final static String PARAM_EDITOR_ID = "editor";
-
- private String defaultEditorId;
-
- private Map<String, String> nodeTypeToEditor = new HashMap<String, String>();
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String path = event.getParameter(Property.JCR_PATH);
- String type = event.getParameter(NodeType.NT_NODE_TYPE);
- if (type == null)
- type = NodeType.NT_UNSTRUCTURED;
-
- String editorId = event.getParameter(PARAM_EDITOR_ID);
- if (editorId == null)
- editorId = nodeTypeToEditor.containsKey(type) ? nodeTypeToEditor
- .get(type) : defaultEditorId;
-
- NodeEditorInput nei = new NodeEditorInput(path);
- try {
- HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
- .openEditor(nei, editorId);
- } catch (PartInitException e) {
- ErrorFeedback.show("Cannot open " + editorId + " with " + path
- + " of type " + type, e);
- }
- return null;
- }
-
- public void setDefaultEditorId(String defaultEditorId) {
- this.defaultEditorId = defaultEditorId;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.jcr.Node;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Compute an approximative size for the selected node(s) */
-public class GetNodeSize extends AbstractHandler {
- // private final static CmsLog log = CmsLog.getLog(GetNodeSize.class);
-
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".getNodeSize";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
-
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
-
- long size = 0;
-
- Iterator<?> it = ((IStructuredSelection) selection).iterator();
-
- // TODO enhance this: as the size method is recursive, we keep track
- // of nodes for which we already have computed size so that we don't
- // count them twice. In a first approximation, we assume that the
- // structure selection keep the nodes ordered.
- List<String> importedPathes = new ArrayList<String>();
- try {
- nodesIt: while (it.hasNext()) {
- Object obj = it.next();
- String curPath;
- Node node;
- if (obj instanceof SingleJcrNodeElem) {
- node = ((SingleJcrNodeElem) obj).getNode();
- curPath = node.getSession().getWorkspace().getName();
- curPath += "/" + node.getPath();
- } else if (obj instanceof WorkspaceElem) {
- node = ((WorkspaceElem) obj).getRootNode();
- curPath = node.getSession().getWorkspace().getName();
- } else
- // non valid object type
- continue nodesIt;
-
- Iterator<String> itPath = importedPathes.iterator();
- while (itPath.hasNext()) {
- String refPath = itPath.next();
- if (curPath.startsWith(refPath))
- // Already done : skip node
- continue nodesIt;
- }
- size += JcrUtils.getNodeApproxSize(node);
- importedPathes.add(curPath);
- }
- } catch (Exception e) {
- ErrorFeedback.show("Cannot Get size of selected node ", e);
- }
-
- String[] labels = { "OK" };
- Shell shell = HandlerUtil.getActiveWorkbenchWindow(event)
- .getShell();
- MessageDialog md = new MessageDialog(shell, "Node size", null,
- "Node size is: " + size / 1024 + " KB",
- MessageDialog.INFORMATION, labels, 0);
- md.open();
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.Iterator;
-
-import org.argeo.cms.ui.jcr.JcrBrowserUtils;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-
-/**
- * Force the selected objects of the active view to be refreshed doing the
- * following:
- * <ol>
- * <li>The model objects are recomputed</li>
- * <li>the view is refreshed</li>
- * </ol>
- */
-public class Refresh extends AbstractHandler {
-
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".refresh";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- JcrBrowserView view = (JcrBrowserView) WorkbenchUiPlugin.getDefault()
- .getWorkbench().getActiveWorkbenchWindow().getActivePage()
- .getActivePart();//
-
- ISelection selection = WorkbenchUiPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getSelection();
-
- if (selection != null && selection instanceof IStructuredSelection
- && !selection.isEmpty()) {
- Iterator<?> it = ((IStructuredSelection) selection).iterator();
- while (it.hasNext()) {
- Object obj = it.next();
- if (obj instanceof TreeParent) {
- TreeParent tp = (TreeParent) obj;
- JcrBrowserUtils.forceRefreshIfNeeded(tp);
- view.refresh(obj);
- }
- }
- } else if (view instanceof JcrBrowserView)
- ((JcrBrowserView) view).refresh(null); // force full refresh
-
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.security.Principal;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.security.AccessControlEntry;
-import javax.jcr.security.AccessControlList;
-import javax.jcr.security.AccessControlManager;
-import javax.jcr.security.Privilege;
-
-import org.argeo.cms.ui.jcr.JcrImages;
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Open a dialog to remove privileges from the selected node */
-public class RemovePrivileges extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".removePrivileges";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
- TreeParent uiNode = null;
- Node jcrNode = null;
-
- if (obj instanceof SingleJcrNodeElem) {
- uiNode = (TreeParent) obj;
- jcrNode = ((SingleJcrNodeElem) uiNode).getNode();
- } else if (obj instanceof WorkspaceElem) {
- uiNode = (TreeParent) obj;
- jcrNode = ((WorkspaceElem) uiNode).getRootNode();
- } else
- return null;
-
- try {
- String targetPath = jcrNode.getPath();
- Dialog dialog = new RemovePrivDialog(
- HandlerUtil.getActiveShell(event),
- jcrNode.getSession(), targetPath);
- dialog.open();
- return null;
- } catch (RepositoryException re) {
- throw new EclipseUiException("Unable to retrieve "
- + "path or JCR session to add privilege on " + jcrNode,
- re);
- }
- } else {
- ErrorFeedback.show("Cannot add privileges");
- }
- return null;
- }
-
- private class RemovePrivDialog extends TitleAreaDialog {
- private static final long serialVersionUID = 280139710002698692L;
-
- private Composite body;
-
- private final String path;
- private final Session session;
-
- public RemovePrivDialog(Shell parentShell, Session session, String path) {
- super(parentShell);
- this.session = session;
- this.path = path;
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Remove privileges");
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true,
- true));
- body = new Composite(dialogarea, SWT.NONE);
- body.setLayoutData(EclipseUiUtils.fillAll());
- refreshContent();
- parent.pack();
- return body;
- }
-
- private void refreshContent() {
- EclipseUiUtils.clear(body);
- try {
- AccessControlManager acm = session.getAccessControlManager();
- AccessControlList acl = JcrUtils
- .getAccessControlList(acm, path);
- if (acl == null || acl.getAccessControlEntries().length <= 0)
- setMessage("No privilege are defined on this node",
- IMessageProvider.INFORMATION);
- else {
- body.setLayout(new GridLayout(3, false));
- for (AccessControlEntry ace : acl.getAccessControlEntries()) {
- addOnePrivRow(body, ace);
- }
- setMessage("Remove some of the defined privileges",
- IMessageProvider.INFORMATION);
- }
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to list privileges on "
- + path, e);
- }
- body.layout(true, true);
- }
-
- private void addOnePrivRow(Composite parent, AccessControlEntry ace) {
- Principal currentPrincipal = ace.getPrincipal();
- final String currPrincipalName = currentPrincipal.getName();
- new Label(parent, SWT.WRAP).setText(currPrincipalName);
- new Label(parent, SWT.WRAP).setText(privAsString(ace
- .getPrivileges()));
- final Button rmBtn = new Button(parent, SWT.FLAT);
- rmBtn.setImage(JcrImages.REMOVE);
-
- rmBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = 7566938841363890730L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
-
- if (MessageDialog.openConfirm(rmBtn.getShell(),
- "Confirm deletion",
- "Are you sure you want to remove this privilege?")) {
- try {
- session.save();
- JcrUtils.clearAccessControList(session, path,
- currPrincipalName);
- session.save();
- refreshContent();
- } catch (RepositoryException re) {
- throw new EclipseUiException("Unable to "
- + "remove privilege for "
- + currPrincipalName + " on " + path, re);
- }
- }
-
- super.widgetSelected(e);
- }
- });
-
- }
-
- private String privAsString(Privilege[] currentPrivileges) {
-
- StringBuilder builder = new StringBuilder();
- builder.append("[ ");
- for (Privilege priv : currentPrivileges) {
- builder.append(priv.getName()).append(", ");
- }
- if (builder.length() > 3)
- return builder.substring(0, builder.length() - 2) + " ]";
- else
- return "[]";
-
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import org.argeo.cms.ui.jcr.model.RemoteRepositoryElem;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Remove a registered remote repository */
-public class RemoveRemoteRepository extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getSelection();
-
- JcrBrowserView view = (JcrBrowserView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(HandlerUtil.getActivePartId(event));
-
- if (selection != null && !selection.isEmpty()
- && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
-
- if (obj instanceof RemoteRepositoryElem) {
- ((RemoteRepositoryElem) obj).remove();
- view.refresh(null);
- }
- }
- return null;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.util.Iterator;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Canonically call JCR Session#move(String, String) on the first element
- * returned by HandlerUtil#getActiveWorkbenchWindow()
- * (...getActivePage().getSelection()), if it is a {@link SingleJcrNodeElem}.
- * The user must then fill a new name in and confirm
- */
-public class RenameNode extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".renameNode";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchPage iwp = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
-
- ISelection selection = iwp.getSelection();
- if (selection == null || !(selection instanceof IStructuredSelection))
- return null;
-
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();
- if (lst.hasNext()) {
- Object element = lst.next();
- if (element instanceof SingleJcrNodeElem) {
- SingleJcrNodeElem sjn = (SingleJcrNodeElem) element;
- Node node = sjn.getNode();
- Session session = null;
- String newName = null;
- String oldPath = null;
- try {
- newName = SingleValue.ask("New node name",
- "Please provide a new name for [" + node.getName() + "]");
- // TODO sanity check and user feedback
- newName = JcrUtils.replaceInvalidChars(newName);
- oldPath = node.getPath();
- session = node.getSession();
- session.move(oldPath, JcrUtils.parentPath(oldPath) + "/" + newName);
- session.save();
-
- // Manually refresh the browser view. Must be enhanced
- if (iwp.getActivePart() instanceof JcrBrowserView)
- ((JcrBrowserView) iwp.getActivePart()).refresh(sjn);
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to rename " + node + " to " + newName, e);
- }
- }
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.State;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Change isSorted state of the DataExplorer Browser */
-public class SortChildNodes extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".sortChildNodes";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- JcrBrowserView view = (JcrBrowserView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(JcrBrowserView.ID);
-
- ICommandService service = (ICommandService) PlatformUI.getWorkbench()
- .getService(ICommandService.class);
- Command command = service.getCommand(ID);
- State state = command.getState(ID + ".toggleState");
-
- boolean wasSorted = (Boolean) state.getValue();
- view.setSortChildNodes(!wasSorted);
- state.setValue(!wasSorted);
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.commands;
-
-import java.io.InputStream;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.jcr.model.WorkspaceElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.JcrBrowserView;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Upload local file(s) under the currently selected node */
-public class UploadFiles extends AbstractHandler {
- // private final static CmsLog log = CmsLog.getLog(ImportFileSystem.class);
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
- JcrBrowserView view = (JcrBrowserView) HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
- .findView(HandlerUtil.getActivePartId(event));
- if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection) selection).getFirstElement();
- try {
- Node folder = null;
- if (obj instanceof SingleJcrNodeElem) {
- folder = ((SingleJcrNodeElem) obj).getNode();
- } else if (obj instanceof WorkspaceElem) {
- folder = ((WorkspaceElem) obj).getRootNode();
- } else {
- ErrorFeedback.show(WorkbenchUiPlugin.getMessage("warningInvalidNodeToImport"));
- }
- if (folder != null) {
- FileDialog dialog = new FileDialog(HandlerUtil.getActiveShell(event), SWT.MULTI);
- dialog.setText("Choose one or more files to upload");
-
- if (EclipseUiUtils.notEmpty(dialog.open())) {
- String[] names = dialog.getFileNames();
- // Workaround small differences between RAP and RCP
- // 1. returned names are absolute path on RAP and
- // relative in RCP
- // 2. in RCP we must use getFilterPath that does not
- // exists on RAP
- Method filterMethod = null;
- Path parPath = null;
-
- try {
- filterMethod = dialog.getClass().getDeclaredMethod("getFilterPath");
- String filterPath = (String) filterMethod.invoke(dialog);
- parPath = Paths.get(filterPath);
- } catch (NoSuchMethodException nsme) { // RAP
- }
- if (names.length == 0)
- return null;
- else {
- loop: for (String name : names) {
- Path path = Paths.get(name);
- if (parPath != null)
- path = parPath.resolve(path);
- if (Files.exists(path)) {
- URI uri = path.toUri();
- String uriStr = uri.toString();
- System.out.println(uriStr);
-
- if (Files.isDirectory(path)) {
- MessageDialog.openError(HandlerUtil.getActiveShell(event),
- "Unimplemented directory import",
- "Upload of directories in the system is not yet implemented");
- continue loop;
- }
- Node fileNode = folder.addNode(path.getFileName().toString(), NodeType.NT_FILE);
- Node resNode = fileNode.addNode(Property.JCR_CONTENT, NodeType.NT_RESOURCE);
- Binary binary = null;
- try (InputStream is = Files.newInputStream(path)) {
- binary = folder.getSession().getValueFactory().createBinary(is);
- resNode.setProperty(Property.JCR_DATA, binary);
- }
- folder.getSession().save();
- } else {
- String msg = "Cannot upload file at " + path.toString();
- if (parPath != null)
- msg += "\nPlease remember that file upload fails when choosing files from the \"Recently Used\" bookmarks on some OS";
- MessageDialog.openError(HandlerUtil.getActiveShell(event), "Missing file", msg);
- continue loop;
- }
- }
- view.nodeAdded((TreeParent) obj);
- return true;
- }
- }
- }
- } catch (Exception e) {
- ErrorFeedback.show("Cannot import files to " + obj, e);
- }
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.Row;
-import javax.jcr.query.RowIterator;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.EditorPart;
-
-/** Executes any JCR query. */
-public abstract class AbstractJcrQueryEditor extends EditorPart {
- private final static CmsLog log = CmsLog.getLog(AbstractJcrQueryEditor.class);
-
- protected String initialQuery;
- protected String initialQueryType;
-
- /* DEPENDENCY INJECTION */
- private Session session;
-
- // Widgets
- private TableViewer viewer;
- private List<TableViewerColumn> tableViewerColumns = new ArrayList<TableViewerColumn>();
- private GenericTableComparator comparator;
-
- /** Override to layout a form enabling the end user to build his query */
- protected abstract void createQueryForm(Composite parent);
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- JcrQueryEditorInput editorInput = (JcrQueryEditorInput) input;
- initialQuery = editorInput.getQuery();
- initialQueryType = editorInput.getQueryType();
- setSite(site);
- setInput(editorInput);
- }
-
- @Override
- public final void createPartControl(final Composite parent) {
- parent.setLayout(new FillLayout());
-
- SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- sashForm.setLayout(new FillLayout());
-
- Composite top = new Composite(sashForm, SWT.NONE);
- GridLayout gl = new GridLayout(1, false);
- top.setLayout(gl);
-
- createQueryForm(top);
-
- Composite bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
- sashForm.setWeights(getWeights());
-
- viewer = new TableViewer(bottom);
- viewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- viewer.getTable().setHeaderVisible(true);
- viewer.setContentProvider(getQueryResultContentProvider());
- viewer.setInput(getEditorSite());
-
- if (getComparator() != null) {
- comparator = getComparator();
- viewer.setComparator(comparator);
- }
- if (getTableDoubleClickListener() != null)
- viewer.addDoubleClickListener(getTableDoubleClickListener());
-
- }
-
- protected void executeQuery(String statement) {
- try {
- if (log.isDebugEnabled())
- log.debug("Query : " + statement);
-
- QueryResult qr = session.getWorkspace().getQueryManager().createQuery(statement, initialQueryType)
- .execute();
-
- // remove previous columns
- for (TableViewerColumn tvc : tableViewerColumns)
- tvc.getColumn().dispose();
-
- int i = 0;
- for (final String columnName : qr.getColumnNames()) {
- TableViewerColumn tvc = new TableViewerColumn(viewer, SWT.NONE);
- configureColumn(columnName, tvc, i);
- tvc.setLabelProvider(getLabelProvider(columnName));
- tableViewerColumns.add(tvc);
- i++;
- }
-
- // Must create a local list: QueryResults can only be read once.
- try {
- List<Row> rows = new ArrayList<Row>();
- RowIterator rit = qr.getRows();
- while (rit.hasNext()) {
- rows.add(rit.nextRow());
- }
- viewer.setInput(rows);
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot read query result", e);
- }
-
- } catch (RepositoryException e) {
- ErrorDialog.openError(null, "Error", "Cannot execute JCR query: " + statement,
- new Status(IStatus.ERROR, "org.argeo.eclipse.ui.jcr", e.getMessage()));
- }
- }
-
- /**
- * To be overidden to adapt size of form and result frames.
- *
- * @return
- */
- protected int[] getWeights() {
- return new int[] { 30, 70 };
- }
-
- /**
- * To be overidden to implement a doubleclick Listener on one of the rows of
- * the table.
- *
- * @return
- */
- protected IDoubleClickListener getTableDoubleClickListener() {
- return null;
- }
-
- /**
- * To be overiden in order to implement a specific
- * QueryResultContentProvider
- */
- protected IStructuredContentProvider getQueryResultContentProvider() {
- return new QueryResultContentProvider();
- }
-
- /**
- * Enable specific implementation for columns
- */
- protected List<TableViewerColumn> getTableViewerColumns() {
- return tableViewerColumns;
- }
-
- /**
- * Enable specific implementation for columns
- */
- protected TableViewer getTableViewer() {
- return viewer;
- }
-
- /**
- * To be overridden in order to configure column label providers .
- */
- protected ColumnLabelProvider getLabelProvider(final String columnName) {
- return new ColumnLabelProvider() {
- private static final long serialVersionUID = -3539689333250152606L;
-
- public String getText(Object element) {
- Row row = (Row) element;
- try {
- return row.getValue(columnName).getString();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot display row " + row, e);
- }
- }
-
- public Image getImage(Object element) {
- return null;
- }
- };
- }
-
- /**
- * To be overridden in order to configure the columns.
- *
- * @deprecated use
- * {@link AbstractJcrQueryEditor#configureColumn(String, TableViewerColumn , int )}
- * instead
- */
- protected void configureColumn(String jcrColumnName, TableViewerColumn column) {
- column.getColumn().setWidth(50);
- column.getColumn().setText(jcrColumnName);
- }
-
- /** To be overridden in order to configure the columns. */
- protected void configureColumn(String jcrColumnName, TableViewerColumn column, int columnIndex) {
- column.getColumn().setWidth(50);
- column.getColumn().setText(jcrColumnName);
- }
-
- private class QueryResultContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -5421095459600554741L;
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public Object[] getElements(Object inputElement) {
-
- if (inputElement instanceof List)
- return ((List<?>) inputElement).toArray();
-
- // Never reached might be deleted in future release
- if (!(inputElement instanceof QueryResult))
- return new String[] {};
-
- try {
- QueryResult queryResult = (QueryResult) inputElement;
- List<Row> rows = new ArrayList<Row>();
- RowIterator rit = queryResult.getRows();
- while (rit.hasNext()) {
- rows.add(rit.nextRow());
- }
-
- // List<Node> elems = new ArrayList<Node>();
- // NodeIterator nit = queryResult.getNodes();
- // while (nit.hasNext()) {
- // elems.add(nit.nextNode());
- // }
- return rows.toArray();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot read query result", e);
- }
- }
-
- }
-
- /**
- * Might be used by children classes to sort columns.
- *
- * @param column
- * @param index
- * @return
- */
- protected SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) {
-
- // A comparator must be define
- if (comparator == null)
- return null;
-
- SelectionAdapter selectionAdapter = new SelectionAdapter() {
- private static final long serialVersionUID = 239829307927778349L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
-
- try {
-
- comparator.setColumn(index);
- int dir = viewer.getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column) {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- } else {
-
- dir = SWT.DOWN;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- } catch (Exception exc) {
- exc.printStackTrace();
- }
- }
- };
- return selectionAdapter;
- }
-
- /**
- * To be overridden to enable sorting.
- */
- protected GenericTableComparator getComparator() {
- return null;
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- // TODO save the query in JCR?
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- /** Returns the injected current session */
- protected Session getSession() {
- return session;
- }
-
- /* DEPENDENCY INJECTION */
- public void setSession(Session session) {
- this.session = session;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.security.Privilege;
-
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.cms.swt.useradmin.PickUpUserDialog;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Text;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-
-/** Add JCR privileges to the chosen user group on a given node */
-public class AddPrivilegeWizard extends Wizard {
-
- // Context
- private UserAdmin userAdmin;
- private Session currentSession;
- private String targetPath;
- // Chosen parameters
- private String chosenDn;
- private User chosenUser;
- private String jcrPrivilege;
-
- // UI Object
- private DefinePrivilegePage page;
-
- // TODO enable external definition of possible values and corresponding
- // description
- protected static final Map<String, String> AUTH_TYPE_LABELS;
- static {
- Map<String, String> tmpMap = new HashMap<String, String>();
- tmpMap.put(Privilege.JCR_READ, "jcr:read");
- tmpMap.put(Privilege.JCR_WRITE, "jcr:write");
- tmpMap.put(Privilege.JCR_ALL, "jcr:all");
- AUTH_TYPE_LABELS = Collections.unmodifiableMap(tmpMap);
- }
-
- protected static final Map<String, String> AUTH_TYPE_DESC;
- static {
- Map<String, String> tmpMap = new HashMap<String, String>();
- tmpMap.put(Privilege.JCR_READ, "The privilege to retrieve a node and get its properties and their values.");
- tmpMap.put(Privilege.JCR_WRITE, "An aggregate privilege that "
- + "contains: jcr:modifyProperties, jcr:addChildNodes, " + "jcr:removeNode, jcr:removeChildNodes");
- tmpMap.put(Privilege.JCR_ALL, "An aggregate privilege that " + "contains all JCR predefined privileges, "
- + "plus all implementation-defined privileges. ");
- AUTH_TYPE_DESC = Collections.unmodifiableMap(tmpMap);
- }
-
- public AddPrivilegeWizard(Session currentSession, String path, UserAdmin userAdmin) {
- super();
- this.userAdmin = userAdmin;
- this.currentSession = currentSession;
- this.targetPath = path;
- }
-
- @Override
- public void addPages() {
- try {
- setWindowTitle("Add privilege on " + targetPath);
- page = new DefinePrivilegePage(userAdmin, targetPath);
- addPage(page);
- } catch (Exception e) {
- throw new EclipseUiException("Cannot add page to wizard ", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- try {
- String username = chosenUser.getName();
- if (EclipseUiUtils.notEmpty(chosenDn) && chosenDn.equalsIgnoreCase(username))
- // Enable forcing the username case. TODO clean once this issue
- // has been generally addressed
- username = chosenDn;
- JcrUtils.addPrivilege(currentSession, targetPath, username, jcrPrivilege);
- } catch (RepositoryException re) {
- throw new EclipseUiException(
- "Cannot set " + jcrPrivilege + " for " + chosenUser.getName() + " on " + targetPath, re);
- }
- return true;
- }
-
- private class DefinePrivilegePage extends WizardPage implements ModifyListener {
- private static final long serialVersionUID = 8084431378762283920L;
-
- // Context
- final private UserAdmin userAdmin;
-
- public DefinePrivilegePage(UserAdmin userAdmin, String path) {
- super("Main");
- this.userAdmin = userAdmin;
- setTitle("Define the privilege to apply to " + path);
- setMessage("Please choose a user or a group and relevant JCR Privilege.");
- }
-
- public void createControl(Composite parent) {
- final Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(3, false));
-
- // specify subject
- createBoldLabel(composite, "User or group name");
- final Label userNameLbl = new Label(composite, SWT.LEAD);
- userNameLbl.setLayoutData(EclipseUiUtils.fillWidth());
-
- Link pickUpLk = new Link(composite, SWT.LEFT);
- pickUpLk.setText(" <a>Change</a> ");
-
- createBoldLabel(composite, "User or group DN");
- final Text userNameTxt = new Text(composite, SWT.LEAD | SWT.BORDER);
- userNameTxt.setLayoutData(EclipseUiUtils.fillWidth(2));
-
- pickUpLk.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- PickUpUserDialog dialog = new PickUpUserDialog(getShell(), "Choose a group or a user", userAdmin);
- if (dialog.open() == Window.OK) {
- chosenUser = dialog.getSelected();
- userNameLbl.setText(UserAdminUtils.getCommonName(chosenUser));
- userNameTxt.setText(chosenUser.getName());
- }
- }
- });
-
- userNameTxt.addFocusListener(new FocusListener() {
- private static final long serialVersionUID = 1965498600105667738L;
-
- @Override
- public void focusLost(FocusEvent event) {
- String dn = userNameTxt.getText();
- if (EclipseUiUtils.isEmpty(dn))
- return;
-
- User newChosen = null;
- try {
- newChosen = (User) userAdmin.getRole(dn);
- } catch (Exception e) {
- boolean tryAgain = MessageDialog.openQuestion(getShell(), "Unvalid DN",
- "DN " + dn + " is not valid.\nError message: " + e.getMessage()
- + "\n\t\tDo you want to try again?");
- if (tryAgain)
- userNameTxt.setFocus();
- else
- resetOnFail();
- }
-
- if (userAdmin.getRole(dn) == null) {
- boolean tryAgain = MessageDialog.openQuestion(getShell(), "Unexisting role",
- "User/group " + dn + " does not exist. " + "Do you want to try again?");
- if (tryAgain)
- userNameTxt.setFocus();
- else
- resetOnFail();
- } else {
- chosenUser = newChosen;
- chosenDn = dn;
- userNameLbl.setText(UserAdminUtils.getCommonName(chosenUser));
- }
- }
-
- private void resetOnFail() {
- String oldDn = chosenUser == null ? "" : chosenUser.getName();
- userNameTxt.setText(oldDn);
- }
-
- @Override
- public void focusGained(FocusEvent event) {
- }
- });
-
- // JCR Privileges
- createBoldLabel(composite, "Privilege type");
- Combo authorizationCmb = new Combo(composite, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL);
- authorizationCmb.setItems(AUTH_TYPE_LABELS.values().toArray(new String[0]));
- authorizationCmb.setLayoutData(EclipseUiUtils.fillWidth(2));
- createBoldLabel(composite, ""); // empty cell
- final Label descLbl = new Label(composite, SWT.WRAP);
- descLbl.setLayoutData(EclipseUiUtils.fillWidth(2));
-
- authorizationCmb.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- String chosenPrivStr = ((Combo) e.getSource()).getText();
- if (AUTH_TYPE_LABELS.containsValue(chosenPrivStr)) {
- loop: for (String key : AUTH_TYPE_LABELS.keySet()) {
- if (AUTH_TYPE_LABELS.get(key).equals(chosenPrivStr)) {
- jcrPrivilege = key;
- break loop;
- }
- }
- }
-
- if (jcrPrivilege != null) {
- descLbl.setText(AUTH_TYPE_DESC.get(jcrPrivilege));
- composite.layout(true, true);
- }
- }
- });
-
- // Compulsory
- setControl(composite);
- }
-
- public void modifyText(ModifyEvent event) {
- String message = checkComplete();
- if (message != null)
- setMessage(message, WizardPage.ERROR);
- else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- }
-
- /** @return error message or null if complete */
- protected String checkComplete() {
- if (chosenUser == null)
- return "Please choose a relevant group or user";
- else if (userAdmin.getRole(chosenUser.getName()) == null)
- return "Please choose a relevant group or user";
- else if (jcrPrivilege == null)
- return "Please choose a relevant JCR privilege";
- return null;
- }
- }
-
- private Label createBoldLabel(Composite parent, String value) {
- Label label = new Label(parent, SWT.RIGHT);
- label.setText(" " + value);
- label.setFont(EclipseUiUtils.getBoldFont(parent));
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- return label;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import javax.jcr.Node;
-
-import org.argeo.cms.ui.jcr.JcrTreeContentProvider;
-import org.argeo.cms.ui.jcr.NodeLabelProvider;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.jcr.DefaultNodeEditor;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/** List all children of the current node */
-public class ChildNodesPage extends FormPage {
- // private final static CmsLog log = CmsLog.getLog(ChildNodesPage.class);
-
- private Node currentNode;
-
- private JcrTreeContentProvider nodeContentProvider;
- private TreeViewer nodesViewer;
-
- public ChildNodesPage(FormEditor editor, String title, Node currentNode) {
- super(editor, "ChildNodesPage", title);
- this.currentNode = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- try {
- ScrolledForm form = managedForm.getForm();
- form.setText(WorkbenchUiPlugin.getMessage("childNodesPageTitle"));
- Composite innerBox = form.getBody();
- // Composite innerBox = new Composite(body, SWT.NO_FOCUS);
- GridLayout twt = new GridLayout(1, false);
- twt.marginWidth = twt.marginHeight = 5;
- innerBox.setLayout(twt);
- if (!currentNode.hasNodes()) {
- managedForm.getToolkit().createLabel(innerBox, WorkbenchUiPlugin.getMessage("warningNoChildNode"));
- } else {
- nodeContentProvider = new JcrTreeContentProvider();
- nodesViewer = createNodeViewer(innerBox, nodeContentProvider);
- nodesViewer.setInput(currentNode);
- }
- } catch (Exception e) {
- throw new EclipseUiException("Cannot create children page for " + currentNode, e);
- }
- }
-
- protected TreeViewer createNodeViewer(Composite parent, final ITreeContentProvider nodeContentProvider) {
-
- final TreeViewer tmpNodeViewer = new TreeViewer(parent, SWT.BORDER);
- Tree tree = tmpNodeViewer.getTree();
- tree.setLinesVisible(true);
- tmpNodeViewer.getTree().setLayoutData(EclipseUiUtils.fillAll());
- tmpNodeViewer.setContentProvider(nodeContentProvider);
- tmpNodeViewer.setLabelProvider(new NodeLabelProvider());
- tmpNodeViewer.addDoubleClickListener(new DClickListener());
- return tmpNodeViewer;
- }
-
- public class DClickListener implements IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- if (event.getSelection() == null || event.getSelection().isEmpty())
- return;
- Object obj = ((IStructuredSelection) event.getSelection()).getFirstElement();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- try {
- GenericNodeEditorInput gnei = new GenericNodeEditorInput(node);
- WorkbenchUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage()
- .openEditor(gnei, DefaultNodeEditor.ID);
- } catch (PartInitException pie) {
- throw new EclipseUiException("Cannot open editor for " + node, pie);
- }
- }
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-/** Ask end user for a name */
-public class ChooseNameDialog extends TitleAreaDialog {
- private static final long serialVersionUID = 280139710002698692L;
- private Text nameTxt;
-
- public ChooseNameDialog(Shell parentShell) {
- super(parentShell);
- setTitle("Choose name");
- }
-
- protected Point getInitialSize() {
- return new Point(300, 250);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- nameTxt = createLT(composite, "Name");
- setMessage("Choose name", IMessageProvider.INFORMATION);
- parent.pack();
- nameTxt.setFocus();
- return composite;
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- return text;
- }
-
- public String getName() {
- return nameTxt.getText();
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/** Editor input for {@link Node} editors */
-public class GenericNodeEditorInput implements IEditorInput {
- private final Node currentNode;
-
- // Caches key properties at creation time to avoid Exception at recovering
- // time when the session has been closed
- private String path;
- private String uid;
- private String name;
-
- public GenericNodeEditorInput(Node currentNode) {
- this.currentNode = currentNode;
- try {
- name = currentNode.getName();
- uid = currentNode.getIdentifier();
- path = currentNode.getPath();
- } catch (RepositoryException re) {
- throw new EclipseUiException("Cannot cache the key properties for " + currentNode, re);
- }
- }
-
- public Node getCurrentNode() {
- return currentNode;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return name;
- }
-
- public String getUid() {
- return uid;
- }
-
- public String getToolTipText() {
- return path;
- }
-
- public String getPath() {
- return path;
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- /**
- * Equals method based on UID that is unique within a workspace and path of
- * the node, thus 2 shared node that have same UID as defined in the spec
- * but 2 different paths will open two distinct editors.
- *
- * TODO enhance this method to support multi repository and multi workspace
- * environments
- */
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
-
- GenericNodeEditorInput other = (GenericNodeEditorInput) obj;
- if (!getUid().equals(other.getUid()))
- return false;
- if (!getPath().equals(other.getPath()))
- return false;
- return true;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.ListIterator;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.CmsUiConstants;
-import org.argeo.cms.ui.workbench.internal.WorkbenchConstants;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Work-In-Progress Node editor page: provides edition feature on String
- * properties for power users. TODO implement manual modification of all
- * property types.
- */
-
-public class GenericNodePage extends FormPage implements WorkbenchConstants {
- // private final static CmsLog log = CmsLog.getLog(GenericNodePage.class);
-
- // local constants
- private final static String JCR_PROPERTY_NAME = "jcr:name";
-
- // Utils
- protected DateFormat timeFormatter = new SimpleDateFormat(CmsUiConstants.DATE_TIME_FORMAT);
-
- // Main business Objects
- private Node currentNode;
-
- // This page widgets
- private FormToolkit tk;
- private List<Control> modifyableProperties = new ArrayList<Control>();
-
- public GenericNodePage(FormEditor editor, String title, Node currentNode) {
- super(editor, "id", title);
- this.currentNode = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- tk = managedForm.getToolkit();
- ScrolledForm form = managedForm.getForm();
- Composite innerBox = form.getBody();
- // Composite innerBox = new Composite(form.getBody(), SWT.NO_FOCUS);
- GridLayout twt = new GridLayout(3, false);
- innerBox.setLayout(twt);
- createPropertiesPart(innerBox);
- }
-
- private void createPropertiesPart(Composite parent) {
- try {
- AbstractFormPart part = new AbstractFormPart() {
- public void commit(boolean onSave) {
- try {
- if (onSave) {
- ListIterator<Control> it = modifyableProperties.listIterator();
- while (it.hasNext()) {
- // we only support Text controls
- Text curControl = (Text) it.next();
- String value = curControl.getText();
- currentNode.setProperty((String) curControl.getData(JCR_PROPERTY_NAME), value);
- }
-
- // We only commit when onSave = true,
- // thus it is still possible to save after a tab
- // change.
- if (currentNode.getSession().hasPendingChanges())
- currentNode.getSession().save();
- super.commit(onSave);
- }
- } catch (RepositoryException re) {
- throw new EclipseUiException("Cannot save properties on " + currentNode, re);
- }
- }
- };
-
- PropertyIterator pi = currentNode.getProperties();
- while (pi.hasNext()) {
- Property prop = pi.nextProperty();
- addPropertyLine(parent, part, prop);
- }
- getManagedForm().addPart(part);
- } catch (RepositoryException re) {
- throw new EclipseUiException("Cannot display properties for " + currentNode, re);
- }
- }
-
- private void addPropertyLine(Composite parent, AbstractFormPart part, Property prop) {
- try {
- tk.createLabel(parent, prop.getName());
- tk.createLabel(parent, "[" + JcrUtils.getPropertyDefinitionAsString(prop) + "]");
-
- if (prop.getDefinition().isProtected()) {
- tk.createLabel(parent, formatReadOnlyPropertyValue(prop));
- } else
- addModifyableValueWidget(parent, part, prop);
- } catch (RepositoryException re) {
- throw new EclipseUiException("Cannot display property " + prop, re);
- }
- }
-
- private String formatReadOnlyPropertyValue(Property prop) throws RepositoryException {
- String strValue;
- if (prop.getType() == PropertyType.BINARY)
- strValue = "<binary>";
- else if (prop.isMultiple())
- strValue = Arrays.asList(prop.getValues()).toString();
- else if (prop.getType() == PropertyType.DATE)
- strValue = timeFormatter.format(prop.getValue().getDate().getTime());
- else
- strValue = prop.getValue().getString();
- return strValue;
- }
-
- private Control addModifyableValueWidget(Composite parent, AbstractFormPart part, Property prop)
- throws RepositoryException {
- GridData gd;
- if (prop.getType() == PropertyType.STRING && !prop.isMultiple()) {
- Text txt = tk.createText(parent, prop.getString(), SWT.WRAP | SWT.MULTI);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- txt.setLayoutData(gd);
- txt.addModifyListener(new ModifiedFieldListener(part));
- txt.setData(JCR_PROPERTY_NAME, prop.getName());
- modifyableProperties.add(txt);
- } else {
- // unsupported property type for editing, we create a read only
- // label.
- return tk.createLabel(parent, formatReadOnlyPropertyValue(prop));
- }
- return null;
- }
-
- private class ModifiedFieldListener implements ModifyListener {
- private static final long serialVersionUID = 2117484480773434646L;
- private AbstractFormPart formPart;
-
- public ModifiedFieldListener(AbstractFormPart generalPart) {
- this.formPart = generalPart;
- }
-
- public void modifyText(ModifyEvent e) {
- formPart.markDirty();
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.jcr.PropertyLabelProvider;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.WorkbenchConstants;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Generic editor property page. Lists all properties of current node as a
- * complex tree. TODO: enable editing
- */
-public class GenericPropertyPage extends FormPage implements WorkbenchConstants {
- // private final static Log log =
- // LogFactory.getLog(GenericPropertyPage.class);
-
- // Main business Objects
- private Node currentNode;
-
- public GenericPropertyPage(FormEditor editor, String title, Node currentNode) {
- super(editor, "id", title);
- this.currentNode = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- form.setText(WorkbenchUiPlugin.getMessage("genericNodePageTitle"));
- Composite innerBox = form.getBody();
- //Composite innerBox = new Composite(body, SWT.NO_FOCUS);
- FillLayout layout = new FillLayout();
- layout.marginHeight = 5;
- layout.marginWidth = 5;
- innerBox.setLayout(layout);
- createComplexTree(innerBox);
- // TODO TreeColumnLayout triggers a scroll issue with the form:
- // The inside body is always to big and a scroll bar is shown
- // Composite tableCmp = new Composite(body, SWT.NO_FOCUS);
- // createComplexTree(tableCmp);
- }
-
- private TreeViewer createComplexTree(Composite parent) {
- int style = SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION;
- Tree tree = new Tree(parent, style);
- TreeColumnLayout tableColumnLayout = new TreeColumnLayout();
-
- createColumn(tree, tableColumnLayout, "Property", SWT.LEFT, 200, 30);
- createColumn(tree, tableColumnLayout, "Value(s)", SWT.LEFT, 300, 60);
- createColumn(tree, tableColumnLayout, "Type", SWT.LEFT, 75, 10);
- createColumn(tree, tableColumnLayout, "Attributes", SWT.LEFT, 75, 0);
- // Do not apply the treeColumnLayout it does not work yet
- // parent.setLayout(tableColumnLayout);
-
- tree.setLinesVisible(true);
- tree.setHeaderVisible(true);
-
- TreeViewer treeViewer = new TreeViewer(tree);
- treeViewer.setContentProvider(new TreeContentProvider());
- treeViewer.setLabelProvider(new PropertyLabelProvider());
- treeViewer.setInput(currentNode);
- treeViewer.expandAll();
- return treeViewer;
- }
-
- private static TreeColumn createColumn(Tree parent, TreeColumnLayout tableColumnLayout, String name, int style,
- int width, int weight) {
- TreeColumn column = new TreeColumn(parent, style);
- column.setText(name);
- column.setWidth(width);
- column.setMoveable(true);
- column.setResizable(true);
- tableColumnLayout.setColumnData(column, new ColumnWeightData(weight, width, true));
- return column;
- }
-
- private class TreeContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = -6162736530019406214L;
-
- public Object[] getElements(Object parent) {
- Object[] props = null;
- try {
-
- if (parent instanceof Node) {
- Node node = (Node) parent;
- PropertyIterator pi;
- pi = node.getProperties();
- List<Property> propList = new ArrayList<Property>();
- while (pi.hasNext()) {
- propList.add(pi.nextProperty());
- }
- props = propList.toArray();
- }
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unexpected exception while listing node properties", e);
- }
- return props;
- }
-
- public Object getParent(Object child) {
- return null;
- }
-
- public Object[] getChildren(Object parent) {
- if (parent instanceof Property) {
- Property prop = (Property) parent;
- try {
- if (prop.isMultiple())
- return prop.getValues();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot get multi-prop values on " + prop, e);
- }
- }
- return null;
- }
-
- public boolean hasChildren(Object parent) {
- try {
- return (parent instanceof Property && ((Property) parent).isMultiple());
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot check if property is multiple for " + parent, e);
- }
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public void dispose() {
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import javax.jcr.query.Query;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-public class JcrQueryEditorInput implements IEditorInput {
- private final String query;
- private final String queryType;
-
- public JcrQueryEditorInput(String query, String queryType) {
- this.query = query;
- if (queryType == null)
- this.queryType = Query.JCR_SQL2;
- else
- this.queryType = queryType;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return query;
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return query;
- }
-
- public String getQuery() {
- return query;
- }
-
- public String getQueryType() {
- return queryType;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/**
- * A canonical editor input based on a path to a node. In a multirepository
- * environment, path can be enriched with Repository Alias and workspace
- */
-
-public class NodeEditorInput implements IEditorInput {
- private final String path;
-
- public NodeEditorInput(String path) {
- this.path = path;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return path;
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return path;
- }
-
- public String getPath() {
- return path;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Display and edit a given node privilege. For the time being it is completely
- * JackRabbit specific (and hard coded for this) and will display an empty page
- * if using any other implementation
- */
-public class NodePrivilegesPage extends FormPage {
-
- private Node context;
-
- private TableViewer viewer;
-
- public NodePrivilegesPage(FormEditor editor, String title, Node context) {
- super(editor, "NodePrivilegesPage", title);
- this.context = context;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- form.setText(WorkbenchUiPlugin.getMessage("nodeRightsManagementPageTitle"));
- FillLayout layout = new FillLayout();
- layout.marginHeight = 5;
- layout.marginWidth = 5;
- form.getBody().setLayout(layout);
- if (isJackRabbit())
- createRightsPart(form.getBody());
- }
-
- /** Creates the authorization part */
- protected void createRightsPart(Composite parent) {
- Table table = new Table(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
- viewer = new TableViewer(table);
-
- // Group / user name
- TableViewerColumn column = createTableViewerColumn(viewer, "User/Group Name", 280);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -2290781173498395973L;
-
- public String getText(Object element) {
- Node node = (Node) element;
- try {
- if (node.hasProperty("rep:principalName"))
- return node.getProperty("rep:principalName").getString();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to retrieve " + "principal name on " + node, e);
- }
- return "";
- }
-
- public Image getImage(Object element) {
- return null;
- }
- });
-
- // Privileges
- column = createTableViewerColumn(viewer, "Assigned privileges", 300);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -2290781173498395973L;
- private String propertyName = "rep:privileges";
-
- public String getText(Object element) {
- Node node = (Node) element;
- try {
- if (node.hasProperty(propertyName)) {
- String separator = ", ";
- Value[] langs = node.getProperty(propertyName).getValues();
- StringBuilder builder = new StringBuilder();
- for (Value val : langs) {
- String currStr = val.getString();
- builder.append(currStr).append(separator);
- }
- if (builder.lastIndexOf(separator) >= 0)
- return builder.substring(0, builder.length() - separator.length());
- else
- return builder.toString();
-
- }
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to retrieve " + "privileges on " + node, e);
- }
- return "";
- }
-
- public Image getImage(Object element) {
- return null;
- }
- });
-
- // Relevant node
- column = createTableViewerColumn(viewer, "Relevant node", 300);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 4245522992038244849L;
-
- public String getText(Object element) {
- Node node = (Node) element;
- try {
- return node.getParent().getParent().getPath();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable get path for " + node, e);
- }
- }
-
- public Image getImage(Object element) {
- return null;
- }
- });
-
- viewer.setContentProvider(new RightsContentProvider());
- viewer.setInput(getEditorSite());
- }
-
- protected TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound) {
- TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
- TableColumn column = viewerColumn.getColumn();
- column.setText(title);
- column.setWidth(bound);
- column.setResizable(true);
- column.setMoveable(true);
- return viewerColumn;
- }
-
- private class RightsContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -7631476348552802706L;
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- // TODO JackRabbit specific retrieval of authorization. Clean and
- // generalize
- public Object[] getElements(Object inputElement) {
- try {
- List<Node> privs = new ArrayList<Node>();
-
- Node currNode = context;
- String currPath = currNode.getPath();
-
- loop: while (true) {
- if (currNode.hasNode("rep:policy")) {
- NodeIterator nit = currNode.getNode("rep:policy").getNodes();
- while (nit.hasNext()) {
- Node currPrivNode = nit.nextNode();
- if (currPrivNode.getName().startsWith("allow"))
- privs.add(currPrivNode);
- }
- }
- if ("/".equals(currPath))
- break loop;
- else {
- currNode = currNode.getParent();
- currPath = currNode.getPath();
- }
- }
-
- // AccessControlManager acm = context.getSession()
- // .getAccessControlManager();
- // AccessControlPolicyIterator acpi = acm
- // .getApplicablePolicies(context.getPath());
- //
- // List<AccessControlPolicy> acps = new
- // ArrayList<AccessControlPolicy>();
- // try {
- // while (true) {
- // Object obj = acpi.next();
- // acps.add((AccessControlPolicy) obj);
- // }
- // } catch (Exception e) {
- // // No more elements
- // }
- //
- // AccessControlList acl = ((AccessControlList) acps.get(0));
- // AccessControlEntry[] entries = acl.getAccessControlEntries();
-
- return privs.toArray();
- } catch (Exception e) {
- throw new EclipseUiException("Cannot retrieve authorization for " + context, e);
- }
- }
- }
-
- /**
- * Simply checks if we are using jackrabbit without adding code dependencies
- */
- private boolean isJackRabbit() {
- try {
- String cname = context.getSession().getClass().getName();
- return cname.startsWith("org.apache.jackrabbit");
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot check JCR implementation used on " + context, e);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.version.Version;
-import javax.jcr.version.VersionHistory;
-import javax.jcr.version.VersionIterator;
-import javax.jcr.version.VersionManager;
-
-import org.argeo.cms.ui.CmsUiConstants;
-import org.argeo.cms.ui.jcr.FullVersioningTreeContentProvider;
-import org.argeo.cms.ui.jcr.JcrDClickListener;
-import org.argeo.cms.ui.jcr.VersionLabelProvider;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.WorkbenchConstants;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.PropertyDiff;
-import org.argeo.jcr.VersionDiff;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-
-/**
- * Offers two main sections : one to display a text area with a summary of all
- * variations between a version and its predecessor and one tree view that
- * enable browsing
- */
-public class NodeVersionHistoryPage extends FormPage implements WorkbenchConstants {
- // private final static CmsLog log = CmsLog
- // .getLog(NodeVersionHistoryPage.class);
-
- // Utils
- protected DateFormat timeFormatter = new SimpleDateFormat(CmsUiConstants.DATE_TIME_FORMAT);
-
- // business objects
- private Node currentNode;
-
- // this page UI components
- private FullVersioningTreeContentProvider nodeContentProvider;
- private TreeViewer nodesViewer;
- private FormToolkit tk;
-
- public NodeVersionHistoryPage(FormEditor editor, String title, Node currentNode) {
- super(editor, "NodeVersionHistoryPage", title);
- this.currentNode = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- form.setText(WorkbenchUiPlugin.getMessage("nodeVersionHistoryPageTitle"));
- tk = managedForm.getToolkit();
- Composite innerBox = form.getBody();
- // Composite innerBox = new Composite(body, SWT.NO_FOCUS);
- GridLayout twt = new GridLayout(1, false);
- twt.marginWidth = twt.marginHeight = 5;
- innerBox.setLayout(twt);
- try {
- if (!currentNode.isNodeType(NodeType.MIX_VERSIONABLE)) {
- tk.createLabel(innerBox, WorkbenchUiPlugin.getMessage("warningUnversionableNode"));
- } else {
- createHistorySection(innerBox);
- createTreeSection(innerBox);
- }
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unable to check if node is versionable", e);
- }
- }
-
- protected void createTreeSection(Composite parent) {
- Section section = tk.createSection(parent, Section.TWISTIE);
- section.setLayoutData(new GridData(GridData.FILL_BOTH));
- section.setText(WorkbenchUiPlugin.getMessage("versionTreeSectionTitle"));
-
- Composite body = tk.createComposite(section, SWT.FILL);
- section.setClient(body);
- section.setExpanded(true);
- body.setLayoutData(new GridData(GridData.FILL_BOTH));
- body.setLayout(new GridLayout());
-
- nodeContentProvider = new FullVersioningTreeContentProvider();
- nodesViewer = createNodeViewer(body, nodeContentProvider);
- nodesViewer.setInput(currentNode);
- }
-
- protected TreeViewer createNodeViewer(Composite parent, final ITreeContentProvider nodeContentProvider) {
-
- final TreeViewer tmpNodeViewer = new TreeViewer(parent, SWT.MULTI);
-
- tmpNodeViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- tmpNodeViewer.setContentProvider(nodeContentProvider);
- tmpNodeViewer.setLabelProvider(new VersionLabelProvider());
- tmpNodeViewer.addDoubleClickListener(new JcrDClickListener(tmpNodeViewer));
- return tmpNodeViewer;
- }
-
- protected void createHistorySection(Composite parent) {
-
- // Section Layout
- Section section = tk.createSection(parent, Section.TWISTIE);
- section.setLayoutData(new GridData(TableWrapData.FILL_GRAB));
- TableWrapLayout twt = new TableWrapLayout();
- section.setLayout(twt);
-
- // Set title of the section
- section.setText(WorkbenchUiPlugin.getMessage("versionHistorySectionTitle"));
-
- final Text styledText = tk.createText(section, "",
- SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
- section.setClient(styledText);
- styledText.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.FILL_GRAB));
- refreshHistory(styledText);
- styledText.setEditable(false);
- section.setExpanded(false);
-
- AbstractFormPart part = new AbstractFormPart() {
- public void commit(boolean onSave) {
- }
-
- public void refresh() {
- super.refresh();
- refreshHistory(styledText);
- }
- };
- getManagedForm().addPart(part);
- }
-
- protected void refreshHistory(Text styledText) {
- try {
- List<VersionDiff> lst = listHistoryDiff();
- StringBuffer main = new StringBuffer("");
-
- for (int i = lst.size() - 1; i >= 0; i--) {
- if (i == 0)
- main.append("Creation (");
- else
- main.append("Update " + i + " (");
-
- if (lst.get(i).getUserId() != null)
- main.append("UserId : " + lst.get(i).getUserId());
-
- if (lst.get(i).getUserId() != null && lst.get(i).getUpdateTime() != null)
- main.append(", ");
-
- if (lst.get(i).getUpdateTime() != null)
- main.append("Date : " + timeFormatter.format(lst.get(i).getUpdateTime().getTime()) + ")\n");
-
- StringBuffer buf = new StringBuffer("");
- Map<String, PropertyDiff> diffs = lst.get(i).getDiffs();
- for (String prop : diffs.keySet()) {
- PropertyDiff pd = diffs.get(prop);
- // String propName = pd.getRelPath();
- Value refValue = pd.getReferenceValue();
- Value newValue = pd.getNewValue();
- String refValueStr = "";
- String newValueStr = "";
-
- if (refValue != null) {
- if (refValue.getType() == PropertyType.DATE) {
- refValueStr = timeFormatter.format(refValue.getDate().getTime());
- } else
- refValueStr = refValue.getString();
- }
- if (newValue != null) {
- if (newValue.getType() == PropertyType.DATE) {
- newValueStr = timeFormatter.format(newValue.getDate().getTime());
- } else
- newValueStr = newValue.getString();
- }
-
- if (pd.getType() == PropertyDiff.MODIFIED) {
- buf.append(prop).append(": ");
- buf.append(refValueStr);
- buf.append(" > ");
- buf.append(newValueStr);
- buf.append("\n");
- } else if (pd.getType() == PropertyDiff.ADDED && !"".equals(newValueStr)) {
- // we don't list property that have been added with an
- // empty string as value
- buf.append(prop).append(": ");
- buf.append(" + ");
- buf.append(newValueStr);
- buf.append("\n");
- } else if (pd.getType() == PropertyDiff.REMOVED) {
- buf.append(prop).append(": ");
- buf.append(" - ");
- buf.append(refValueStr);
- buf.append("\n");
- }
- }
- buf.append("\n");
- main.append(buf);
- }
- styledText.setText(main.toString());
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot generate history for node", e);
- }
- }
-
- public List<VersionDiff> listHistoryDiff() {
- try {
- List<VersionDiff> res = new ArrayList<VersionDiff>();
- VersionManager versionManager = currentNode.getSession().getWorkspace().getVersionManager();
- VersionHistory versionHistory = versionManager.getVersionHistory(currentNode.getPath());
-
- VersionIterator vit = versionHistory.getAllLinearVersions();
- while (vit.hasNext()) {
- Version version = vit.nextVersion();
- Node node = version.getFrozenNode();
- Version predecessor = null;
- try {
- predecessor = version.getLinearPredecessor();
- } catch (Exception e) {
- // no predecessor seems to throw an exception even if it
- // shouldn't...
- }
- if (predecessor == null) {// original
- } else {
- Map<String, PropertyDiff> diffs = JcrUtils.diffProperties(predecessor.getFrozenNode(), node);
- if (!diffs.isEmpty()) {
- String lastUserName = null;
- Calendar lastUpdate = null;
- try {
- if (currentNode.isNodeType(NodeType.MIX_LAST_MODIFIED)) {
- lastUserName = node.getProperty(Property.JCR_LAST_MODIFIED_BY).getString();
- lastUpdate = node.getProperty(Property.JCR_LAST_MODIFIED).getDate();
- } else
- lastUpdate = version.getProperty(Property.JCR_CREATED).getDate();
-
- } catch (Exception e) {
- // Silent that info is optional
- }
- VersionDiff vd = new VersionDiff(lastUserName, lastUpdate, diffs);
- res.add(vd);
- }
- }
- }
- return res;
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot generate history for node ");
- }
-
- }
-
- @Override
- public void setActive(boolean active) {
- super.setActive(active);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.jcr.parts;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/**
- * An editor input based on three strings define a node :
- * <ul>
- * <li>complete path to the node</li>
- * <li>the workspace name</li>
- * <li>the repository alias</li>
- * </ul>
- * In a single workspace and/or repository environment, name and alias can be
- * null.
- *
- * Note : unused for the time being.
- */
-
-public class StringNodeEditorInput implements IEditorInput {
- private final String path;
- private final String repositoryAlias;
- private final String workspaceName;
-
- /**
- * In order to implement a generic explorer that supports remote and multi
- * workspaces repositories, node path can be detailed by these strings.
- *
- * @param repositoryAlias
- * : can be null
- * @param workspaceName
- * : can be null
- * @param path
- */
- public StringNodeEditorInput(String repositoryAlias, String workspaceName,
- String path) {
- this.path = path;
- this.repositoryAlias = repositoryAlias;
- this.workspaceName = workspaceName;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return path;
- }
-
- public String getRepositoryAlias() {
- return repositoryAlias;
- }
-
- public String getWorkspaceName() {
- return workspaceName;
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return path;
- }
-
- public String getPath() {
- return path;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
-
- StringNodeEditorInput other = (StringNodeEditorInput) obj;
-
- if (!path.equals(other.getPath()))
- return false;
-
- String own = other.getWorkspaceName();
- if ((workspaceName == null && own != null)
- || (workspaceName != null && (own == null || !workspaceName
- .equals(own))))
- return false;
-
- String ora = other.getRepositoryAlias();
- if ((repositoryAlias == null && ora != null)
- || (repositoryAlias != null && (ora == null || !repositoryAlias
- .equals(ora))))
- return false;
-
- return true;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin;
-
-import org.argeo.cms.CmsException;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IStartup;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-
-/** Manage transaction and part refresh while updating the security model */
-public class PartStateChanged implements IPartListener, IStartup {
- // private final static CmsLog log = CmsLog.getLog(PartStateChanged.class);
- // private IContextActivation contextActivation;
-
- @Override
- public void earlyStartup() {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- try {
- IWorkbenchPage iwp = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- if (iwp != null)
- iwp.addPartListener(new PartStateChanged());
- } catch (Exception e) {
- throw new CmsException(
- "Error while registering the PartStateChangedListener",
- e);
- }
- }
- });
- }
-
- @Override
- public void partActivated(IWorkbenchPart part) {
- // Nothing to do
- }
-
- @Override
- public void partBroughtToTop(IWorkbenchPart part) {
- // Nothing to do
- }
-
- @Override
- public void partClosed(IWorkbenchPart part) {
- // Nothing to do
- }
-
- @Override
- public void partDeactivated(IWorkbenchPart part) {
- // Nothing to do
- }
-
- @Override
- public void partOpened(IWorkbenchPart part) {
- // Nothing to do
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin;
-
-import static org.argeo.cms.ui.workbench.WorkbenchUiPlugin.getImageDescriptor;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-
-/** Shared icons that must be declared programmatically . */
-public class SecurityAdminImages {
- private final static String PREFIX = "icons/";
-
- public final static ImageDescriptor ICON_REMOVE_DESC = getImageDescriptor(PREFIX + "delete.png");
- public final static ImageDescriptor ICON_USER_DESC = getImageDescriptor(PREFIX + "person.png");
-
- public final static Image ICON_USER = ICON_USER_DESC.createImage();
- public final static Image ICON_GROUP = getImageDescriptor(PREFIX + "group.png").createImage();
- public final static Image ICON_WORKGROUP = getImageDescriptor(PREFIX + "workgroup.png").createImage();
- public final static Image ICON_ROLE = getImageDescriptor(PREFIX + "role.gif").createImage();
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin;
-
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTransactionProvider;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.services.ISourceProviderService;
-
-/** First effort to centralize back end methods used by the user admin UI */
-public class UiAdminUtils {
- /*
- * INTERNAL METHODS: Below methods are meant to stay here and are not part
- * of a potential generic backend to manage the useradmin
- */
- /** Easily notify the ActiveWindow that the transaction had a state change */
- public final static void notifyTransactionStateChange(
- WorkTransaction userTransaction) {
- try {
- IWorkbenchWindow aww = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- ISourceProviderService sourceProviderService = (ISourceProviderService) aww
- .getService(ISourceProviderService.class);
- UserTransactionProvider esp = (UserTransactionProvider) sourceProviderService
- .getSourceProvider(UserTransactionProvider.TRANSACTION_STATE);
- esp.fireTransactionStateChange();
- } catch (Exception e) {
- throw new CmsException("Unable to begin transaction", e);
- }
- }
-
- /**
- * Email addresses must match this regexp pattern ({@value #EMAIL_PATTERN}.
- * Thanks to <a href=
- * "http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/"
- * >this tip</a>.
- */
- public final static String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin;
-
-import org.eclipse.swt.widgets.Display;
-import org.osgi.service.useradmin.UserAdminEvent;
-import org.osgi.service.useradmin.UserAdminListener;
-
-/** Convenience class to insure the call to refresh is done in the UI thread */
-public abstract class UiUserAdminListener implements UserAdminListener {
-
- private final Display display;
-
- public UiUserAdminListener(Display display) {
- this.display = display;
- }
-
- @Override
- public void roleChanged(final UserAdminEvent event) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- roleChangedToUiThread(event);
- }
- });
- }
-
- public abstract void roleChangedToUiThread(UserAdminEvent event);
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin;
-
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.CmsException;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.argeo.osgi.useradmin.UserAdminConf;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-import org.osgi.service.useradmin.UserAdminListener;
-
-/** Centralise interaction with the UserAdmin in this bundle */
-public class UserAdminWrapper {
-
- private UserAdmin userAdmin;
- private ServiceReference<UserAdmin> userAdminServiceReference;
- private WorkTransaction userTransaction;
-
- // First effort to simplify UX while managing users and groups
- public final static boolean COMMIT_ON_SAVE = true;
-
- // Registered listeners
- List<UserAdminListener> listeners = new ArrayList<UserAdminListener>();
-
- /**
- * Starts a transaction if necessary. Should always been called together
- * with {@link UserAdminWrapper#commitOrNotifyTransactionStateChange()} once
- * the security model changes have been performed.
- */
- public WorkTransaction beginTransactionIfNeeded() {
- try {
- // UserTransaction userTransaction = getUserTransaction();
- if (userTransaction.isNoTransactionStatus()) {
- userTransaction.begin();
- // UiAdminUtils.notifyTransactionStateChange(userTransaction);
- }
- return userTransaction;
- } catch (Exception e) {
- throw new CmsException("Unable to begin transaction", e);
- }
- }
-
- /**
- * Depending on the current application configuration, it will either commit
- * the current transaction or throw a notification that the transaction
- * state has changed (In the later case, it must be called from the UI
- * thread).
- */
- public void commitOrNotifyTransactionStateChange() {
- try {
- // UserTransaction userTransaction = getUserTransaction();
- if (userTransaction.isNoTransactionStatus())
- return;
-
- if (UserAdminWrapper.COMMIT_ON_SAVE)
- userTransaction.commit();
- else
- UiAdminUtils.notifyTransactionStateChange(userTransaction);
- } catch (Exception e) {
- throw new CmsException("Unable to clean transaction", e);
- }
- }
-
- // TODO implement safer mechanism
- public void addListener(UserAdminListener userAdminListener) {
- if (!listeners.contains(userAdminListener))
- listeners.add(userAdminListener);
- }
-
- public void removeListener(UserAdminListener userAdminListener) {
- if (listeners.contains(userAdminListener))
- listeners.remove(userAdminListener);
- }
-
- public void notifyListeners(UserAdminEvent event) {
- for (UserAdminListener listener : listeners)
- listener.roleChanged(event);
- }
-
- public Map<String, String> getKnownBaseDns(boolean onlyWritable) {
- Map<String, String> dns = new HashMap<String, String>();
- for (String uri : userAdminServiceReference.getPropertyKeys()) {
- if (!uri.startsWith("/"))
- continue;
- Dictionary<String, ?> props = UserAdminConf.uriAsProperties(uri);
- String readOnly = UserAdminConf.readOnly.getValue(props);
- String baseDn = UserAdminConf.baseDn.getValue(props);
-
- if (onlyWritable && "true".equals(readOnly))
- continue;
- if (baseDn.equalsIgnoreCase(CmsConstants.ROLES_BASEDN))
- continue;
- dns.put(baseDn, uri);
- }
- return dns;
- }
-
- public UserAdmin getUserAdmin() {
- return userAdmin;
- }
-
- public WorkTransaction getUserTransaction() {
- return userTransaction;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdmin(UserAdmin userAdmin) {
- this.userAdmin = userAdmin;
- }
-
- public void setUserTransaction(WorkTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-
- public void setUserAdminServiceReference(
- ServiceReference<UserAdmin> userAdminServiceReference) {
- this.userAdminServiceReference = userAdminServiceReference;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditorInput;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Delete the selected groups */
-public class DeleteGroups extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".deleteGroups";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- @SuppressWarnings("unchecked")
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection.isEmpty())
- return null;
-
- List<Group> groups = new ArrayList<Group>();
- Iterator<Group> it = ((IStructuredSelection) selection).iterator();
- StringBuilder builder = new StringBuilder();
- while (it.hasNext()) {
- Group currGroup = it.next();
- String groupName = UserAdminUtils.getUserLocalId(currGroup.getName());
- // TODO add checks
- builder.append(groupName).append("; ");
- groups.add(currGroup);
- }
-
- if (!MessageDialog.openQuestion(HandlerUtil.getActiveShell(event), "Delete Groups", "Are you sure that you "
- + "want to delete these groups?\n" + builder.substring(0, builder.length() - 2)))
- return null;
-
- userAdminWrapper.beginTransactionIfNeeded();
- UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
- IWorkbenchPage iwp = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
- for (Group group : groups) {
- String groupName = group.getName();
- // TODO find a way to close the editor cleanly if opened. Cannot be
- // done through the UserAdminListeners, it causes a
- // java.util.ConcurrentModificationException because disposing the
- // editor unregisters and disposes the listener
- IEditorPart part = iwp.findEditor(new UserEditorInput(groupName));
- if (part != null)
- iwp.closeEditor(part, false);
- userAdmin.removeRole(groupName);
- }
- userAdminWrapper.commitOrNotifyTransactionStateChange();
-
- // Update the view
- for (Group group : groups) {
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_REMOVED, group));
- }
-
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditorInput;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Delete the selected users */
-public class DeleteUsers extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".deleteUsers";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- @SuppressWarnings("unchecked")
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection.isEmpty())
- return null;
-
- Iterator<User> it = ((IStructuredSelection) selection).iterator();
- List<User> users = new ArrayList<User>();
- StringBuilder builder = new StringBuilder();
-
- while (it.hasNext()) {
- User currUser = it.next();
- String userName = UserAdminUtils.getUserLocalId(currUser.getName());
- if (UserAdminUtils.isCurrentUser(currUser)) {
- MessageDialog.openError(HandlerUtil.getActiveShell(event), "Deletion forbidden",
- "You cannot delete your own user this way.");
- return null;
- }
- builder.append(userName).append("; ");
- users.add(currUser);
- }
-
- if (!MessageDialog.openQuestion(HandlerUtil.getActiveShell(event), "Delete Users",
- "Are you sure that you want to delete these users?\n" + builder.substring(0, builder.length() - 2)))
- return null;
-
- userAdminWrapper.beginTransactionIfNeeded();
- UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
- IWorkbenchPage iwp = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
-
- for (User user : users) {
- String userName = user.getName();
- // TODO find a way to close the editor cleanly if opened. Cannot be
- // done through the UserAdminListeners, it causes a
- // java.util.ConcurrentModificationException because disposing the
- // editor unregisters and disposes the listener
- IEditorPart part = iwp.findEditor(new UserEditorInput(userName));
- if (part != null)
- iwp.closeEditor(part, false);
- userAdmin.removeRole(userName);
- }
- userAdminWrapper.commitOrNotifyTransactionStateChange();
-
- for (User user : users) {
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_REMOVED, user));
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.GroupsView;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UsersView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Retrieve the active view or editor and call forceRefresh method if defined */
-public class ForceRefresh extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchWindow iww = HandlerUtil.getActiveWorkbenchWindow(event);
- if (iww == null)
- return null;
- IWorkbenchPage activePage = iww.getActivePage();
- IWorkbenchPart part = activePage.getActivePart();
- if (part instanceof UsersView)
- ((UsersView) part).refresh();
- else if (part instanceof GroupsView)
- ((GroupsView) part).refresh();
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import java.util.Dictionary;
-import java.util.Map;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.osgi.useradmin.UserAdminConf;
-import org.argeo.util.naming.LdapAttrs;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Create a new group */
-public class NewGroup extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".newGroup";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- NewGroupWizard newGroupWizard = new NewGroupWizard();
- newGroupWizard.setWindowTitle("Group creation");
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), newGroupWizard);
- dialog.open();
- return null;
- }
-
- private class NewGroupWizard extends Wizard {
-
- // Pages
- private MainGroupInfoWizardPage mainGroupInfo;
-
- // UI fields
- private Text dNameTxt, commonNameTxt, descriptionTxt;
- private Combo baseDnCmb;
-
- public NewGroupWizard() {
- }
-
- @Override
- public void addPages() {
- mainGroupInfo = new MainGroupInfoWizardPage();
- addPage(mainGroupInfo);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- String commonName = commonNameTxt.getText();
- try {
- userAdminWrapper.beginTransactionIfNeeded();
- String dn = getDn(commonName);
- Group group = (Group) userAdminWrapper.getUserAdmin()
- .createRole(dn, Role.GROUP);
- Dictionary props = group.getProperties();
- String descStr = descriptionTxt.getText();
- if (EclipseUiUtils.notEmpty(descStr))
- props.put(LdapAttrs.description.name(), descStr);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CREATED, group));
- return true;
- } catch (Exception e) {
- ErrorFeedback.show("Cannot create new group " + commonName, e);
- return false;
- }
- }
-
- private class MainGroupInfoWizardPage extends WizardPage implements
- FocusListener, ArgeoNames {
- private static final long serialVersionUID = -3150193365151601807L;
-
- public MainGroupInfoWizardPage() {
- super("Main");
- setTitle("General information");
- setMessage("Please choose a domain, provide a common name "
- + "and a free description");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite bodyCmp = new Composite(parent, SWT.NONE);
- setControl(bodyCmp);
- bodyCmp.setLayout(new GridLayout(2, false));
-
- dNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
- "Distinguished name");
- dNameTxt.setEnabled(false);
-
- baseDnCmb = createGridLC(bodyCmp, "Base DN");
- // Initialise before adding the listener to avoid NPE
- initialiseDnCmb(baseDnCmb);
- baseDnCmb.addFocusListener(this);
-
- commonNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
- "Common name");
- commonNameTxt.addFocusListener(this);
-
- Label descLbl = new Label(bodyCmp, SWT.LEAD);
- descLbl.setText("Description");
- descLbl.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false,
- false));
- descriptionTxt = new Text(bodyCmp, SWT.LEAD | SWT.MULTI
- | SWT.WRAP | SWT.BORDER);
- descriptionTxt.setLayoutData(EclipseUiUtils.fillAll());
- descriptionTxt.addFocusListener(this);
-
- // Initialize buttons
- setPageComplete(false);
- getContainer().updateButtons();
- }
-
- @Override
- public void focusLost(FocusEvent event) {
- String name = commonNameTxt.getText();
- if (EclipseUiUtils.isEmpty(name))
- dNameTxt.setText("");
- else
- dNameTxt.setText(getDn(name));
-
- String message = checkComplete();
- if (message != null) {
- setMessage(message, WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- getContainer().updateButtons();
- }
-
- @Override
- public void focusGained(FocusEvent event) {
- }
-
- /** @return the error message or null if complete */
- protected String checkComplete() {
- String name = commonNameTxt.getText();
-
- if (name.trim().equals(""))
- return "Common name must not be empty";
- Role role = userAdminWrapper.getUserAdmin()
- .getRole(getDn(name));
- if (role != null)
- return "Group " + name + " already exists";
- return null;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible)
- if (baseDnCmb.getSelectionIndex() == -1)
- baseDnCmb.setFocus();
- else
- commonNameTxt.setFocus();
- }
- }
-
- private Map<String, String> getDns() {
- return userAdminWrapper.getKnownBaseDns(true);
- }
-
- private String getDn(String cn) {
- Map<String, String> dns = getDns();
- String bdn = baseDnCmb.getText();
- if (EclipseUiUtils.notEmpty(bdn)) {
- Dictionary<String, ?> props = UserAdminConf.uriAsProperties(dns
- .get(bdn));
- String dn = LdapAttrs.cn.name() + "=" + cn + ","
- + UserAdminConf.groupBase.getValue(props) + "," + bdn;
- return dn;
- }
- return null;
- }
-
- private void initialiseDnCmb(Combo combo) {
- Map<String, String> dns = userAdminWrapper.getKnownBaseDns(true);
- if (dns.isEmpty())
- throw new CmsException(
- "No writable base dn found. Cannot create group");
- combo.setItems(dns.keySet().toArray(new String[0]));
- if (dns.size() == 1)
- combo.select(0);
- }
- }
-
- private Combo createGridLC(Composite parent, String label) {
- Label lbl = new Label(parent, SWT.LEAD);
- lbl.setText(label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Combo combo = new Combo(parent, SWT.LEAD | SWT.BORDER | SWT.READ_ONLY);
- combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return combo;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import java.util.Dictionary;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-import javax.naming.ldap.Rdn;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiAdminUtils;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.osgi.useradmin.UserAdminConf;
-import org.argeo.util.naming.LdapAttrs;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Open a wizard that enables creation of a new user. */
-public class NewUser extends AbstractHandler {
- // private final static CmsLog log = CmsLog.getLog(NewUser.class);
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".newUser";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- NewUserWizard newUserWizard = new NewUserWizard();
- newUserWizard.setWindowTitle("User creation");
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), newUserWizard);
- dialog.open();
- return null;
- }
-
- private class NewUserWizard extends Wizard {
-
- // pages
- private MainUserInfoWizardPage mainUserInfo;
-
- // End user fields
- private Text dNameTxt, usernameTxt, firstNameTxt, lastNameTxt,
- primaryMailTxt, pwd1Txt, pwd2Txt;
- private Combo baseDnCmb;
-
- public NewUserWizard() {
-
- }
-
- @Override
- public void addPages() {
- mainUserInfo = new MainUserInfoWizardPage();
- addPage(mainUserInfo);
- String message = "Default wizard that also eases user creation tests:\n "
- + "Mail and last name are automatically "
- + "generated form the uid. Password are defauted to 'demo'.";
- mainUserInfo.setMessage(message, WizardPage.WARNING);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- String username = mainUserInfo.getUsername();
- userAdminWrapper.beginTransactionIfNeeded();
- try {
- User user = (User) userAdminWrapper.getUserAdmin().createRole(
- getDn(username), Role.USER);
-
- Dictionary props = user.getProperties();
-
- String lastNameStr = lastNameTxt.getText();
- if (EclipseUiUtils.notEmpty(lastNameStr))
- props.put(LdapAttrs.sn.name(), lastNameStr);
-
- String firstNameStr = firstNameTxt.getText();
- if (EclipseUiUtils.notEmpty(firstNameStr))
- props.put(LdapAttrs.givenName.name(), firstNameStr);
-
- String cn = UserAdminUtils.buildDefaultCn(firstNameStr,
- lastNameStr);
- if (EclipseUiUtils.notEmpty(cn))
- props.put(LdapAttrs.cn.name(), cn);
-
- String mailStr = primaryMailTxt.getText();
- if (EclipseUiUtils.notEmpty(mailStr))
- props.put(LdapAttrs.mail.name(), mailStr);
-
- char[] password = mainUserInfo.getPassword();
- user.getCredentials().put(null, password);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CREATED, user));
- return true;
- } catch (Exception e) {
- ErrorFeedback.show("Cannot create new user " + username, e);
- return false;
- }
- }
-
- private class MainUserInfoWizardPage extends WizardPage implements
- ModifyListener, ArgeoNames {
- private static final long serialVersionUID = -3150193365151601807L;
-
- public MainUserInfoWizardPage() {
- super("Main");
- setTitle("Required Information");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- dNameTxt = EclipseUiUtils.createGridLT(composite,
- "Distinguished name", this);
- dNameTxt.setEnabled(false);
-
- baseDnCmb = createGridLC(composite, "Base DN");
- initialiseDnCmb(baseDnCmb);
- baseDnCmb.addModifyListener(this);
- baseDnCmb.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -1435351236582736843L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String name = usernameTxt.getText();
- dNameTxt.setText(getDn(name));
- }
- });
-
- usernameTxt = EclipseUiUtils.createGridLT(composite,
- "Local ID", this);
- usernameTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -1435351236582736843L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String name = usernameTxt.getText();
- if (name.trim().equals("")) {
- dNameTxt.setText("");
- lastNameTxt.setText("");
- primaryMailTxt.setText("");
- pwd1Txt.setText("");
- pwd2Txt.setText("");
- } else {
- dNameTxt.setText(getDn(name));
- lastNameTxt.setText(name.toUpperCase());
- primaryMailTxt.setText(getMail(name));
- pwd1Txt.setText("demo");
- pwd2Txt.setText("demo");
- }
- }
- });
-
- primaryMailTxt = EclipseUiUtils.createGridLT(composite,
- "Email", this);
- firstNameTxt = EclipseUiUtils.createGridLT(composite,
- "First name", this);
- lastNameTxt = EclipseUiUtils.createGridLT(composite,
- "Last name", this);
- pwd1Txt = EclipseUiUtils.createGridLP(composite, "Password",
- this);
- pwd2Txt = EclipseUiUtils.createGridLP(composite,
- "Repeat password", this);
- setControl(composite);
-
- // Initialize buttons
- setPageComplete(false);
- getContainer().updateButtons();
- }
-
- @Override
- public void modifyText(ModifyEvent event) {
- String message = checkComplete();
- if (message != null) {
- setMessage(message, WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- getContainer().updateButtons();
- }
-
- /** @return error message or null if complete */
- protected String checkComplete() {
- String name = usernameTxt.getText();
-
- if (name.trim().equals(""))
- return "User name must not be empty";
- Role role = userAdminWrapper.getUserAdmin()
- .getRole(getDn(name));
- if (role != null)
- return "User " + name + " already exists";
- if (!primaryMailTxt.getText().matches(UiAdminUtils.EMAIL_PATTERN))
- return "Not a valid email address";
- if (lastNameTxt.getText().trim().equals(""))
- return "Specify a last name";
- if (pwd1Txt.getText().trim().equals(""))
- return "Specify a password";
- if (pwd2Txt.getText().trim().equals(""))
- return "Repeat the password";
- if (!pwd2Txt.getText().equals(pwd1Txt.getText()))
- return "Passwords are different";
- return null;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible)
- if (baseDnCmb.getSelectionIndex() == -1)
- baseDnCmb.setFocus();
- else
- usernameTxt.setFocus();
- }
-
- public String getUsername() {
- return usernameTxt.getText();
- }
-
- public char[] getPassword() {
- return pwd1Txt.getTextChars();
- }
-
- }
-
- private Map<String, String> getDns() {
- return userAdminWrapper.getKnownBaseDns(true);
- }
-
- private String getDn(String uid) {
- Map<String, String> dns = getDns();
- String bdn = baseDnCmb.getText();
- if (EclipseUiUtils.notEmpty(bdn)) {
- Dictionary<String, ?> props = UserAdminConf.uriAsProperties(dns
- .get(bdn));
- String dn = LdapAttrs.uid.name() + "=" + uid + ","
- + UserAdminConf.userBase.getValue(props) + "," + bdn;
- return dn;
- }
- return null;
- }
-
- private void initialiseDnCmb(Combo combo) {
- Map<String, String> dns = userAdminWrapper.getKnownBaseDns(true);
- if (dns.isEmpty())
- throw new CmsException(
- "No writable base dn found. Cannot create user");
- combo.setItems(dns.keySet().toArray(new String[0]));
- if (dns.size() == 1)
- combo.select(0);
- }
-
- private String getMail(String username) {
- if (baseDnCmb.getSelectionIndex() == -1)
- return null;
- String baseDn = baseDnCmb.getText();
- try {
- LdapName name = new LdapName(baseDn);
- List<Rdn> rdns = name.getRdns();
- return username + "@" + (String) rdns.get(1).getValue() + '.'
- + (String) rdns.get(0).getValue();
- } catch (InvalidNameException e) {
- throw new CmsException("Unable to generate mail for "
- + username + " with base dn " + baseDn, e);
- }
- }
- }
-
- private Combo createGridLC(Composite parent, String label) {
- Label lbl = new Label(parent, SWT.LEAD);
- lbl.setText(label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Combo combo = new Combo(parent, SWT.LEAD | SWT.BORDER | SWT.READ_ONLY);
- combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return combo;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Save the currently edited Argeo user. */
-public class SaveArgeoUser extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".saveArgeoUser";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- IWorkbenchPart iwp = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getActivePart();
- if (!(iwp instanceof IEditorPart))
- return null;
- IEditorPart editor = (IEditorPart) iwp;
- editor.doSave(null);
- } catch (Exception e) {
- MessageDialog.openError(Display.getDefault().getActiveShell(),
- "Error", "Cannot save user: " + e.getMessage());
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserBatchUpdateWizard;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Launch a wizard to perform batch process on users */
-public class UserBatchUpdate extends AbstractHandler {
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper uaWrapper;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- UserBatchUpdateWizard wizard = new UserBatchUpdateWizard(uaWrapper);
- wizard.setWindowTitle("User batch processing");
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- dialog.open();
- return null;
- }
-
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.uaWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.commands;
-
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiAdminUtils;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Manage the transaction that is bound to the current perspective */
-public class UserTransactionHandler extends AbstractHandler {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".userTransactionHandler";
-
- public final static String PARAM_COMMAND_ID = "param.commandId";
-
- public final static String TRANSACTION_BEGIN = "transaction.begin";
- public final static String TRANSACTION_COMMIT = "transaction.commit";
- public final static String TRANSACTION_ROLLBACK = "transaction.rollback";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String commandId = event.getParameter(PARAM_COMMAND_ID);
- final WorkTransaction userTransaction = userAdminWrapper.getUserTransaction();
- try {
- if (TRANSACTION_BEGIN.equals(commandId)) {
- if (!userTransaction.isNoTransactionStatus())
- throw new CmsException("A transaction already exists");
- else
- userTransaction.begin();
- } else if (TRANSACTION_COMMIT.equals(commandId)) {
- if (userTransaction.isNoTransactionStatus())
- throw new CmsException("No transaction.");
- else
- userTransaction.commit();
- } else if (TRANSACTION_ROLLBACK.equals(commandId)) {
- if (userTransaction.isNoTransactionStatus())
- throw new CmsException("No transaction to rollback.");
- else {
- userTransaction.rollback();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, null));
- }
- }
-
- UiAdminUtils.notifyTransactionStateChange(userTransaction);
- // Try to remove invalid thread access errors when managing users.
- // HandlerUtil.getActivePart(event).getSite().getShell().getDisplay()
- // .asyncExec(new Runnable() {
- // @Override
- // public void run() {
- // UiAdminUtils
- // .notifyTransactionStateChange(userTransaction);
- // }
- // });
-
- } catch (CmsException e) {
- throw e;
- } catch (Exception e) {
- throw new CmsException("Unable to call " + commandId + " on " + userTransaction, e);
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/** Editor input for an Argeo user. */
-public class ArgeoUserEditorInput implements IEditorInput {
- private final String username;
-
- public ArgeoUserEditorInput(String username) {
- this.username = username;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return username != null;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return username != null ? username : "<new user>";
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return username != null ? username : "<new user>";
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof ArgeoUserEditorInput))
- return false;
- if (((ArgeoUserEditorInput) obj).getUsername() == null)
- return false;
- return ((ArgeoUserEditorInput) obj).getUsername().equals(username);
- }
-
- public String getUsername() {
- return username;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import static org.argeo.api.cms.CmsContext.WORKGROUP;
-import static org.argeo.cms.auth.UserAdminUtils.setProperty;
-import static org.argeo.util.naming.LdapAttrs.businessCategory;
-import static org.argeo.util.naming.LdapAttrs.description;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.api.cms.CmsContext;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.swt.CmsSwtUtils;
-import org.argeo.cms.ui.workbench.CmsWorkbenchStyles;
-import org.argeo.cms.ui.workbench.internal.useradmin.SecurityAdminImages;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor.GroupChangeListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor.MainInfoListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.CommonNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.MailLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.RoleIconLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserFilter;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTableDefaultDClickListener;
-import org.argeo.eclipse.ui.ColumnDefinition;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.parts.LdifUsersTable;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.argeo.util.naming.LdapAttrs;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Display/edit main properties of a given group */
-public class GroupMainPage extends FormPage implements ArgeoNames {
- final static String ID = "GroupEditor.mainPage";
-
- private final UserEditor editor;
- private final CmsContext nodeInstance;
- private final UserAdminWrapper userAdminWrapper;
- private final Session session;
-
- public GroupMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper, Repository repository,
- CmsContext nodeInstance) {
- super(editor, ID, "Main");
- try {
- session = repository.login();
- } catch (RepositoryException e) {
- throw new CmsException("Cannot retrieve session of in MainGroupPage constructor", e);
- }
- this.editor = (UserEditor) editor;
- this.userAdminWrapper = userAdminWrapper;
- this.nodeInstance = nodeInstance;
- }
-
- protected void createFormContent(final IManagedForm mf) {
- ScrolledForm form = mf.getForm();
- Composite body = form.getBody();
- GridLayout mainLayout = new GridLayout();
- body.setLayout(mainLayout);
- Group group = (Group) editor.getDisplayedUser();
- appendOverviewPart(body, group);
- appendMembersPart(body, group);
- }
-
- @Override
- public void dispose() {
- JcrUtils.logoutQuietly(session);
- super.dispose();
- }
-
- /** Creates the general section */
- protected void appendOverviewPart(final Composite parent, final Group group) {
- FormToolkit tk = getManagedForm().getToolkit();
- Composite body = addSection(tk, parent);
- // GridLayout layout = new GridLayout(5, false);
- GridLayout layout = new GridLayout(2, false);
- body.setLayout(layout);
-
- String cn = UserAdminUtils.getProperty(group, LdapAttrs.cn.name());
- createReadOnlyLT(body, "Name", cn);
- // Text dnTxt = createReadOnlyLT(body, "DN", group.getName());
- createReadOnlyLT(body, "Domain", UserAdminUtils.getDomainName(group));
-
- // Description
- Label descLbl = new Label(body, SWT.LEAD);
- descLbl.setFont(EclipseUiUtils.getBoldFont(body));
- descLbl.setText("Description");
- descLbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false, 2, 1));
- final Text descTxt = new Text(body, SWT.LEAD | SWT.MULTI | SWT.WRAP | SWT.BORDER);
- GridData gd = EclipseUiUtils.fillAll();
- gd.heightHint = 50;
- gd.horizontalSpan = 2;
- descTxt.setLayoutData(gd);
-
- // Mark as workgroup
- Link markAsWorkgroupLk = new Link(body, SWT.NONE);
- markAsWorkgroupLk.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
-
- // create form part (controller)
- final AbstractFormPart part = new SectionPart((Section) body.getParent()) {
-
- private MainInfoListener listener;
-
- @Override
- public void initialize(IManagedForm form) {
- super.initialize(form);
- listener = editor.new MainInfoListener(parent.getDisplay(), this);
- userAdminWrapper.addListener(listener);
- }
-
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- public void commit(boolean onSave) {
- // group.getProperties().put(LdapAttrs.description.name(), descTxt.getText());
- setProperty(group, description, descTxt.getText());
- super.commit(onSave);
- }
-
- @Override
- public void refresh() {
- // dnTxt.setText(group.getName());
- // cnTxt.setText(UserAdminUtils.getProperty(group, LdapAttrs.cn.name()));
- descTxt.setText(UserAdminUtils.getProperty(group, LdapAttrs.description.name()));
- Node workgroupHome = CmsJcrUtils.getGroupHome(session, cn);
- if (workgroupHome == null)
- markAsWorkgroupLk.setText("<a>Mark as workgroup</a>");
- else
- markAsWorkgroupLk.setText("Configured as workgroup");
- parent.layout(true, true);
- super.refresh();
- }
- };
-
- markAsWorkgroupLk.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -6439340898096365078L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
-
- boolean confirmed = MessageDialog.openConfirm(parent.getShell(), "Mark as workgroup",
- "Are you sure you want to mark " + cn + " as being a workgroup? ");
- if (confirmed) {
- Node workgroupHome = CmsJcrUtils.getGroupHome(session, cn);
- if (workgroupHome != null)
- return; // already marked as workgroup, do nothing
- else {
- // improve transaction management
- userAdminWrapper.beginTransactionIfNeeded();
- nodeInstance.createWorkgroup(group.getName());
- setProperty(group, businessCategory, WORKGROUP);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, group));
- part.refresh();
- }
- }
- }
- });
-
- ModifyListener defaultListener = editor.new FormPartML(part);
- descTxt.addModifyListener(defaultListener);
- getManagedForm().addPart(part);
- }
-
- /** Filtered table with members. Has drag and drop ability */
- protected void appendMembersPart(Composite parent, Group group) {
- FormToolkit tk = getManagedForm().getToolkit();
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- section.setText("Members");
- section.setLayoutData(EclipseUiUtils.fillAll());
-
- Composite body = new Composite(section, SWT.NO_FOCUS);
- section.setClient(body);
- body.setLayoutData(EclipseUiUtils.fillAll());
-
- LdifUsersTable userTableViewerCmp = createMemberPart(body, group);
-
- SectionPart part = new GroupMembersPart(section, userTableViewerCmp);
- getManagedForm().addPart(part);
- addRemoveAbitily(part, userTableViewerCmp.getTableViewer(), group);
- }
-
- public LdifUsersTable createMemberPart(Composite parent, Group group) {
- parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- // Define the displayed columns
- List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
- columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Name", 150));
- columnDefs.add(new ColumnDefinition(new MailLP(), "Mail", 150));
- // columnDefs.add(new ColumnDefinition(new UserNameLP(), "Distinguished Name",
- // 240));
-
- // Create and configure the table
- LdifUsersTable userViewerCmp = new MyUserTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL,
- userAdminWrapper.getUserAdmin());
-
- userViewerCmp.setColumnDefinitions(columnDefs);
- userViewerCmp.populate(true, false);
- userViewerCmp.setLayoutData(EclipseUiUtils.fillAll());
-
- // Controllers
- TableViewer userViewer = userViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- userViewer.addDropSupport(operations, tt,
- new GroupDropListener(userAdminWrapper, userViewerCmp, (Group) editor.getDisplayedUser()));
-
- return userViewerCmp;
- }
-
- // Local viewers
- private class MyUserTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 8467999509931900367L;
-
- private final UserFilter userFilter;
-
- public MyUserTableViewer(Composite parent, int style, UserAdmin userAdmin) {
- super(parent, style, true);
- userFilter = new UserFilter();
-
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- // reload user and set it in the editor
- Group group = (Group) editor.getDisplayedUser();
- Role[] roles = group.getMembers();
- List<User> users = new ArrayList<User>();
- userFilter.setSearchText(filter);
- // userFilter.setShowSystemRole(true);
- for (Role role : roles)
- // if (role.getType() == Role.GROUP)
- if (userFilter.select(null, null, role))
- users.add((User) role);
- return users;
- }
- }
-
- private void addRemoveAbitily(SectionPart sectionPart, TableViewer userViewer, Group group) {
- Section section = sectionPart.getSection();
- ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
- ToolBar toolbar = toolBarManager.createControl(section);
- final Cursor handCursor = new Cursor(section.getDisplay(), SWT.CURSOR_HAND);
- toolbar.setCursor(handCursor);
- toolbar.addDisposeListener(new DisposeListener() {
- private static final long serialVersionUID = 3882131405820522925L;
-
- public void widgetDisposed(DisposeEvent e) {
- if ((handCursor != null) && (handCursor.isDisposed() == false)) {
- handCursor.dispose();
- }
- }
- });
-
- Action action = new RemoveMembershipAction(userViewer, group, "Remove selected items from this group",
- SecurityAdminImages.ICON_REMOVE_DESC);
- toolBarManager.add(action);
- toolBarManager.update(true);
- section.setTextClient(toolbar);
- }
-
- private class RemoveMembershipAction extends Action {
- private static final long serialVersionUID = -1337713097184522588L;
-
- private final TableViewer userViewer;
- private final Group group;
-
- RemoveMembershipAction(TableViewer userViewer, Group group, String name, ImageDescriptor img) {
- super(name, img);
- this.userViewer = userViewer;
- this.group = group;
- }
-
- @Override
- public void run() {
- ISelection selection = userViewer.getSelection();
- if (selection.isEmpty())
- return;
-
- @SuppressWarnings("unchecked")
- Iterator<User> it = ((IStructuredSelection) selection).iterator();
- List<User> users = new ArrayList<User>();
- while (it.hasNext()) {
- User currUser = it.next();
- users.add(currUser);
- }
-
- userAdminWrapper.beginTransactionIfNeeded();
- for (User user : users) {
- group.removeMember(user);
- }
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, group));
- }
- }
-
- // LOCAL CONTROLLERS
- private class GroupMembersPart extends SectionPart {
- private final LdifUsersTable userViewer;
- // private final Group group;
-
- private GroupChangeListener listener;
-
- public GroupMembersPart(Section section, LdifUsersTable userViewer) {
- super(section);
- this.userViewer = userViewer;
- // this.group = group;
- }
-
- @Override
- public void initialize(IManagedForm form) {
- super.initialize(form);
- listener = editor.new GroupChangeListener(userViewer.getDisplay(), GroupMembersPart.this);
- userAdminWrapper.addListener(listener);
- }
-
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- @Override
- public void refresh() {
- userViewer.refresh();
- super.refresh();
- }
- }
-
- /**
- * Defines this table as being a potential target to add group membership
- * (roles) to this group
- */
- private class GroupDropListener extends ViewerDropAdapter {
- private static final long serialVersionUID = 2893468717831451621L;
-
- private final UserAdminWrapper userAdminWrapper;
- // private final LdifUsersTable myUserViewerCmp;
- private final Group myGroup;
-
- public GroupDropListener(UserAdminWrapper userAdminWrapper, LdifUsersTable userTableViewerCmp, Group group) {
- super(userTableViewerCmp.getTableViewer());
- this.userAdminWrapper = userAdminWrapper;
- this.myGroup = group;
- // this.myUserViewerCmp = userTableViewerCmp;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation, TransferData transferType) {
- // Target is always OK in a list only view
- // TODO check if not a string
- boolean validDrop = true;
- return validDrop;
- }
-
- @Override
- public void drop(DropTargetEvent event) {
- // TODO Is there an opportunity to perform the check before?
- String newUserName = (String) event.data;
- UserAdmin myUserAdmin = userAdminWrapper.getUserAdmin();
- Role role = myUserAdmin.getRole(newUserName);
- if (role.getType() == Role.GROUP) {
- Group newGroup = (Group) role;
- Shell shell = getViewer().getControl().getShell();
- // Sanity checks
- if (myGroup == newGroup) { // Equality
- MessageDialog.openError(shell, "Forbidden addition ", "A group cannot be a member of itself.");
- return;
- }
-
- // Cycle
- String myName = myGroup.getName();
- List<User> myMemberships = editor.getFlatGroups(myGroup);
- if (myMemberships.contains(newGroup)) {
- MessageDialog.openError(shell, "Forbidden addition: cycle",
- "Cannot add " + newUserName + " to group " + myName + ". This would create a cycle");
- return;
- }
-
- // Already member
- List<User> newGroupMemberships = editor.getFlatGroups(newGroup);
- if (newGroupMemberships.contains(myGroup)) {
- MessageDialog.openError(shell, "Forbidden addition",
- "Cannot add " + newUserName + " to group " + myName + ", this membership already exists");
- return;
- }
- userAdminWrapper.beginTransactionIfNeeded();
- myGroup.addMember(newGroup);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, myGroup));
- } else if (role.getType() == Role.USER) {
- // TODO check if the group is already member of this group
- WorkTransaction transaction = userAdminWrapper.beginTransactionIfNeeded();
- User user = (User) role;
- myGroup.addMember(user);
- if (UserAdminWrapper.COMMIT_ON_SAVE)
- try {
- transaction.commit();
- } catch (Exception e) {
- throw new CmsException("Cannot commit transaction " + "after user group membership update", e);
- }
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, myGroup));
- }
- super.drop(event);
- }
-
- @Override
- public boolean performDrop(Object data) {
- // myUserViewerCmp.refresh();
- return true;
- }
- }
-
- // LOCAL HELPERS
- private Composite addSection(FormToolkit tk, Composite parent) {
- Section section = tk.createSection(parent, SWT.NO_FOCUS);
- section.setLayoutData(EclipseUiUtils.fillWidth());
- Composite body = tk.createComposite(section, SWT.WRAP);
- body.setLayoutData(EclipseUiUtils.fillAll());
- section.setClient(body);
- return body;
- }
-
- /** Creates label and text. */
- // private Text createLT(Composite parent, String label, String value) {
- // FormToolkit toolkit = getManagedForm().getToolkit();
- // Label lbl = toolkit.createLabel(parent, label);
- // lbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false));
- // lbl.setFont(EclipseUiUtils.getBoldFont(parent));
- // Text text = toolkit.createText(parent, value, SWT.BORDER);
- // text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- // CmsUiUtils.style(text, CmsWorkbenchStyles.WORKBENCH_FORM_TEXT);
- // return text;
- // }
- //
- Text createReadOnlyLT(Composite parent, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(parent, label);
- lbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false));
- lbl.setFont(EclipseUiUtils.getBoldFont(parent));
- Text text = toolkit.createText(parent, value, SWT.NONE);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- text.setEditable(false);
- CmsSwtUtils.style(text, CmsWorkbenchStyles.WORKBENCH_FORM_TEXT);
- return text;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiUserAdminListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.CommonNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.DomainNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.RoleIconLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserDragListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTableDefaultDClickListener;
-import org.argeo.eclipse.ui.ColumnDefinition;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.parts.LdifUsersTable;
-import org.argeo.util.naming.LdapAttrs;
-import org.argeo.util.naming.LdapObjs;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdminEvent;
-import org.osgi.service.useradmin.UserAdminListener;
-
-/** List all groups with filter */
-public class GroupsView extends ViewPart implements ArgeoNames {
- private final static CmsLog log = CmsLog.getLog(GroupsView.class);
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".groupsView";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- // UI Objects
- private LdifUsersTable groupTableViewerCmp;
- private TableViewer userViewer;
- private List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
-
- private UserAdminListener listener;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
-// boolean isAdmin = CurrentUser.isInRole(NodeConstants.ROLE_ADMIN);
-
- // Define the displayed columns
- columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 19));
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Name", 150));
- columnDefs.add(new ColumnDefinition(new DomainNameLP(), "Domain", 100));
- // Only show technical DN to admin
- // if (isAdmin)
- // columnDefs.add(new ColumnDefinition(new UserNameLP(),
- // "Distinguished Name", 300));
-
- // Create and configure the table
- groupTableViewerCmp = new MyUserTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
-
- groupTableViewerCmp.setColumnDefinitions(columnDefs);
-// if (isAdmin)
-// groupTableViewerCmp.populateWithStaticFilters(false, false);
-// else
- groupTableViewerCmp.populate(true, false);
-
- groupTableViewerCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Links
- userViewer = groupTableViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- getViewSite().setSelectionProvider(userViewer);
-
- // Really?
- groupTableViewerCmp.refresh();
-
- // Drag and drop
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- userViewer.addDragSupport(operations, tt, new UserDragListener(userViewer));
-
- // // Register a useradmin listener
- // listener = new UserAdminListener() {
- // @Override
- // public void roleChanged(UserAdminEvent event) {
- // if (userViewer != null && !userViewer.getTable().isDisposed())
- // refresh();
- // }
- // };
- // userAdminWrapper.addListener(listener);
- // }
-
- // Register a useradmin listener
- listener = new MyUiUAListener(parent.getDisplay());
- userAdminWrapper.addListener(listener);
- }
-
- private class MyUiUAListener extends UiUserAdminListener {
- public MyUiUAListener(Display display) {
- super(display);
- }
-
- @Override
- public void roleChangedToUiThread(UserAdminEvent event) {
- if (userViewer != null && !userViewer.getTable().isDisposed())
- refresh();
- }
- }
-
- private class MyUserTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 8467999509931900367L;
-
- private boolean showSystemRoles = true;
-
- private final String[] knownProps = { LdapAttrs.uid.name(), LdapAttrs.cn.name(), LdapAttrs.DN };
-
- public MyUserTableViewer(Composite parent, int style) {
- super(parent, style);
- showSystemRoles = CurrentUser.isInRole(CmsConstants.ROLE_ADMIN);
- }
-
- protected void populateStaticFilters(Composite staticFilterCmp) {
- staticFilterCmp.setLayout(new GridLayout());
- final Button showSystemRoleBtn = new Button(staticFilterCmp, SWT.CHECK);
- showSystemRoleBtn.setText("Show system roles");
- showSystemRoles = CurrentUser.isInRole(CmsConstants.ROLE_ADMIN);
- showSystemRoleBtn.setSelection(showSystemRoles);
-
- showSystemRoleBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -7033424592697691676L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- showSystemRoles = showSystemRoleBtn.getSelection();
- refresh();
- }
-
- });
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- Role[] roles;
- try {
- StringBuilder builder = new StringBuilder();
- StringBuilder tmpBuilder = new StringBuilder();
- if (EclipseUiUtils.notEmpty(filter))
- for (String prop : knownProps) {
- tmpBuilder.append("(");
- tmpBuilder.append(prop);
- tmpBuilder.append("=*");
- tmpBuilder.append(filter);
- tmpBuilder.append("*)");
- }
- if (tmpBuilder.length() > 1) {
- builder.append("(&(").append(LdapAttrs.objectClass.name()).append("=")
- .append(LdapObjs.groupOfNames.name()).append(")");
- if (!showSystemRoles)
- builder.append("(!(").append(LdapAttrs.DN).append("=*").append(CmsConstants.ROLES_BASEDN)
- .append("))");
- builder.append("(|");
- builder.append(tmpBuilder.toString());
- builder.append("))");
- } else {
- if (!showSystemRoles)
- builder.append("(&(").append(LdapAttrs.objectClass.name()).append("=")
- .append(LdapObjs.groupOfNames.name()).append(")(!(").append(LdapAttrs.DN).append("=*")
- .append(CmsConstants.ROLES_BASEDN).append(")))");
- else
- builder.append("(").append(LdapAttrs.objectClass.name()).append("=")
- .append(LdapObjs.groupOfNames.name()).append(")");
-
- }
- roles = userAdminWrapper.getUserAdmin().getRoles(builder.toString());
- } catch (InvalidSyntaxException e) {
- throw new CmsException("Unable to get roles with filter: " + filter, e);
- }
- List<User> users = new ArrayList<User>();
- for (Role role : roles)
- if (!users.contains(role))
- users.add((User) role);
- else
- log.warn("Duplicated role: " + role);
-
- return users;
- }
- }
-
- public void refresh() {
- groupTableViewerCmp.refresh();
- }
-
- // Override generic view methods
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- @Override
- public void setFocus() {
- groupTableViewerCmp.setFocus();
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiAdminUtils;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.CommonNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.DomainNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.MailLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserNameLP;
-import org.argeo.eclipse.ui.ColumnDefinition;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.parts.LdifUsersTable;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.argeo.util.naming.LdapAttrs;
-import org.argeo.util.naming.LdapObjs;
-import org.eclipse.jface.dialogs.IPageChangeProvider;
-import org.eclipse.jface.dialogs.IPageChangedListener;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.PageChangedEvent;
-import org.eclipse.jface.wizard.IWizardContainer;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Wizard to update users */
-public class UserBatchUpdateWizard extends Wizard {
-
- private final static CmsLog log = CmsLog.getLog(UserBatchUpdateWizard.class);
- private UserAdminWrapper userAdminWrapper;
-
- // pages
- private ChooseCommandWizardPage chooseCommandPage;
- private ChooseUsersWizardPage userListPage;
- private ValidateAndLaunchWizardPage validatePage;
-
- // Various implemented commands keys
- private final static String CMD_UPDATE_PASSWORD = "resetPassword";
- private final static String CMD_UPDATE_EMAIL = "resetEmail";
- private final static String CMD_GROUP_MEMBERSHIP = "groupMembership";
-
- private final Map<String, String> commands = new HashMap<String, String>() {
- private static final long serialVersionUID = 1L;
- {
- put("Reset password(s)", CMD_UPDATE_PASSWORD);
- put("Reset email(s)", CMD_UPDATE_EMAIL);
- // TODO implement role / group management
- // put("Add/Remove from group", CMD_GROUP_MEMBERSHIP);
- }
- };
-
- public UserBatchUpdateWizard(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-
- @Override
- public void addPages() {
- chooseCommandPage = new ChooseCommandWizardPage();
- addPage(chooseCommandPage);
- userListPage = new ChooseUsersWizardPage();
- addPage(userListPage);
- validatePage = new ValidateAndLaunchWizardPage();
- addPage(validatePage);
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- WorkTransaction ut = userAdminWrapper.getUserTransaction();
- if (!ut.isNoTransactionStatus() && !MessageDialog.openConfirm(getShell(), "Existing Transaction",
- "A user transaction is already existing, " + "are you sure you want to proceed ?"))
- return false;
-
- // We cannot use jobs, user modifications are still meant to be done in
- // the UIThread
- // UpdateJob job = null;
- // if (job != null)
- // job.schedule();
-
- if (CMD_UPDATE_PASSWORD.equals(chooseCommandPage.getCommand())) {
- char[] newValue = chooseCommandPage.getPwdValue();
- if (newValue == null)
- throw new CmsException("Password cannot be null or an empty string");
- ResetPassword job = new ResetPassword(userAdminWrapper, userListPage.getSelectedUsers(), newValue);
- job.doUpdate();
- } else if (CMD_UPDATE_EMAIL.equals(chooseCommandPage.getCommand())) {
- String newValue = chooseCommandPage.getEmailValue();
- if (newValue == null)
- throw new CmsException("Password cannot be null or an empty string");
- ResetEmail job = new ResetEmail(userAdminWrapper, userListPage.getSelectedUsers(), newValue);
- job.doUpdate();
- }
- return true;
- }
-
- public boolean canFinish() {
- if (this.getContainer().getCurrentPage() == validatePage)
- return true;
- return false;
- }
-
- private class ResetPassword {
- private char[] newPwd;
- private UserAdminWrapper userAdminWrapper;
- private List<User> usersToUpdate;
-
- public ResetPassword(UserAdminWrapper userAdminWrapper, List<User> usersToUpdate, char[] newPwd) {
- this.newPwd = newPwd;
- this.usersToUpdate = usersToUpdate;
- this.userAdminWrapper = userAdminWrapper;
- }
-
- @SuppressWarnings("unchecked")
- protected void doUpdate() {
- userAdminWrapper.beginTransactionIfNeeded();
- try {
- for (User user : usersToUpdate) {
- // the char array is emptied after being used.
- user.getCredentials().put(null, newPwd.clone());
- }
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- } catch (Exception e) {
- throw new CmsException("Cannot perform batch update on users", e);
- } finally {
- WorkTransaction ut = userAdminWrapper.getUserTransaction();
- if (!ut.isNoTransactionStatus())
- ut.rollback();
- }
- }
- }
-
- private class ResetEmail {
- private String newEmail;
- private UserAdminWrapper userAdminWrapper;
- private List<User> usersToUpdate;
-
- public ResetEmail(UserAdminWrapper userAdminWrapper, List<User> usersToUpdate, String newEmail) {
- this.newEmail = newEmail;
- this.usersToUpdate = usersToUpdate;
- this.userAdminWrapper = userAdminWrapper;
- }
-
- @SuppressWarnings("unchecked")
- protected void doUpdate() {
- userAdminWrapper.beginTransactionIfNeeded();
- try {
- for (User user : usersToUpdate) {
- // the char array is emptied after being used.
- user.getProperties().put(LdapAttrs.mail.name(), newEmail);
- }
-
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- if (!usersToUpdate.isEmpty())
- userAdminWrapper.notifyListeners(
- new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, usersToUpdate.get(0)));
- } catch (Exception e) {
- throw new CmsException("Cannot perform batch update on users", e);
- } finally {
- WorkTransaction ut = userAdminWrapper.getUserTransaction();
- if (!ut.isNoTransactionStatus())
- ut.rollback();
- }
- }
- }
-
- // @SuppressWarnings("unused")
- // private class AddToGroup extends UpdateJob {
- // private String groupID;
- // private Session session;
- //
- // public AddToGroup(Session session, List<Node> nodesToUpdate,
- // String groupID) {
- // super(session, nodesToUpdate);
- // this.session = session;
- // this.groupID = groupID;
- // }
- //
- // protected void doUpdate(Node node) {
- // log.info("Add/Remove to group actions are not yet implemented");
- // // TODO implement this
- // // try {
- // // throw new CmsException("Not yet implemented");
- // // } catch (RepositoryException re) {
- // // throw new CmsException(
- // // "Unable to update boolean value for node " + node, re);
- // // }
- // }
- // }
-
- // /**
- // * Base privileged job that will be run asynchronously to perform the
- // batch
- // * update
- // */
- // private abstract class UpdateJob extends PrivilegedJob {
- //
- // private final UserAdminWrapper userAdminWrapper;
- // private final List<User> usersToUpdate;
- //
- // protected abstract void doUpdate(User user);
- //
- // public UpdateJob(UserAdminWrapper userAdminWrapper,
- // List<User> usersToUpdate) {
- // super("Perform update");
- // this.usersToUpdate = usersToUpdate;
- // this.userAdminWrapper = userAdminWrapper;
- // }
- //
- // @Override
- // protected IStatus doRun(IProgressMonitor progressMonitor) {
- // try {
- // JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- // int total = usersToUpdate.size();
- // monitor.beginTask("Performing change", total);
- // userAdminWrapper.beginTransactionIfNeeded();
- // for (User user : usersToUpdate) {
- // doUpdate(user);
- // monitor.worked(1);
- // }
- // userAdminWrapper.getUserTransaction().commit();
- // } catch (Exception e) {
- // throw new CmsException(
- // "Cannot perform batch update on users", e);
- // } finally {
- // UserTransaction ut = userAdminWrapper.getUserTransaction();
- // try {
- // if (ut.getStatus() != javax.transaction.Status.STATUS_NO_TRANSACTION)
- // ut.rollback();
- // } catch (IllegalStateException | SecurityException
- // | SystemException e) {
- // log.error("Unable to rollback session in 'finally', "
- // + "the system might be in a dirty state");
- // e.printStackTrace();
- // }
- // }
- // return Status.OK_STATUS;
- // }
- // }
-
- // PAGES
- /**
- * Displays a combo box that enables user to choose which action to perform
- */
- private class ChooseCommandWizardPage extends WizardPage {
- private static final long serialVersionUID = -8069434295293996633L;
- private Combo chooseCommandCmb;
- private Button trueChk;
- private Text valueTxt;
- private Text pwdTxt;
- private Text pwd2Txt;
-
- public ChooseCommandWizardPage() {
- super("Choose a command to run.");
- setTitle("Choose a command to run.");
- }
-
- @Override
- public void createControl(Composite parent) {
- GridLayout gl = new GridLayout();
- Composite container = new Composite(parent, SWT.NO_FOCUS);
- container.setLayout(gl);
-
- chooseCommandCmb = new Combo(container, SWT.READ_ONLY);
- chooseCommandCmb.setLayoutData(EclipseUiUtils.fillWidth());
- String[] values = commands.keySet().toArray(new String[0]);
- chooseCommandCmb.setItems(values);
-
- final Composite bottomPart = new Composite(container, SWT.NO_FOCUS);
- bottomPart.setLayoutData(EclipseUiUtils.fillAll());
- bottomPart.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- chooseCommandCmb.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (getCommand().equals(CMD_UPDATE_PASSWORD))
- populatePasswordCmp(bottomPart);
- else if (getCommand().equals(CMD_UPDATE_EMAIL))
- populateEmailCmp(bottomPart);
- else if (getCommand().equals(CMD_GROUP_MEMBERSHIP))
- populateGroupCmp(bottomPart);
- else
- populateBooleanFlagCmp(bottomPart);
- checkPageComplete();
- bottomPart.layout(true, true);
- }
- });
- setControl(container);
- }
-
- private void populateBooleanFlagCmp(Composite parent) {
- EclipseUiUtils.clear(parent);
- trueChk = new Button(parent, SWT.CHECK);
- trueChk.setText("Do it. (It will to the contrary if unchecked)");
- trueChk.setSelection(true);
- trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- }
-
- private void populatePasswordCmp(Composite parent) {
- EclipseUiUtils.clear(parent);
- Composite body = new Composite(parent, SWT.NO_FOCUS);
-
- ModifyListener ml = new ModifyListener() {
- private static final long serialVersionUID = -1558726363536729634L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- checkPageComplete();
- }
- };
-
- body.setLayout(new GridLayout(2, false));
- body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- pwdTxt = EclipseUiUtils.createGridLP(body, "New password", ml);
- pwd2Txt = EclipseUiUtils.createGridLP(body, "Repeat password", ml);
- }
-
- private void populateEmailCmp(Composite parent) {
- EclipseUiUtils.clear(parent);
- Composite body = new Composite(parent, SWT.NO_FOCUS);
-
- ModifyListener ml = new ModifyListener() {
- private static final long serialVersionUID = 2147704227294268317L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- checkPageComplete();
- }
- };
-
- body.setLayout(new GridLayout(2, false));
- body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- valueTxt = EclipseUiUtils.createGridLT(body, "New e-mail", ml);
- }
-
- private void checkPageComplete() {
- String errorMsg = null;
- if (chooseCommandCmb.getSelectionIndex() < 0)
- errorMsg = "Please select an action";
- else if (CMD_UPDATE_EMAIL.equals(getCommand())) {
- if (!valueTxt.getText().matches(UiAdminUtils.EMAIL_PATTERN))
- errorMsg = "Not a valid e-mail address";
- } else if (CMD_UPDATE_PASSWORD.equals(getCommand())) {
- if (EclipseUiUtils.isEmpty(pwdTxt.getText()) || pwdTxt.getText().length() < 4)
- errorMsg = "Please enter a password that is at least 4 character long";
- else if (!pwdTxt.getText().equals(pwd2Txt.getText()))
- errorMsg = "Passwords are different";
- }
- if (EclipseUiUtils.notEmpty(errorMsg)) {
- setMessage(errorMsg, WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Page complete, you can proceed to user choice", WizardPage.INFORMATION);
- setPageComplete(true);
- }
-
- getContainer().updateButtons();
- }
-
- private void populateGroupCmp(Composite parent) {
- EclipseUiUtils.clear(parent);
- trueChk = new Button(parent, SWT.CHECK);
- trueChk.setText("Add to group. (It will remove user(s) from the " + "corresponding group if unchecked)");
- trueChk.setSelection(true);
- trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- }
-
- protected String getCommand() {
- return commands.get(chooseCommandCmb.getItem(chooseCommandCmb.getSelectionIndex()));
- }
-
- protected String getCommandLbl() {
- return chooseCommandCmb.getItem(chooseCommandCmb.getSelectionIndex());
- }
-
- @SuppressWarnings("unused")
- protected boolean getBoleanValue() {
- // FIXME this is not consistent and will lead to errors.
- if ("argeo:enabled".equals(getCommand()))
- return trueChk.getSelection();
- else
- return !trueChk.getSelection();
- }
-
- @SuppressWarnings("unused")
- protected String getStringValue() {
- String value = null;
- if (valueTxt != null) {
- value = valueTxt.getText();
- if ("".equals(value.trim()))
- value = null;
- }
- return value;
- }
-
- protected char[] getPwdValue() {
- // We do not directly reset the password text fields: There is no
- // need to over secure this process: setting a pwd to multi users
- // at the same time is anyhow a bad practice and should be used only
- // in test environment or for temporary access
- if (pwdTxt == null || pwdTxt.isDisposed())
- return null;
- else
- return pwdTxt.getText().toCharArray();
- }
-
- protected String getEmailValue() {
- // We do not directly reset the password text fields: There is no
- // need to over secure this process: setting a pwd to multi users
- // at the same time is anyhow a bad practice and should be used only
- // in test environment or for temporary access
- if (valueTxt == null || valueTxt.isDisposed())
- return null;
- else
- return valueTxt.getText();
- }
- }
-
- /**
- * Displays a list of users with a check box to be able to choose some of them
- */
- private class ChooseUsersWizardPage extends WizardPage implements IPageChangedListener {
- private static final long serialVersionUID = 7651807402211214274L;
- private ChooseUserTableViewer userTableCmp;
-
- public ChooseUsersWizardPage() {
- super("Choose Users");
- setTitle("Select users who will be impacted");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite pageCmp = new Composite(parent, SWT.NONE);
- pageCmp.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- // Define the displayed columns
- List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name", 150));
- columnDefs.add(new ColumnDefinition(new MailLP(), "E-mail", 150));
- columnDefs.add(new ColumnDefinition(new DomainNameLP(), "Domain", 200));
-
- // Only show technical DN to admin
- if (CurrentUser.isInRole(CmsConstants.ROLE_ADMIN))
- columnDefs.add(new ColumnDefinition(new UserNameLP(), "Distinguished Name", 300));
-
- userTableCmp = new ChooseUserTableViewer(pageCmp, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- userTableCmp.setLayoutData(EclipseUiUtils.fillAll());
- userTableCmp.setColumnDefinitions(columnDefs);
- userTableCmp.populate(true, true);
- userTableCmp.refresh();
-
- setControl(pageCmp);
-
- // Add listener to update message when shown
- final IWizardContainer wContainer = this.getContainer();
- if (wContainer instanceof IPageChangeProvider) {
- ((IPageChangeProvider) wContainer).addPageChangedListener(this);
- }
-
- }
-
- @Override
- public void pageChanged(PageChangedEvent event) {
- if (event.getSelectedPage() == this) {
- String msg = "Chosen batch action: " + chooseCommandPage.getCommandLbl();
- ((WizardPage) event.getSelectedPage()).setMessage(msg);
- }
- }
-
- protected List<User> getSelectedUsers() {
- return userTableCmp.getSelectedUsers();
- }
-
- private class ChooseUserTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 5080437561015853124L;
- private final String[] knownProps = { LdapAttrs.uid.name(), LdapAttrs.DN, LdapAttrs.cn.name(),
- LdapAttrs.givenName.name(), LdapAttrs.sn.name(), LdapAttrs.mail.name() };
-
- public ChooseUserTableViewer(Composite parent, int style) {
- super(parent, style);
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- Role[] roles;
-
- try {
- StringBuilder builder = new StringBuilder();
-
- StringBuilder tmpBuilder = new StringBuilder();
- if (EclipseUiUtils.notEmpty(filter))
- for (String prop : knownProps) {
- tmpBuilder.append("(");
- tmpBuilder.append(prop);
- tmpBuilder.append("=*");
- tmpBuilder.append(filter);
- tmpBuilder.append("*)");
- }
- if (tmpBuilder.length() > 1) {
- builder.append("(&(").append(LdapAttrs.objectClass.name()).append("=")
- .append(LdapObjs.inetOrgPerson.name()).append(")(|");
- builder.append(tmpBuilder.toString());
- builder.append("))");
- } else
- builder.append("(").append(LdapAttrs.objectClass.name()).append("=")
- .append(LdapObjs.inetOrgPerson.name()).append(")");
- roles = userAdminWrapper.getUserAdmin().getRoles(builder.toString());
- } catch (InvalidSyntaxException e) {
- throw new CmsException("Unable to get roles with filter: " + filter, e);
- }
- List<User> users = new ArrayList<User>();
- for (Role role : roles)
- // Prevent current logged in user to perform batch on
- // himself
- if (!UserAdminUtils.isCurrentUser((User) role))
- users.add((User) role);
- return users;
- }
- }
- }
-
- /** Summary of input data before launching the process */
- private class ValidateAndLaunchWizardPage extends WizardPage implements IPageChangedListener {
- private static final long serialVersionUID = 7098918351451743853L;
- private ChosenUsersTableViewer userTableCmp;
-
- public ValidateAndLaunchWizardPage() {
- super("Validate and launch");
- setTitle("Validate and launch");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite pageCmp = new Composite(parent, SWT.NO_FOCUS);
- pageCmp.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name", 150));
- columnDefs.add(new ColumnDefinition(new MailLP(), "E-mail", 150));
- columnDefs.add(new ColumnDefinition(new DomainNameLP(), "Domain", 200));
- // Only show technical DN to admin
- if (CurrentUser.isInRole(CmsConstants.ROLE_ADMIN))
- columnDefs.add(new ColumnDefinition(new UserNameLP(), "Distinguished Name", 300));
- userTableCmp = new ChosenUsersTableViewer(pageCmp, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- userTableCmp.setLayoutData(EclipseUiUtils.fillAll());
- userTableCmp.setColumnDefinitions(columnDefs);
- userTableCmp.populate(false, false);
- userTableCmp.refresh();
- setControl(pageCmp);
- // Add listener to update message when shown
- final IWizardContainer wContainer = this.getContainer();
- if (wContainer instanceof IPageChangeProvider) {
- ((IPageChangeProvider) wContainer).addPageChangedListener(this);
- }
- }
-
- @Override
- public void pageChanged(PageChangedEvent event) {
- if (event.getSelectedPage() == this) {
- @SuppressWarnings({ "unchecked", "rawtypes" })
- Object[] values = ((ArrayList) userListPage.getSelectedUsers())
- .toArray(new Object[userListPage.getSelectedUsers().size()]);
- userTableCmp.getTableViewer().setInput(values);
- String msg = "Following batch action: [" + chooseCommandPage.getCommandLbl()
- + "] will be perfomed on the users listed below.\n";
- // + "Are you sure you want to proceed?";
- setMessage(msg);
- }
- }
-
- private class ChosenUsersTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 7814764735794270541L;
-
- public ChosenUsersTableViewer(Composite parent, int style) {
- super(parent, style);
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- return userListPage.getSelectedUsers();
- }
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Repository;
-
-import org.argeo.api.cms.CmsContext;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiUserAdminListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.util.naming.LdapAttrs;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.osgi.service.useradmin.Authorization;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Editor for a user, might be a user or a group. */
-public class UserEditor extends FormEditor {
- private static final long serialVersionUID = 8357851520380820241L;
-
- public final static String USER_EDITOR_ID = WorkbenchUiPlugin.PLUGIN_ID + ".userEditor";
- public final static String GROUP_EDITOR_ID = WorkbenchUiPlugin.PLUGIN_ID + ".groupEditor";
-
- /* DEPENDENCY INJECTION */
- private Repository repository;
- private UserAdminWrapper userAdminWrapper;
- private UserAdmin userAdmin;
- private CmsContext nodeInstance;
-
- // Context
- private User user;
- private String username;
-
- private NameChangeListener listener;
-
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- super.init(site, input);
- this.userAdmin = userAdminWrapper.getUserAdmin();
- username = ((UserEditorInput) getEditorInput()).getUsername();
- user = (User) userAdmin.getRole(username);
-
- listener = new NameChangeListener(site.getShell().getDisplay());
- userAdminWrapper.addListener(listener);
- updateEditorTitle(null);
- }
-
- /**
- * returns the list of all authorization for the given user or of the current
- * displayed user if parameter is null
- */
- protected List<User> getFlatGroups(User aUser) {
- Authorization currAuth;
- if (aUser == null)
- currAuth = userAdmin.getAuthorization(this.user);
- else
- currAuth = userAdmin.getAuthorization(aUser);
-
- String[] roles = currAuth.getRoles();
-
- List<User> groups = new ArrayList<User>();
- for (String roleStr : roles) {
- User currRole = (User) userAdmin.getRole(roleStr);
- if (currRole != null && !groups.contains(currRole))
- groups.add(currRole);
- }
- return groups;
- }
-
- /** Exposes the user (or group) that is displayed by the current editor */
- protected User getDisplayedUser() {
- return user;
- }
-
- private void setDisplayedUser(User user) {
- this.user = user;
- }
-
- void updateEditorTitle(String title) {
- if (title == null) {
- String commonName = UserAdminUtils.getProperty(user, LdapAttrs.cn.name());
- title = "".equals(commonName) ? user.getName() : commonName;
- }
- setPartName(title);
- }
-
- protected void addPages() {
- try {
- if (user.getType() == Role.GROUP)
- addPage(new GroupMainPage(this, userAdminWrapper, repository, nodeInstance));
- else
- addPage(new UserMainPage(this, userAdminWrapper));
- } catch (Exception e) {
- throw new CmsException("Cannot add pages", e);
- }
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- userAdminWrapper.beginTransactionIfNeeded();
- commitPages(true);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- firePropertyChange(PROP_DIRTY);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_REMOVED, user));
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- // CONTROLERS FOR THIS EDITOR AND ITS PAGES
-
- private class NameChangeListener extends UiUserAdminListener {
- public NameChangeListener(Display display) {
- super(display);
- }
-
- @Override
- public void roleChangedToUiThread(UserAdminEvent event) {
- Role changedRole = event.getRole();
- if (changedRole == null || changedRole.equals(user)) {
- updateEditorTitle(null);
- User reloadedUser = (User) userAdminWrapper.getUserAdmin().getRole(user.getName());
- setDisplayedUser(reloadedUser);
- }
- }
- }
-
- class MainInfoListener extends UiUserAdminListener {
- private final AbstractFormPart part;
-
- public MainInfoListener(Display display, AbstractFormPart part) {
- super(display);
- this.part = part;
- }
-
- @Override
- public void roleChangedToUiThread(UserAdminEvent event) {
- // Rollback
- if (event.getRole() == null)
- part.markStale();
- }
- }
-
- class GroupChangeListener extends UiUserAdminListener {
- private final AbstractFormPart part;
-
- public GroupChangeListener(Display display, AbstractFormPart part) {
- super(display);
- this.part = part;
- }
-
- @Override
- public void roleChangedToUiThread(UserAdminEvent event) {
- // always mark as stale
- part.markStale();
- }
- }
-
- /** Registers a listener that will notify this part */
- class FormPartML implements ModifyListener {
- private static final long serialVersionUID = 6299808129505381333L;
- private AbstractFormPart formPart;
-
- public FormPartML(AbstractFormPart generalPart) {
- this.formPart = generalPart;
- }
-
- public void modifyText(ModifyEvent e) {
- // Discard event when the control does not have the focus, typically
- // to avoid all editors being marked as dirty during a Rollback
- if (((Control) e.widget).isFocusControl())
- formPart.markDirty();
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-
- public void setNodeInstance(CmsContext nodeInstance) {
- this.nodeInstance = nodeInstance;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/**
- * Editor input for an user defined by unique name (usually a distinguished
- * name).
- */
-public class UserEditorInput implements IEditorInput {
- private final String username;
-
- public UserEditorInput(String username) {
- this.username = username;
- }
-
- @SuppressWarnings("unchecked")
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return username != null;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return username != null ? username : "<new user>";
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return username != null ? username : "<new user>";
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof UserEditorInput))
- return false;
- if (((UserEditorInput) obj).getUsername() == null)
- return false;
- return ((UserEditorInput) obj).getUsername().equals(username);
- }
-
- public String getUsername() {
- return username;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import static org.argeo.cms.auth.UserAdminUtils.getProperty;
-import static org.argeo.util.naming.LdapAttrs.cn;
-import static org.argeo.util.naming.LdapAttrs.givenName;
-import static org.argeo.util.naming.LdapAttrs.mail;
-import static org.argeo.util.naming.LdapAttrs.sn;
-import static org.argeo.util.naming.LdapAttrs.uid;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.ui.workbench.CmsWorkbenchStyles;
-import org.argeo.cms.ui.workbench.internal.useradmin.SecurityAdminImages;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor.GroupChangeListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor.MainInfoListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.CommonNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.DomainNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.RoleIconLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserFilter;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTableDefaultDClickListener;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.cms.swt.CmsSwtUtils;
-import org.argeo.eclipse.ui.ColumnDefinition;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.parts.LdifUsersTable;
-import org.argeo.util.naming.LdapAttrs;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TrayDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Display/edit the properties of a given user */
-public class UserMainPage extends FormPage implements ArgeoNames {
- final static String ID = "UserEditor.mainPage";
-
- private final UserEditor editor;
- private UserAdminWrapper userAdminWrapper;
-
- // Local configuration
- private final int PRE_TITLE_INDENT = 10;
-
- public UserMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper) {
- super(editor, ID, "Main");
- this.editor = (UserEditor) editor;
- this.userAdminWrapper = userAdminWrapper;
- }
-
- protected void createFormContent(final IManagedForm mf) {
- ScrolledForm form = mf.getForm();
- Composite body = form.getBody();
- GridLayout mainLayout = new GridLayout();
- // mainLayout.marginRight = 10;
- body.setLayout(mainLayout);
- User user = editor.getDisplayedUser();
- appendOverviewPart(body, user);
- // Remove to ability to force the password for his own user. The user
- // must then use the change pwd feature
- appendMemberOfPart(body, user);
- }
-
- /** Creates the general section */
- private void appendOverviewPart(final Composite parent, final User user) {
- FormToolkit tk = getManagedForm().getToolkit();
-
- Section section = tk.createSection(parent, SWT.NO_FOCUS);
- GridData gd = EclipseUiUtils.fillWidth();
- // gd.verticalAlignment = PRE_TITLE_INDENT;
- section.setLayoutData(gd);
- Composite body = tk.createComposite(section, SWT.WRAP);
- body.setLayoutData(EclipseUiUtils.fillAll());
- section.setClient(body);
- // body.setLayout(new GridLayout(6, false));
- body.setLayout(new GridLayout(2, false));
-
- Text commonName = createReadOnlyLT(tk, body, "Name", getProperty(user, cn));
- Text distinguishedName = createReadOnlyLT(tk, body, "Login", getProperty(user, uid));
- Text firstName = createLT(tk, body, "First name", getProperty(user, givenName));
- Text lastName = createLT(tk, body, "Last name", getProperty(user, sn));
- Text email = createLT(tk, body, "Email", getProperty(user, mail));
-
- Link resetPwdLk = new Link(body, SWT.NONE);
- if (!UserAdminUtils.isCurrentUser(user)) {
- resetPwdLk.setText("<a>Reset password</a>");
- }
- resetPwdLk.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
-
- // create form part (controller)
- AbstractFormPart part = new SectionPart((Section) body.getParent()) {
- private MainInfoListener listener;
-
- @Override
- public void initialize(IManagedForm form) {
- super.initialize(form);
- listener = editor.new MainInfoListener(parent.getDisplay(), this);
- userAdminWrapper.addListener(listener);
- }
-
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- @SuppressWarnings("unchecked")
- public void commit(boolean onSave) {
- // TODO Sanity checks (mail validity...)
- user.getProperties().put(LdapAttrs.givenName.name(), firstName.getText());
- user.getProperties().put(LdapAttrs.sn.name(), lastName.getText());
- user.getProperties().put(LdapAttrs.cn.name(), commonName.getText());
- user.getProperties().put(LdapAttrs.mail.name(), email.getText());
- super.commit(onSave);
- }
-
- @Override
- public void refresh() {
- distinguishedName.setText(UserAdminUtils.getProperty(user, LdapAttrs.uid.name()));
- commonName.setText(UserAdminUtils.getProperty(user, LdapAttrs.cn.name()));
- firstName.setText(UserAdminUtils.getProperty(user, LdapAttrs.givenName.name()));
- lastName.setText(UserAdminUtils.getProperty(user, LdapAttrs.sn.name()));
- email.setText(UserAdminUtils.getProperty(user, LdapAttrs.mail.name()));
- refreshFormTitle(user);
- super.refresh();
- }
- };
-
- // Improve this: automatically generate CN when first or last name
- // changes
- ModifyListener cnML = new ModifyListener() {
- private static final long serialVersionUID = 4298649222869835486L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String first = firstName.getText();
- String last = lastName.getText();
- String cn = first.trim() + " " + last.trim() + " ";
- cn = cn.trim();
- commonName.setText(cn);
- // getManagedForm().getForm().setText(cn);
- editor.updateEditorTitle(cn);
- }
- };
- firstName.addModifyListener(cnML);
- lastName.addModifyListener(cnML);
-
- ModifyListener defaultListener = editor.new FormPartML(part);
- firstName.addModifyListener(defaultListener);
- lastName.addModifyListener(defaultListener);
- email.addModifyListener(defaultListener);
-
- if (!UserAdminUtils.isCurrentUser(user))
- resetPwdLk.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = 5881800534589073787L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- new ChangePasswordDialog(tk, user, "Reset password").open();
- }
- });
-
- getManagedForm().addPart(part);
- }
-
- private class ChangePasswordDialog extends TrayDialog {
- private static final long serialVersionUID = 2843538207460082349L;
-
- private User user;
- private Text password1;
- private Text password2;
- private String title;
- private FormToolkit tk;
-
- public ChangePasswordDialog(FormToolkit tk, User user, String title) {
- super(Display.getDefault().getActiveShell());
- this.tk = tk;
- this.user = user;
- this.title = title;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Composite body = new Composite(dialogarea, SWT.NO_FOCUS);
- body.setLayoutData(EclipseUiUtils.fillAll());
- GridLayout layout = new GridLayout(2, false);
- body.setLayout(layout);
-
- password1 = createLP(tk, body, "New password", "");
- password2 = createLP(tk, body, "Repeat password", "");
- parent.pack();
- return body;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected void okPressed() {
- String msg = null;
-
- if (password1.getText().equals(""))
- msg = "Password cannot be empty";
- else if (password1.getText().equals(password2.getText())) {
- char[] newPassword = password1.getText().toCharArray();
- // userAdminWrapper.beginTransactionIfNeeded();
- userAdminWrapper.beginTransactionIfNeeded();
- user.getCredentials().put(null, newPassword);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- super.okPressed();
- } else {
- msg = "Passwords are not equals";
- }
-
- if (EclipseUiUtils.notEmpty(msg))
- MessageDialog.openError(getParentShell(), "Cannot reset pasword", msg);
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText(title);
- }
- }
-
- private LdifUsersTable appendMemberOfPart(final Composite parent, User user) {
- FormToolkit tk = getManagedForm().getToolkit();
- Section section = addSection(tk, parent, "Roles");
- Composite body = (Composite) section.getClient();
- body.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- // boolean isAdmin = CurrentUser.isInRole(NodeConstants.ROLE_ADMIN);
-
- // Displayed columns
- List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
- columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Name", 150));
- columnDefs.add(new ColumnDefinition(new DomainNameLP(), "Domain", 100));
- // Only show technical DN to administrators
- // if (isAdmin)
- // columnDefs.add(new ColumnDefinition(new UserNameLP(), "Distinguished Name",
- // 300));
-
- // Create and configure the table
- final LdifUsersTable userViewerCmp = new MyUserTableViewer(body, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, user);
-
- userViewerCmp.setColumnDefinitions(columnDefs);
- // if (isAdmin)
- // userViewerCmp.populateWithStaticFilters(false, false);
- // else
- userViewerCmp.populate(true, false);
- GridData gd = EclipseUiUtils.fillAll();
- gd.heightHint = 500;
- userViewerCmp.setLayoutData(gd);
-
- // Controllers
- TableViewer userViewer = userViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- GroupDropListener dropL = new GroupDropListener(userAdminWrapper, userViewer, user);
- userViewer.addDropSupport(operations, tt, dropL);
-
- SectionPart part = new SectionPart((Section) body.getParent()) {
-
- private GroupChangeListener listener;
-
- @Override
- public void initialize(IManagedForm form) {
- super.initialize(form);
- listener = editor.new GroupChangeListener(parent.getDisplay(), this);
- userAdminWrapper.addListener(listener);
- }
-
- public void commit(boolean onSave) {
- super.commit(onSave);
- }
-
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- @Override
- public void refresh() {
- userViewerCmp.refresh();
- super.refresh();
- }
- };
- getManagedForm().addPart(part);
- addRemoveAbitily(part, userViewer, user);
- return userViewerCmp;
- }
-
- private class MyUserTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 2653790051461237329L;
-
- private Button showSystemRoleBtn;
-
- private final User user;
- private final UserFilter userFilter;
-
- public MyUserTableViewer(Composite parent, int style, User user) {
- super(parent, style, true);
- this.user = user;
- userFilter = new UserFilter();
- }
-
- protected void populateStaticFilters(Composite staticFilterCmp) {
- staticFilterCmp.setLayout(new GridLayout());
- showSystemRoleBtn = new Button(staticFilterCmp, SWT.CHECK);
- showSystemRoleBtn.setText("Show system roles");
- boolean showSysRole = CurrentUser.isInRole(CmsConstants.ROLE_ADMIN);
- showSystemRoleBtn.setSelection(showSysRole);
- userFilter.setShowSystemRole(showSysRole);
- showSystemRoleBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -7033424592697691676L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- userFilter.setShowSystemRole(showSystemRoleBtn.getSelection());
- refresh();
- }
- });
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- List<User> users = (List<User>) editor.getFlatGroups(null);
- List<User> filteredUsers = new ArrayList<User>();
- if (users.contains(user))
- users.remove(user);
- userFilter.setSearchText(filter);
- for (User user : users)
- if (userFilter.select(null, null, user))
- filteredUsers.add(user);
- return filteredUsers;
- }
- }
-
- private void addRemoveAbitily(SectionPart sectionPart, TableViewer userViewer, User user) {
- Section section = sectionPart.getSection();
- ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
- ToolBar toolbar = toolBarManager.createControl(section);
- final Cursor handCursor = new Cursor(section.getDisplay(), SWT.CURSOR_HAND);
- toolbar.setCursor(handCursor);
- toolbar.addDisposeListener(new DisposeListener() {
- private static final long serialVersionUID = 3882131405820522925L;
-
- public void widgetDisposed(DisposeEvent e) {
- if ((handCursor != null) && (handCursor.isDisposed() == false)) {
- handCursor.dispose();
- }
- }
- });
-
- String tooltip = "Remove " + UserAdminUtils.getUserLocalId(user.getName()) + " from the below selected groups";
- Action action = new RemoveMembershipAction(userViewer, user, tooltip, SecurityAdminImages.ICON_REMOVE_DESC);
- toolBarManager.add(action);
- toolBarManager.update(true);
- section.setTextClient(toolbar);
- }
-
- private class RemoveMembershipAction extends Action {
- private static final long serialVersionUID = -1337713097184522588L;
-
- private final TableViewer userViewer;
- private final User user;
-
- RemoveMembershipAction(TableViewer userViewer, User user, String name, ImageDescriptor img) {
- super(name, img);
- this.userViewer = userViewer;
- this.user = user;
- }
-
- @Override
- public void run() {
- ISelection selection = userViewer.getSelection();
- if (selection.isEmpty())
- return;
-
- @SuppressWarnings("unchecked")
- Iterator<Group> it = ((IStructuredSelection) selection).iterator();
- List<Group> groups = new ArrayList<Group>();
- while (it.hasNext()) {
- Group currGroup = it.next();
- groups.add(currGroup);
- }
-
- userAdminWrapper.beginTransactionIfNeeded();
- for (Group group : groups) {
- group.removeMember(user);
- }
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- for (Group group : groups) {
- userAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, group));
- }
- }
- }
-
- /**
- * Defines the table as being a potential target to add group memberships
- * (roles) to this user
- */
- private class GroupDropListener extends ViewerDropAdapter {
- private static final long serialVersionUID = 2893468717831451621L;
-
- private final UserAdminWrapper myUserAdminWrapper;
- private final User myUser;
-
- public GroupDropListener(UserAdminWrapper userAdminWrapper, Viewer userViewer, User user) {
- super(userViewer);
- this.myUserAdminWrapper = userAdminWrapper;
- this.myUser = user;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation, TransferData transferType) {
- // Target is always OK in a list only view
- // TODO check if not a string
- boolean validDrop = true;
- return validDrop;
- }
-
- @Override
- public void drop(DropTargetEvent event) {
- String name = (String) event.data;
- UserAdmin myUserAdmin = myUserAdminWrapper.getUserAdmin();
- Role role = myUserAdmin.getRole(name);
- // TODO this check should be done before.
- if (role.getType() == Role.GROUP) {
- // TODO check if the user is already member of this group
-
- myUserAdminWrapper.beginTransactionIfNeeded();
- Group group = (Group) role;
- group.addMember(myUser);
- userAdminWrapper.commitOrNotifyTransactionStateChange();
- myUserAdminWrapper.notifyListeners(new UserAdminEvent(null, UserAdminEvent.ROLE_CHANGED, group));
- }
- super.drop(event);
- }
-
- @Override
- public boolean performDrop(Object data) {
- // userTableViewerCmp.refresh();
- return true;
- }
- }
-
- // LOCAL HELPERS
- private void refreshFormTitle(User group) {
- // getManagedForm().getForm().setText(UserAdminUtils.getProperty(group,
- // LdapAttrs.cn.name()));
- }
-
- /** Appends a section with a title */
- private Section addSection(FormToolkit tk, Composite parent, String title) {
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- GridData gd = EclipseUiUtils.fillWidth();
- gd.verticalAlignment = PRE_TITLE_INDENT;
- section.setLayoutData(gd);
- section.setText(title);
- // section.getMenu().setVisible(true);
-
- Composite body = tk.createComposite(section, SWT.WRAP);
- body.setLayoutData(EclipseUiUtils.fillAll());
- section.setClient(body);
-
- return section;
- }
-
- /** Creates label and multiline text. */
- Text createLMT(FormToolkit toolkit, Composite body, String label, String value) {
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.MULTI);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
- return text;
- }
-
- /** Creates label and password. */
- Text createLP(FormToolkit toolkit, Composite body, String label, String value) {
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.PASSWORD);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- /** Creates label and text. */
- Text createLT(FormToolkit toolkit, Composite parent, String label, String value) {
- Label lbl = toolkit.createLabel(parent, label);
- lbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false));
- lbl.setFont(EclipseUiUtils.getBoldFont(parent));
- Text text = toolkit.createText(parent, value, SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- CmsSwtUtils.style(text, CmsWorkbenchStyles.WORKBENCH_FORM_TEXT);
- return text;
- }
-
- Text createReadOnlyLT(FormToolkit toolkit, Composite parent, String label, String value) {
- Label lbl = toolkit.createLabel(parent, label);
- lbl.setLayoutData(new GridData(SWT.LEAD, SWT.CENTER, false, false));
- lbl.setFont(EclipseUiUtils.getBoldFont(parent));
- Text text = toolkit.createText(parent, value, SWT.NONE);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- text.setEditable(false);
- CmsSwtUtils.style(text, CmsWorkbenchStyles.WORKBENCH_FORM_TEXT);
- return text;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.parts;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.UiUserAdminListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.UserAdminWrapper;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.CommonNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.DomainNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.MailLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserDragListener;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserNameLP;
-import org.argeo.cms.ui.workbench.internal.useradmin.providers.UserTableDefaultDClickListener;
-import org.argeo.eclipse.ui.ColumnDefinition;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.parts.LdifUsersTable;
-import org.argeo.util.naming.LdapAttrs;
-import org.argeo.util.naming.LdapObjs;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdminEvent;
-import org.osgi.service.useradmin.UserAdminListener;
-
-/** List all users with filter - based on Ldif userAdmin */
-public class UsersView extends ViewPart implements ArgeoNames {
- // private final static CmsLog log = CmsLog.getLog(UsersView.class);
-
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".usersView";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- // UI Objects
- private LdifUsersTable userTableViewerCmp;
- private TableViewer userViewer;
- private List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
-
- private UserAdminListener listener;
-
- @Override
- public void createPartControl(Composite parent) {
-
- parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
- // Define the displayed columns
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name",
- 150));
- columnDefs.add(new ColumnDefinition(new MailLP(), "E-mail", 150));
- columnDefs.add(new ColumnDefinition(new DomainNameLP(), "Domain", 200));
- // Only show technical DN to admin
- if (CurrentUser.isInRole(CmsConstants.ROLE_ADMIN))
- columnDefs.add(new ColumnDefinition(new UserNameLP(),
- "Distinguished Name", 300));
-
- // Create and configure the table
- userTableViewerCmp = new MyUserTableViewer(parent, SWT.MULTI
- | SWT.H_SCROLL | SWT.V_SCROLL);
- userTableViewerCmp.setLayoutData(EclipseUiUtils.fillAll());
- userTableViewerCmp.setColumnDefinitions(columnDefs);
- userTableViewerCmp.populate(true, false);
-
- // Links
- userViewer = userTableViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- getViewSite().setSelectionProvider(userViewer);
-
- // Really?
- userTableViewerCmp.refresh();
-
- // Drag and drop
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- userViewer.addDragSupport(operations, tt, new UserDragListener(
- userViewer));
-
- // Register a useradmin listener
- listener = new MyUiUAListener(parent.getDisplay());
- userAdminWrapper.addListener(listener);
- }
-
- private class MyUiUAListener extends UiUserAdminListener {
- public MyUiUAListener(Display display) {
- super(display);
- }
-
- @Override
- public void roleChangedToUiThread(UserAdminEvent event) {
- if (userViewer != null && !userViewer.getTable().isDisposed())
- refresh();
- }
- }
-
- private class MyUserTableViewer extends LdifUsersTable {
- private static final long serialVersionUID = 8467999509931900367L;
-
- private final String[] knownProps = { LdapAttrs.DN,
- LdapAttrs.uid.name(), LdapAttrs.cn.name(),
- LdapAttrs.givenName.name(), LdapAttrs.sn.name(),
- LdapAttrs.mail.name() };
-
- public MyUserTableViewer(Composite parent, int style) {
- super(parent, style);
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- Role[] roles;
-
- try {
- StringBuilder builder = new StringBuilder();
-
- StringBuilder tmpBuilder = new StringBuilder();
- if (EclipseUiUtils.notEmpty(filter))
- for (String prop : knownProps) {
- tmpBuilder.append("(");
- tmpBuilder.append(prop);
- tmpBuilder.append("=*");
- tmpBuilder.append(filter);
- tmpBuilder.append("*)");
- }
- if (tmpBuilder.length() > 1) {
- builder.append("(&(").append(LdapAttrs.objectClass.name())
- .append("=").append(LdapObjs.inetOrgPerson.name())
- .append(")(|");
- builder.append(tmpBuilder.toString());
- builder.append("))");
- } else
- builder.append("(").append(LdapAttrs.objectClass.name())
- .append("=").append(LdapObjs.inetOrgPerson.name())
- .append(")");
- roles = userAdminWrapper.getUserAdmin().getRoles(
- builder.toString());
- } catch (InvalidSyntaxException e) {
- throw new CmsException("Unable to get roles with filter: "
- + filter, e);
- }
- List<User> users = new ArrayList<User>();
- for (Role role : roles)
- // if (role.getType() == Role.USER && role.getType() !=
- // Role.GROUP)
- users.add((User) role);
- return users;
- }
- }
-
- public void refresh() {
- userTableViewerCmp.refresh();
- }
-
- // Override generic view methods
- @Override
- public void dispose() {
- userAdminWrapper.removeListener(listener);
- super.dispose();
- }
-
- @Override
- public void setFocus() {
- userTableViewerCmp.setFocus();
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.util.naming.LdapAttrs;
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the common name of a user */
-public class CommonNameLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 5256703081044911941L;
-
- @Override
- public String getText(User user) {
- return UserAdminUtils.getProperty(user, LdapAttrs.cn.name());
- }
-
- @Override
- public String getToolTipText(Object element) {
- return UserAdminUtils.getProperty((User) element, LdapAttrs.DN);
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.argeo.cms.auth.UserAdminUtils;
-import org.osgi.service.useradmin.User;
-
-/** The human friendly domain name for the corresponding user. */
-public class DomainNameLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 5256703081044911941L;
-
- @Override
- public String getText(User user) {
- return UserAdminUtils.getDomainName(user);
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.util.naming.LdapAttrs;
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the Primary Mail of a user */
-public class MailLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 8329764452141982707L;
-
- @Override
- public String getText(User user) {
- return UserAdminUtils.getProperty(user, LdapAttrs.mail.name());
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.argeo.cms.ui.workbench.internal.useradmin.SecurityAdminImages;
-import org.argeo.util.naming.LdapAttrs;
-import org.argeo.api.cms.CmsContext;
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.eclipse.swt.graphics.Image;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-
-/** Provide a bundle specific image depending on the current user type */
-public class RoleIconLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 6550449442061090388L;
-
- @Override
- public String getText(User user) {
- return "";
- }
-
- @Override
- public Image getImage(Object element) {
- User user = (User) element;
- String dn = user.getName();
- if (dn.endsWith(CmsConstants.ROLES_BASEDN))
- return SecurityAdminImages.ICON_ROLE;
- else if (user.getType() == Role.GROUP) {
- String businessCategory = UserAdminUtils.getProperty(user, LdapAttrs.businessCategory);
- if (businessCategory != null && businessCategory.equals(CmsContext.WORKGROUP))
- return SecurityAdminImages.ICON_WORKGROUP;
- return SecurityAdminImages.ICON_GROUP;
- } else
- return SecurityAdminImages.ICON_USER;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-
-import org.argeo.cms.CmsException;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Display;
-import org.osgi.service.useradmin.User;
-
-/**
- * Utility class that add font modifications to a column label provider
- * depending on the given user properties
- */
-public abstract class UserAdminAbstractLP extends ColumnLabelProvider {
- private static final long serialVersionUID = 137336765024922368L;
-
- // private Font italic;
- private Font bold;
-
- @Override
- public Font getFont(Object element) {
- // Self as bold
- try {
- LdapName selfUserName = UserAdminUtils.getCurrentUserLdapName();
- String userName = ((User) element).getName();
- LdapName userLdapName = new LdapName(userName);
- if (userLdapName.equals(selfUserName)) {
- if (bold == null)
- bold = JFaceResources.getFontRegistry()
- .defaultFontDescriptor().setStyle(SWT.BOLD)
- .createFont(Display.getCurrent());
- return bold;
- }
- } catch (InvalidNameException e) {
- throw new CmsException("cannot parse dn for " + element, e);
- }
-
- // Disabled as Italic
- // Node userProfile = (Node) elem;
- // if (!userProfile.getProperty(ARGEO_ENABLED).getBoolean())
- // return italic;
-
- return null;
- // return super.getFont(element);
- }
-
- @Override
- public String getText(Object element) {
- User user = (User) element;
- return getText(user);
- }
-
- public void setDisplay(Display display) {
- // italic = JFaceResources.getFontRegistry().defaultFontDescriptor()
- // .setStyle(SWT.ITALIC).createFont(display);
- bold = JFaceResources.getFontRegistry().defaultFontDescriptor()
- .setStyle(SWT.BOLD).createFont(Display.getCurrent());
- }
-
- public abstract String getText(User user);
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.osgi.service.useradmin.User;
-
-/** Default drag listener to modify group and users via the UI */
-public class UserDragListener implements DragSourceListener {
- private static final long serialVersionUID = -2074337775033781454L;
- private final Viewer viewer;
-
- public UserDragListener(Viewer viewer) {
- this.viewer = viewer;
- }
-
- public void dragStart(DragSourceEvent event) {
- // TODO implement finer checks
- IStructuredSelection selection = (IStructuredSelection) viewer
- .getSelection();
- if (selection.isEmpty() || selection.size() > 1)
- event.doit = false;
- else
- event.doit = true;
- }
-
- public void dragSetData(DragSourceEvent event) {
- // TODO Support multiple selection
- Object obj = ((IStructuredSelection) viewer.getSelection())
- .getFirstElement();
- if (obj != null) {
- User user = (User) obj;
- event.data = user.getName();
- }
- }
-
- public void dragFinished(DragSourceEvent event) {
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import static org.argeo.eclipse.ui.EclipseUiUtils.notEmpty;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.auth.UserAdminUtils;
-import org.argeo.util.naming.LdapAttrs;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.osgi.service.useradmin.User;
-
-/**
- * Filter user list using JFace mechanism on the client (yet on the server) side
- * rather than having the UserAdmin to process the search
- */
-public class UserFilter extends ViewerFilter {
- private static final long serialVersionUID = 5082509381672880568L;
-
- private String searchString;
- private boolean showSystemRole = true;
-
- private final String[] knownProps = { LdapAttrs.DN, LdapAttrs.cn.name(), LdapAttrs.givenName.name(),
- LdapAttrs.sn.name(), LdapAttrs.uid.name(), LdapAttrs.description.name(), LdapAttrs.mail.name() };
-
- public void setSearchText(String s) {
- // ensure that the value can be used for matching
- if (notEmpty(s))
- searchString = ".*" + s.toLowerCase() + ".*";
- else
- searchString = ".*";
- }
-
- public void setShowSystemRole(boolean showSystemRole) {
- this.showSystemRole = showSystemRole;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- User user = (User) element;
- if (!showSystemRole && user.getName().matches(".*(" + CmsConstants.ROLES_BASEDN + ")"))
- // UserAdminUtils.getProperty(user, LdifName.dn.name())
- // .toLowerCase().endsWith(AuthConstants.ROLES_BASEDN))
- return false;
-
- if (searchString == null || searchString.length() == 0)
- return true;
-
- if (user.getName().matches(searchString))
- return true;
-
- for (String key : knownProps) {
- String currVal = UserAdminUtils.getProperty(user, key);
- if (notEmpty(currVal) && currVal.toLowerCase().matches(searchString))
- return true;
- }
- return false;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the username of a user */
-public class UserNameLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 6550449442061090388L;
-
- @Override
- public String getText(User user) {
- return user.getName();
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditor;
-import org.argeo.cms.ui.workbench.internal.useradmin.parts.UserEditorInput;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.User;
-
-/**
- * Default double click listener for the various user tables, will open the
- * clicked item in the editor
- */
-public class UserTableDefaultDClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- if (evt.getSelection().isEmpty())
- return;
- Object obj = ((IStructuredSelection) evt.getSelection())
- .getFirstElement();
- User user = (User) obj;
- IWorkbenchWindow iww = WorkbenchUiPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
- IWorkbenchPage iwp = iww.getActivePage();
- UserEditorInput uei = new UserEditorInput(user.getName());
-
- try {
- // Works around the fact that dynamic setting of the editor icon
- // causes NPE after a login/logout on RAP
- if (user instanceof Group)
- iwp.openEditor(uei, UserEditor.GROUP_EDITOR_ID);
- else
- iwp.openEditor(uei, UserEditor.USER_EDITOR_ID);
- } catch (PartInitException pie) {
- throw new CmsException("Unable to open UserEditor for " + user, pie);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.internal.useradmin.providers;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.eclipse.ui.AbstractSourceProvider;
-import org.eclipse.ui.ISources;
-
-/** Observe and notify UI on UserTransaction state changes */
-public class UserTransactionProvider extends AbstractSourceProvider {
- private final static CmsLog log = CmsLog
- .getLog(UserTransactionProvider.class);
-
- public final static String TRANSACTION_STATE = WorkbenchUiPlugin.PLUGIN_ID
- + ".userTransactionState";
- public final static String STATUS_ACTIVE = "status.active";
- public final static String STATUS_NO_TRANSACTION = "status.noTransaction";
-
- /* DEPENDENCY INJECTION */
- private WorkTransaction userTransaction;
-
- @Override
- public String[] getProvidedSourceNames() {
- return new String[] { TRANSACTION_STATE };
- }
-
- @Override
- public Map<String, String> getCurrentState() {
- Map<String, String> currentState = new HashMap<String, String>(1);
- currentState.put(TRANSACTION_STATE, getInternalCurrentState());
- return currentState;
- }
-
- @Override
- public void dispose() {
- }
-
- private String getInternalCurrentState() {
- try {
- String transactionState;
- if (userTransaction.isNoTransactionStatus())
- transactionState = STATUS_NO_TRANSACTION;
- else
- // if (userTransaction.getStatus() == Status.STATUS_ACTIVE)
- transactionState = STATUS_ACTIVE;
- return transactionState;
- } catch (Exception e) {
- throw new CmsException("Unable to begin transaction", e);
- }
- }
-
- /** Publishes the ability to notify a state change */
- public void fireTransactionStateChange() {
- try {
- fireSourceChanged(ISources.WORKBENCH, TRANSACTION_STATE,
- getInternalCurrentState());
- } catch (Exception e) {
- log.warn("Cannot fire transaction state change event. Caught exception: "
- + e.getClass().getCanonicalName() + " - " + e.getMessage());
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserTransaction(WorkTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.jcr;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.security.AccessControlManager;
-import javax.jcr.security.Privilege;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.ChildNodesPage;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.GenericNodeEditorInput;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.GenericNodePage;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.GenericPropertyPage;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.NodePrivilegesPage;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.NodeVersionHistoryPage;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.FormEditor;
-
-/** Default form editor for a Jcr {@link Node} */
-public class DefaultNodeEditor extends FormEditor {
- private static final long serialVersionUID = 8322127770921612239L;
-
- // private final static Log log =
- // LogFactory.getLog(GenericNodeEditor.class);
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".defaultNodeEditor";
-
- private Node currentNode;
-
- private GenericNodePage genericNodePage;
- private GenericPropertyPage genericPropertyPage;
- private ChildNodesPage childNodesPage;
- private NodePrivilegesPage nodeRightsManagementPage;
- private NodeVersionHistoryPage nodeVersionHistoryPage;
-
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- super.init(site, input);
- GenericNodeEditorInput nei = (GenericNodeEditorInput) getEditorInput();
- currentNode = nei.getCurrentNode();
- this.setPartName(JcrUtils.lastPathElement(nei.getPath()));
- }
-
- @Override
- protected void addPages() {
- try {
- genericPropertyPage = new GenericPropertyPage(this,
- WorkbenchUiPlugin.getMessage("genericNodePageTitle"),
- currentNode);
- addPage(genericPropertyPage);
-
- childNodesPage = new ChildNodesPage(this,
- WorkbenchUiPlugin.getMessage("childNodesPageTitle"),
- currentNode);
- addPage(childNodesPage);
-
- AccessControlManager accessControlManager = currentNode
- .getSession().getAccessControlManager();
- List<Privilege> privileges = new ArrayList<Privilege>();
- privileges.add(accessControlManager
- .privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL));
- if (accessControlManager.hasPrivileges(currentNode.getPath(),
- privileges.toArray(new Privilege[0]))) {
- nodeRightsManagementPage = new NodePrivilegesPage(this,
- WorkbenchUiPlugin
- .getMessage("nodeRightsManagementPageTitle"),
- currentNode);
- addPage(nodeRightsManagementPage);
- }
- if (currentNode.isNodeType(NodeType.MIX_VERSIONABLE)) {
- nodeVersionHistoryPage = new NodeVersionHistoryPage(this,
- WorkbenchUiPlugin
- .getMessage("nodeVersionHistoryPageTitle"),
- currentNode);
- addPage(nodeVersionHistoryPage);
- }
-
- privileges = new ArrayList<Privilege>();
- privileges.add(accessControlManager
- .privilegeFromName(Privilege.JCR_ALL));
- if (accessControlManager.hasPrivileges(currentNode.getPath(),
- privileges.toArray(new Privilege[0]))) {
- genericNodePage = new GenericNodePage(
- this,
- WorkbenchUiPlugin.getMessage("propertyEditorPageTitle"),
- currentNode);
- addPage(genericNodePage);
- }
-
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot get node info for "
- + currentNode, e);
- } catch (PartInitException e) {
- throw new EclipseUiException("Cannot add page "
- + "on node editor for " + currentNode, e);
- }
- }
-
- @Override
- public void doSaveAs() {
- // unused compulsory method
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- try {
- // Automatically commit all pages of the editor
- commitPages(true);
- firePropertyChange(PROP_DIRTY);
- } catch (Exception e) {
- throw new EclipseUiException("Error while saving node", e);
- }
-
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- Node getCurrentNode() {
- return currentNode;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.jcr;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.AbstractJcrQueryEditor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-
-/** Enables end user to type and execute any JCR query. */
-public class GenericJcrQueryEditor extends AbstractJcrQueryEditor {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID
- + ".genericJcrQueryEditor";
-
- private Text queryField;
-
- @Override
- public void createQueryForm(Composite parent) {
- parent.setLayout(new GridLayout(1, false));
-
- queryField = new Text(parent, SWT.BORDER | SWT.MULTI | SWT.WRAP);
- queryField.setText(initialQuery);
- queryField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Button execute = new Button(parent, SWT.PUSH);
- execute.setText("Execute");
-
- Listener executeListener = new Listener() {
- private static final long serialVersionUID = -918256291554301699L;
-
- public void handleEvent(Event event) {
- executeQuery(queryField.getText());
- }
- };
-
- execute.addListener(SWT.Selection, executeListener);
- // queryField.addListener(SWT.DefaultSelection, executeListener);
- }
-
- @Override
- public void setFocus() {
- queryField.setFocus();
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.jcr;
-
-import java.util.List;
-
-import javax.jcr.Property;
-import javax.jcr.PropertyType;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.Value;
-import javax.jcr.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.observation.ObservationManager;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.security.Keyring;
-import org.argeo.cms.ui.jcr.DefaultRepositoryRegister;
-import org.argeo.cms.ui.jcr.JcrBrowserUtils;
-import org.argeo.cms.ui.jcr.JcrDClickListener;
-import org.argeo.cms.ui.jcr.NodeContentProvider;
-import org.argeo.cms.ui.jcr.NodeLabelProvider;
-import org.argeo.cms.ui.jcr.PropertiesContentProvider;
-import org.argeo.cms.ui.jcr.RepositoryRegister;
-import org.argeo.cms.ui.jcr.model.SingleJcrNodeElem;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.eclipse.ui.jcr.util.NodeViewerComparer;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Basic View to display a sash form to browse a JCR compliant multiple
- * repository environment
- */
-public class JcrBrowserView extends ViewPart {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".jcrBrowserView";
- private boolean sortChildNodes = true;
-
- /* DEPENDENCY INJECTION */
- private Keyring keyring;
- private RepositoryRegister repositoryRegister = new DefaultRepositoryRegister();
- private RepositoryFactory repositoryFactory;
- private Repository nodeRepository;
-
- // Current user session on the "Argeo node" default workspace
- private Session userSession;
-
- // This page widgets
- private TreeViewer nodesViewer;
- private NodeContentProvider nodeContentProvider;
- private TableViewer propertiesViewer;
- private EventListener resultsObserver;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
- SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- sashForm.setLayout(new FillLayout());
-
- // Create the tree on top of the view
- Composite top = new Composite(sashForm, SWT.NONE);
- GridLayout gl = new GridLayout(1, false);
- top.setLayout(gl);
-
- try {
- this.userSession = this.nodeRepository.login(CmsConstants.HOME_WORKSPACE);
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot open user session", e);
- }
-
- nodeContentProvider = new NodeContentProvider(userSession, keyring, repositoryRegister, repositoryFactory,
- sortChildNodes);
-
- // nodes viewer
- nodesViewer = createNodeViewer(top, nodeContentProvider);
-
- // context menu : it is completely defined in the plugin.xml file.
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(nodesViewer.getTree());
-
- nodesViewer.getTree().setMenu(menu);
- getSite().registerContextMenu(menuManager, nodesViewer);
- getSite().setSelectionProvider(nodesViewer);
-
- nodesViewer.setInput(getViewSite());
-
- // Create the property viewer on the bottom
- Composite bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
- propertiesViewer = createPropertiesViewer(bottom);
-
- sashForm.setWeights(getWeights());
- nodesViewer.setComparer(new NodeViewerComparer());
- }
-
- public void refresh(Object obj) {
- // Enable full refresh from a command when no element of the tree is
- // selected
- if (obj == null) {
- Object[] elements = nodeContentProvider.getElements(null);
- for (Object el : elements) {
- if (el instanceof TreeParent)
- JcrBrowserUtils.forceRefreshIfNeeded((TreeParent) el);
- getNodeViewer().refresh(el);
- }
- } else
- getNodeViewer().refresh(obj);
- }
-
- /**
- * To be overridden to adapt size of form and result frames.
- */
- protected int[] getWeights() {
- return new int[] { 70, 30 };
- }
-
- protected TreeViewer createNodeViewer(Composite parent, final ITreeContentProvider nodeContentProvider) {
-
- final TreeViewer tmpNodeViewer = new TreeViewer(parent, SWT.MULTI);
-
- tmpNodeViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- tmpNodeViewer.setContentProvider(nodeContentProvider);
- tmpNodeViewer.setLabelProvider(new NodeLabelProvider());
- tmpNodeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if (!event.getSelection().isEmpty()) {
- IStructuredSelection sel = (IStructuredSelection) event.getSelection();
- Object firstItem = sel.getFirstElement();
- if (firstItem instanceof SingleJcrNodeElem)
- propertiesViewer.setInput(((SingleJcrNodeElem) firstItem).getNode());
- } else {
- propertiesViewer.setInput(getViewSite());
- }
- }
- });
-
- resultsObserver = new TreeObserver(tmpNodeViewer.getTree().getDisplay());
- if (keyring != null)
- try {
- ObservationManager observationManager = userSession.getWorkspace().getObservationManager();
- observationManager.addEventListener(resultsObserver, Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED, "/",
- true, null, null, false);
- } catch (RepositoryException e) {
- throw new EclipseUiException("Cannot register listeners", e);
- }
-
- tmpNodeViewer.addDoubleClickListener(new JcrDClickListener(tmpNodeViewer));
- return tmpNodeViewer;
- }
-
- protected TableViewer createPropertiesViewer(Composite parent) {
- propertiesViewer = new TableViewer(parent);
- propertiesViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- propertiesViewer.getTable().setHeaderVisible(true);
- propertiesViewer.setContentProvider(new PropertiesContentProvider());
- TableViewerColumn col = new TableViewerColumn(propertiesViewer, SWT.NONE);
- col.getColumn().setText("Name");
- col.getColumn().setWidth(200);
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -6684361063107478595L;
-
- public String getText(Object element) {
- try {
- return ((Property) element).getName();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unexpected exception in label provider", e);
- }
- }
- });
- col = new TableViewerColumn(propertiesViewer, SWT.NONE);
- col.getColumn().setText("Value");
- col.getColumn().setWidth(400);
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -8201994187693336657L;
-
- public String getText(Object element) {
- try {
- Property property = (Property) element;
- if (property.getType() == PropertyType.BINARY)
- return "<binary>";
- else if (property.isMultiple()) {
- StringBuffer buf = new StringBuffer("[");
- Value[] values = property.getValues();
- for (int i = 0; i < values.length; i++) {
- if (i != 0)
- buf.append(", ");
- buf.append(values[i].getString());
- }
- buf.append(']');
- return buf.toString();
- } else
- return property.getValue().getString();
- } catch (RepositoryException e) {
- throw new EclipseUiException("Unexpected exception in label provider", e);
- }
- }
- });
- col = new TableViewerColumn(propertiesViewer, SWT.NONE);
- col.getColumn().setText("Type");
- col.getColumn().setWidth(200);
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -6009599998150286070L;
-
- public String getText(Object element) {
- return JcrBrowserUtils.getPropertyTypeAsString((Property) element);
- }
- });
- propertiesViewer.setInput(getViewSite());
- return propertiesViewer;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- }
-
- protected TreeViewer getNodeViewer() {
- return nodesViewer;
- }
-
- /**
- * Resets the tree content provider
- *
- * @param sortChildNodes
- * if true the content provider will use a comparer to sort nodes
- * that might slow down the display
- */
- public void setSortChildNodes(boolean sortChildNodes) {
- this.sortChildNodes = sortChildNodes;
- ((NodeContentProvider) nodesViewer.getContentProvider()).setSortChildren(sortChildNodes);
- nodesViewer.setInput(getViewSite());
- }
-
- /** Notifies the current view that a node has been added */
- public void nodeAdded(TreeParent parentNode) {
- // insure that Ui objects have been correctly created:
- JcrBrowserUtils.forceRefreshIfNeeded(parentNode);
- getNodeViewer().refresh(parentNode);
- getNodeViewer().expandToLevel(parentNode, 1);
- }
-
- /** Notifies the current view that a node has been removed */
- public void nodeRemoved(TreeParent parentNode) {
- IStructuredSelection newSel = new StructuredSelection(parentNode);
- getNodeViewer().setSelection(newSel, true);
- // Force refresh
- IStructuredSelection tmpSel = (IStructuredSelection) getNodeViewer().getSelection();
- getNodeViewer().refresh(tmpSel.getFirstElement());
- }
-
- class TreeObserver extends AsyncUiEventListener {
-
- public TreeObserver(Display display) {
- super(display);
- }
-
- @Override
- protected Boolean willProcessInUiThread(List<Event> events) throws RepositoryException {
- for (Event event : events) {
- if (getLog().isTraceEnabled())
- getLog().debug("Received event " + event);
- String path = event.getPath();
- int index = path.lastIndexOf('/');
- String propertyName = path.substring(index + 1);
- if (getLog().isTraceEnabled())
- getLog().debug("Concerned property " + propertyName);
- }
- return false;
- }
-
- protected void onEventInUiThread(List<Event> events) throws RepositoryException {
- if (getLog().isTraceEnabled())
- getLog().trace("Refresh result list");
- nodesViewer.refresh();
- }
-
- }
-
- public boolean getSortChildNodes() {
- return sortChildNodes;
- }
-
- @Override
- public void setFocus() {
- getNodeViewer().getTree().setFocus();
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepositoryRegister(RepositoryRegister repositoryRegister) {
- this.repositoryRegister = repositoryRegister;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.jcr;
-
-import java.net.URI;
-import java.nio.file.FileSystem;
-import java.nio.file.Path;
-import java.nio.file.spi.FileSystemProvider;
-
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.fs.SimpleFsBrowser;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-/** Browse the node file system. */
-public class NodeFsBrowserView extends ViewPart {
- public final static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".nodeFsBrowserView";
-
- private FileSystemProvider nodeFileSystemProvider;
-
- @Override
- public void createPartControl(Composite parent) {
- try {
- URI uri = new URI("node:///");
- FileSystem fileSystem = nodeFileSystemProvider.getFileSystem(uri);
- if (fileSystem == null)
- fileSystem = nodeFileSystemProvider.newFileSystem(uri, null);
- Path nodePath = fileSystem.getPath("~");
- SimpleFsBrowser browser = new SimpleFsBrowser(parent, SWT.NO_FOCUS);
- browser.setInput(nodePath);
- } catch (Exception e) {
- throw new CmsException("Cannot open file system browser", e);
- }
- }
-
- @Override
- public void setFocus() {
- }
-
- public void setNodeFileSystemProvider(FileSystemProvider nodeFileSystemProvider) {
- this.nodeFileSystemProvider = nodeFileSystemProvider;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.jcr;
-
-import static javax.jcr.Node.JCR_CONTENT;
-import static javax.jcr.Property.JCR_DATA;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Binary;
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.cms.ui.jcr.JcrDClickListener;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.cms.ui.workbench.internal.jcr.parts.GenericNodeEditorInput;
-import org.argeo.cms.ui.workbench.legacy.rap.OpenFile;
-import org.argeo.cms.ui.workbench.legacy.rap.SingleSourcingException;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.argeo.jcr.JcrUtils;
-import org.eclipse.jface.viewers.TreeViewer;
-
-public class WorkbenchJcrDClickListener extends JcrDClickListener {
-
- public WorkbenchJcrDClickListener(TreeViewer nodeViewer) {
- super(nodeViewer);
- }
-
- @Override
- protected void openNode(Node node) {
- try {
- if (node.isNodeType(NodeType.NT_FILE)) {
- // Also open it
-
- String name = node.getName();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenFile.PARAM_FILE_NAME, name);
-
- // TODO rather directly transmit the path to the node, once
- // we have defined convention to provide an Absolute URI to
- // a node in a multi repo / workspace / user context
- // params.put(OpenFile.PARAM_FILE_URI,
- // OpenFileService.JCR_SCHEME + node.getPath());
-
- // we copy the node to a tmp file to be opened as a dirty
- // workaround
- File tmpFile = null;
- // OutputStream os = null;
- // InputStream is = null;
- int i = name.lastIndexOf('.');
- String prefix, suffix;
- if (i == -1) {
- prefix = name;
- suffix = null;
- } else {
- prefix = name.substring(0, i);
- suffix = name.substring(i);
- }
- Binary binary = null;
- try {
- tmpFile = File.createTempFile(prefix, suffix);
- tmpFile.deleteOnExit();
- } catch (IOException e1) {
- throw new EclipseUiException("Cannot create temp file", e1);
- }
- try (OutputStream os = new FileOutputStream(tmpFile)) {
- binary = node.getNode(JCR_CONTENT).getProperty(JCR_DATA).getBinary();
- try (InputStream is = binary.getStream();) {
- IOUtils.copy(is, os);
- }
- } catch (IOException e) {
- throw new SingleSourcingException("Cannot open file " + prefix + "." + suffix, e);
- } finally {
- // IOUtils.closeQuietly(is);
- // IOUtils.closeQuietly(os);
- JcrUtils.closeQuietly(binary);
- }
- Path path = Paths.get(tmpFile.getAbsolutePath());
- String uri = path.toUri().toString();
- params.put(OpenFile.PARAM_FILE_URI, uri);
- CommandUtils.callCommand(OpenFile.ID, params);
- }
- GenericNodeEditorInput gnei = new GenericNodeEditorInput(node);
- WorkbenchUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(gnei,
- DefaultNodeEditor.ID);
- } catch (RepositoryException re) {
- throw new EclipseUiException("Repository error while getting node info", re);
- } catch (Exception pie) {
- throw new EclipseUiException("Unexpected exception while opening node editor", pie);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.legacy.rap;
-
-import org.argeo.api.cms.CmsLog;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.client.service.UrlLauncher;
-
-/**
- * RWT specific object to open a file retrieved from the server. It forwards the
- * request to the correct service after encoding file name and path in the
- * request URI.
- *
- * <p>
- * The parameter "URI" is used to determine the correct file service, the path
- * and the file name. An optional file name can be added to present the end user
- * with a different file name as the one used to retrieve it.
- * </p>
- *
- *
- * <p>
- * The instance specific service is called by its ID and must have been
- * externally created
- * </p>
- */
-public class OpenFile extends AbstractHandler {
- private final static CmsLog log = CmsLog.getLog(OpenFile.class);
-
- public final static String ID = SingleSourcingConstants.OPEN_FILE_CMD_ID;
- public final static String PARAM_FILE_NAME = SingleSourcingConstants.PARAM_FILE_NAME;
- public final static String PARAM_FILE_URI = SingleSourcingConstants.PARAM_FILE_URI;;
-
- /* DEPENDENCY INJECTION */
- private String openFileServiceId;
-
- public Object execute(ExecutionEvent event) {
- String fileName = event.getParameter(PARAM_FILE_NAME);
- String fileUri = event.getParameter(PARAM_FILE_URI);
- // Sanity check
- if (fileUri == null || "".equals(fileUri.trim()) || openFileServiceId == null
- || "".equals(openFileServiceId.trim()))
- return null;
-
- org.argeo.cms.ui.workbench.legacy.rap.OpenFile openFileClient = new org.argeo.cms.ui.workbench.legacy.rap.OpenFile();
- openFileClient.execute(openFileServiceId, fileUri, fileName);
- return null;
- }
-
- public Object execute(String openFileServiceId, String fileUri, String fileName) {
- StringBuilder url = new StringBuilder();
- url.append(RWT.getServiceManager().getServiceHandlerUrl(openFileServiceId));
-
- if (notEmpty(fileName))
- url.append("&").append(SingleSourcingConstants.PARAM_FILE_NAME).append("=").append(fileName);
- url.append("&").append(SingleSourcingConstants.PARAM_FILE_URI).append("=").append(fileUri);
-
- String downloadUrl = url.toString();
- if (log.isTraceEnabled())
- log.trace("Calling OpenFileService with ID: " + openFileServiceId + " , with download URL: " + downloadUrl);
-
- UrlLauncher launcher = RWT.getClient().getService(UrlLauncher.class);
- launcher.openURL(downloadUrl);
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setOpenFileServiceId(String openFileServiceId) {
- this.openFileServiceId = openFileServiceId;
- }
-
- /** Simply checks if a string is not null nor empty */
- public static boolean notEmpty(String stringToTest) {
- return !(stringToTest == null || "".equals(stringToTest.trim()));
- }
-
- /** Simply checks if a string is null or empty */
- public static boolean isEmpty(String stringToTest) {
- return stringToTest == null || "".equals(stringToTest.trim());
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.legacy.rap;
-
-import static org.argeo.cms.ui.workbench.legacy.rap.SingleSourcingConstants.FILE_SCHEME;
-import static org.argeo.cms.ui.workbench.legacy.rap.SingleSourcingConstants.SCHEME_HOST_SEPARATOR;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.eclipse.rap.rwt.service.ServiceHandler;
-
-/**
- * RWT specific Basic Default service handler that retrieves a file on the
- * server file system using its absolute path and forwards it to the end user
- * browser.
- *
- * Clients might extend to provide context specific services
- */
-public class OpenFileService implements ServiceHandler {
- public OpenFileService() {
- }
-
- public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
- String fileName = request.getParameter(SingleSourcingConstants.PARAM_FILE_NAME);
- String uri = request.getParameter(SingleSourcingConstants.PARAM_FILE_URI);
-
- // Use buffered array to directly write the stream?
- if (!uri.startsWith(SingleSourcingConstants.FILE_SCHEME))
- throw new IllegalArgumentException(
- "Open file service can only handle files that are on the server file system");
-
- // Set the Metadata
- response.setContentLength((int) getFileSize(uri));
- if (OpenFile.isEmpty(fileName))
- fileName = getFileName(uri);
- response.setContentType(getMimeType(uri, fileName));
- String contentDisposition = "attachment; filename=\"" + fileName + "\"";
- response.setHeader("Content-Disposition", contentDisposition);
-
- // Useless for current use
- // response.setHeader("Content-Transfer-Encoding", "binary");
- // response.setHeader("Pragma", "no-cache");
- // response.setHeader("Cache-Control", "no-cache, must-revalidate");
-
- Path path = Paths.get(getAbsPathFromUri(uri));
- Files.copy(path, response.getOutputStream());
-
- // FIXME we always use temporary files for the time being.
- // the deleteOnClose file only works when the JVM is closed so we
- // explicitly delete to avoid overloading the server
- if (path.startsWith("/tmp"))
- path.toFile().delete();
- }
-
- protected long getFileSize(String uri) throws IOException {
- if (uri.startsWith(SingleSourcingConstants.FILE_SCHEME)) {
- Path path = Paths.get(getAbsPathFromUri(uri));
- return Files.size(path);
- }
- return -1l;
- }
-
- protected String getFileName(String uri) {
- if (uri.startsWith(SingleSourcingConstants.FILE_SCHEME)) {
- Path path = Paths.get(getAbsPathFromUri(uri));
- return path.getFileName().toString();
- }
- return null;
- }
-
- private String getAbsPathFromUri(String uri) {
- if (uri.startsWith(FILE_SCHEME))
- return uri.substring((FILE_SCHEME + SCHEME_HOST_SEPARATOR).length());
- // else if (uri.startsWith(JCR_SCHEME))
- // return uri.substring((JCR_SCHEME + SCHEME_HOST_SEPARATOR).length());
- else
- throw new IllegalArgumentException("Unknown URI prefix for" + uri);
- }
-
- protected String getMimeType(String uri, String fileName) throws IOException {
- if (uri.startsWith(FILE_SCHEME)) {
- Path path = Paths.get(getAbsPathFromUri(uri));
- String mimeType = Files.probeContentType(path);
- if (OpenFile.notEmpty(mimeType))
- return mimeType;
- }
- return "application/octet-stream";
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.legacy.rap;
-
-/**
- * Centralise constants that are used in both RAP and RCP specific code to avoid
- * duplicated declaration
- */
-public interface SingleSourcingConstants {
-
- // Single sourced open file command
- String OPEN_FILE_CMD_ID = "org.argeo.cms.ui.workbench.openFile";
- String PARAM_FILE_NAME = "param.fileName";
- String PARAM_FILE_URI = "param.fileURI";
-
- String SCHEME_HOST_SEPARATOR = "://";
- String FILE_SCHEME = "file";
- String JCR_SCHEME = "jcr";
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.legacy.rap;
-
-/** Exception related to SWT/RWT single sourcing. */
-public class SingleSourcingException extends RuntimeException {
- private static final long serialVersionUID = -727700418055348468L;
-
- public SingleSourcingException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public SingleSourcingException(String message) {
- super(message);
- }
-
-}
+++ /dev/null
-## English labels for Agreo JCR UI application
-
-## Generic labels
-
-## Errors & warnings
-errorUnvalidNtFolderNodeType= Error: folder can only be created on a Jcr Node
-warningInvalidNodeToImport=Can only import to a node
-warningInvalidMultipleSelection=This functionality is implemented only on a single node for the time being.
-warningUnversionableNode= Current node is not versionable.
-warningNoChildNode= Current node has no child.
-
-## Commands
-getNodeSizeCmdLbl= Get approx. size
-addFolderNodeCmdLbl= Add Folder
-
-## GenericNodeEditor
-nodeEditorLbl=Generic node editor
-genericNodePageTitle=Properties
-childNodesPageTitle=Children
-nodeRightsManagementPageTitle=Effective privileges
-nodeVersionHistoryPageTitle=History
-propertyEditorPageTitle=Properties Editor (Experimental)
-
-# History
-versionTreeSectionTitle=Version list
-versionHistorySectionTitle=History
-
-## Dummy ones
-testLbl=Internationalizations of messages seems to work properly.
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.ServiceReference;
-
-/** A tree element representing a {@link Bundle} */
-class BundleNode extends TreeParent {
- private final Bundle bundle;
-
- public BundleNode(Bundle bundle) {
- this(bundle, false);
- }
-
- @SuppressWarnings("rawtypes")
- public BundleNode(Bundle bundle, boolean hasChildren) {
- super(bundle.getSymbolicName());
- this.bundle = bundle;
-
- if (hasChildren) {
- // REFERENCES
- ServiceReference[] usedServices = bundle.getServicesInUse();
- if (usedServices != null) {
- for (ServiceReference sr : usedServices) {
- if (sr != null)
- addChild(new ServiceReferenceNode(sr, false));
- }
- }
-
- // SERVICES
- ServiceReference[] registeredServices = bundle
- .getRegisteredServices();
- if (registeredServices != null) {
- for (ServiceReference sr : registeredServices) {
- if (sr != null)
- addChild(new ServiceReferenceNode(sr, true));
- }
- }
- }
-
- }
-
- Bundle getBundle() {
- return bundle;
- }
-}
+++ /dev/null
-//package org.argeo.eclipse.ui.workbench.osgi;
-//public class BundlesView {}
-
-package org.argeo.cms.ui.workbench.osgi;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.ColumnViewerComparator;
-import org.argeo.eclipse.ui.specific.EclipseUiSpecificUtils;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-/**
- * Overview of the bundles as a table. Equivalent to Equinox 'ss' console
- * command.
- */
-public class BundlesView extends ViewPart {
- private TableViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- viewer = new TableViewer(parent);
- viewer.setContentProvider(new BundleContentProvider());
- viewer.getTable().setHeaderVisible(true);
-
- EclipseUiSpecificUtils.enableToolTipSupport(viewer);
-
- // ID
- TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(30);
- column.getColumn().setText("ID");
- column.getColumn().setAlignment(SWT.RIGHT);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -3122136344359358605L;
-
- public String getText(Object element) {
- return Long.toString(((Bundle) element).getBundleId());
- }
- });
- new ColumnViewerComparator(column);
-
- // State
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(18);
- column.getColumn().setText("State");
- column.setLabelProvider(new StateLabelProvider());
- new ColumnViewerComparator(column);
-
- // Symbolic name
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(250);
- column.getColumn().setText("Symbolic Name");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -4280840684440451080L;
-
- public String getText(Object element) {
- return ((Bundle) element).getSymbolicName();
- }
- });
- new ColumnViewerComparator(column);
-
- // Version
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(150);
- column.getColumn().setText("Version");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 6871926308708629989L;
-
- public String getText(Object element) {
- Bundle bundle = (org.osgi.framework.Bundle) element;
- return bundle.getVersion().toString();
- }
- });
- new ColumnViewerComparator(column);
-
- viewer.setInput(WorkbenchUiPlugin.getDefault().getBundle().getBundleContext());
-
- }
-
- @Override
- public void setFocus() {
- if (viewer != null)
- viewer.getControl().setFocus();
- }
-
- /** Content provider managing the array of bundles */
- private static class BundleContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -8533792785725875977L;
-
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof BundleContext) {
- BundleContext bc = (BundleContext) inputElement;
- return bc.getBundles();
- }
- return null;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-}
+++ /dev/null
-//package org.argeo.eclipse.ui.workbench.osgi;
-//public class BundlesView {}
-
-package org.argeo.cms.ui.workbench.osgi;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.naming.ldap.LdapName;
-
-import org.argeo.api.cms.CmsSession;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.ColumnViewerComparator;
-import org.argeo.eclipse.ui.specific.EclipseUiSpecificUtils;
-import org.argeo.util.LangUtils;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-/**
- * Overview of the active CMS sessions.
- */
-public class CmsSessionsView extends ViewPart {
- private TableViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- viewer = new TableViewer(parent);
- viewer.setContentProvider(new CmsSessionContentProvider());
- viewer.getTable().setHeaderVisible(true);
-
- EclipseUiSpecificUtils.enableToolTipSupport(viewer);
-
- int longColWidth = 150;
- int smallColWidth = 100;
-
- // Display name
- TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(longColWidth);
- column.getColumn().setText("User");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5234573509093747505L;
-
- public String getText(Object element) {
- return ((CmsSession) element).getDisplayName();
- }
-
- public String getToolTipText(Object element) {
- return ((CmsSession) element).getUserDn().toString();
- }
- });
- new ColumnViewerComparator(column);
-
- // Creation time
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(smallColWidth);
- column.getColumn().setText("Since");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5234573509093747505L;
-
- public String getText(Object element) {
- return LangUtils.since(((CmsSession) element).getCreationTime());
- }
-
- public String getToolTipText(Object element) {
- return ((CmsSession) element).getCreationTime().toString();
- }
- });
- new ColumnViewerComparator(column);
-
- // Username
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(smallColWidth);
- column.getColumn().setText("Username");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5234573509093747505L;
-
- public String getText(Object element) {
- LdapName userDn = ((CmsSession) element).getUserDn();
- return userDn.getRdn(userDn.size() - 1).getValue().toString();
- }
-
- public String getToolTipText(Object element) {
- return ((CmsSession) element).getUserDn().toString();
- }
- });
- new ColumnViewerComparator(column);
-
- // UUID
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(smallColWidth);
- column.getColumn().setText("UUID");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5234573509093747505L;
-
- public String getText(Object element) {
- return ((CmsSession) element).getUuid().toString();
- }
-
- public String getToolTipText(Object element) {
- return getText(element);
- }
- });
- new ColumnViewerComparator(column);
-
- // Local ID
- column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setWidth(smallColWidth);
- column.getColumn().setText("Local ID");
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5234573509093747505L;
-
- public String getText(Object element) {
- return ((CmsSession) element).getLocalId();
- }
-
- public String getToolTipText(Object element) {
- return getText(element);
- }
- });
- new ColumnViewerComparator(column);
-
- viewer.setInput(WorkbenchUiPlugin.getDefault().getBundle().getBundleContext());
-
- }
-
- @Override
- public void setFocus() {
- if (viewer != null)
- viewer.getControl().setFocus();
- }
-
- /** Content provider managing the array of bundles */
- private static class CmsSessionContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -8533792785725875977L;
-
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof BundleContext) {
- BundleContext bc = (BundleContext) inputElement;
- Collection<ServiceReference<CmsSession>> srs;
- try {
- srs = bc.getServiceReferences(CmsSession.class, null);
- } catch (InvalidSyntaxException e) {
- throw new CmsException("Cannot retrieve CMS sessions", e);
- }
- List<CmsSession> res = new ArrayList<>();
- for (ServiceReference<CmsSession> sr : srs) {
- res.add(bc.getService(sr));
- }
- return res.toArray();
- }
- return null;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-/** The OSGi runtime from a module perspective. */
-public class ModulesView extends ViewPart {
- private TreeViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- viewer.setContentProvider(new ModulesContentProvider());
- viewer.setLabelProvider(new ModulesLabelProvider());
- viewer.setInput(WorkbenchUiPlugin.getDefault().getBundle()
- .getBundleContext());
- }
-
- @Override
- public void setFocus() {
- viewer.getTree().setFocus();
- }
-
- private class ModulesContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = 3819934804640641721L;
-
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof BundleContext) {
- BundleContext bundleContext = (BundleContext) parentElement;
- Bundle[] bundles = bundleContext.getBundles();
-
- List<BundleNode> modules = new ArrayList<BundleNode>();
- for (Bundle bundle : bundles) {
- if (bundle.getState() == Bundle.ACTIVE)
- modules.add(new BundleNode(bundle, true));
- }
- return modules.toArray();
- } else if (parentElement instanceof TreeParent) {
- return ((TreeParent) parentElement).getChildren();
- } else {
- return null;
- }
- }
-
- public Object getParent(Object element) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public boolean hasChildren(Object element) {
- if (element instanceof TreeParent) {
- return ((TreeParent) element).hasChildren();
- }
- return false;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- private class ModulesLabelProvider extends StateLabelProvider {
- private static final long serialVersionUID = 5290046145534824722L;
-
- @Override
- public String getText(Object element) {
- if (element instanceof BundleNode)
- return element.toString() + " ["
- + ((BundleNode) element).getBundle().getBundleId()
- + "]";
- return element.toString();
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.TreeSet;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/** <b>Experimental</b> The OSGi runtime from a module perspective. */
-@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
-public class MultiplePackagesView extends ViewPart {
- private TreeViewer viewer;
- private PackageAdmin packageAdmin;
- private Comparator<ExportedPackage> epc = new Comparator<ExportedPackage>() {
- public int compare(ExportedPackage o1, ExportedPackage o2) {
- if (!o1.getName().equals(o2.getName()))
- return o1.getName().compareTo(o2.getName());
- else
- return o1.getVersion().compareTo(o2.getVersion());
- }
- };
-
- @Override
- public void createPartControl(Composite parent) {
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- viewer.setContentProvider(new ModulesContentProvider());
- viewer.setLabelProvider(new LabelProvider());
- viewer.setInput(WorkbenchUiPlugin.getDefault().getBundle()
- .getBundleContext());
- }
-
- @Override
- public void setFocus() {
- viewer.getTree().setFocus();
- }
-
- private class ModulesContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = 3819934804640641721L;
-
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof BundleContext) {
- BundleContext bundleContext = (BundleContext) parentElement;
- Bundle[] bundles = bundleContext.getBundles();
-
- // scan packages
- ServiceReference paSr = bundleContext
- .getServiceReference(PackageAdmin.class.getName());
- // TODO: make a cleaner referencing
- packageAdmin = (PackageAdmin) bundleContext.getService(paSr);
-
- Map<Bundle, Set<ExportedPackage>> imported = new HashMap<Bundle, Set<ExportedPackage>>();
- Map<String, Set<ExportedPackage>> packages = new TreeMap<String, Set<ExportedPackage>>();
- for (Bundle bundle : bundles) {
- processBundle(bundle, imported, packages);
- }
-
- List<MultiplePackagesNode> multiplePackages = new ArrayList<MultiplePackagesNode>();
- for (String packageName : packages.keySet()) {
- Set<ExportedPackage> pkgs = packages.get(packageName);
- if (pkgs.size() > 1) {
- MultiplePackagesNode mpn = new MultiplePackagesNode(
- packageName, pkgs);
- multiplePackages.add(mpn);
- }
- }
-
- return multiplePackages.toArray();
- } else if (parentElement instanceof TreeParent) {
- return ((TreeParent) parentElement).getChildren();
- } else {
- return null;
- }
- }
-
- protected void processBundle(Bundle bundle,
- Map<Bundle, Set<ExportedPackage>> imported,
- Map<String, Set<ExportedPackage>> packages) {
- ExportedPackage[] pkgs = packageAdmin.getExportedPackages(bundle);
- if (pkgs == null)
- return;
- for (ExportedPackage pkg : pkgs) {
- if (!packages.containsKey(pkg.getName()))
- packages.put(pkg.getName(), new TreeSet<ExportedPackage>(
- epc));
- Set<ExportedPackage> expPackages = packages.get(pkg.getName());
- expPackages.add(pkg);
-
- // imported
- for (Bundle b : pkg.getImportingBundles()) {
- if (bundle.getBundleId() != b.getBundleId()) {
- if (!imported.containsKey(b)) {
- imported.put(b, new TreeSet<ExportedPackage>(epc));
- }
- Set<ExportedPackage> impPackages = imported.get(b);
- impPackages.add(pkg);
- }
- }
- }
- }
-
- public Object getParent(Object element) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public boolean hasChildren(Object element) {
- if (element instanceof TreeParent) {
- return ((TreeParent) element).hasChildren();
- }
- return false;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- private class MultiplePackagesNode extends TreeParent {
- public MultiplePackagesNode(String packageName,
- Set<ExportedPackage> exportedPackages) {
- super(packageName);
- for (ExportedPackage pkg : exportedPackages) {
- addChild(new ExportedPackageNode(pkg));
- }
- }
- }
-
- private class ExportedPackageNode extends TreeParent {
- public ExportedPackageNode(ExportedPackage exportedPackage) {
- super(exportedPackage.getName() + " - "
- + exportedPackage.getVersion() + " ("
- + exportedPackage.getExportingBundle() + ")");
- for (Bundle bundle : exportedPackage.getImportingBundles()) {
- addChild(new BundleNode(bundle, true));
- }
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.eclipse.swt.graphics.Image;
-
-/** Shared icons. */
-public class OsgiExplorerImages {
- public final static Image INSTALLED = WorkbenchUiPlugin.getImageDescriptor(
- "icons/installed.gif").createImage();
- public final static Image RESOLVED = WorkbenchUiPlugin.getImageDescriptor(
- "icons/resolved.gif").createImage();
- public final static Image STARTING = WorkbenchUiPlugin.getImageDescriptor(
- "icons/starting.gif").createImage();
- public final static Image ACTIVE = WorkbenchUiPlugin.getImageDescriptor(
- "icons/active.gif").createImage();
- public final static Image SERVICE_PUBLISHED = WorkbenchUiPlugin
- .getImageDescriptor("icons/service_published.gif").createImage();
- public final static Image SERVICE_REFERENCED = WorkbenchUiPlugin
- .getImageDescriptor("icons/service_referenced.gif").createImage();
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.ServiceReference;
-
-/** A tree element representing a {@link ServiceReference} */
-@SuppressWarnings({ "rawtypes" })
-class ServiceReferenceNode extends TreeParent {
- private final ServiceReference serviceReference;
- private final boolean published;
-
- public ServiceReferenceNode(ServiceReference serviceReference,
- boolean published) {
- super(serviceReference.toString());
- this.serviceReference = serviceReference;
- this.published = published;
-
- if (isPublished()) {
- Bundle[] usedBundles = serviceReference.getUsingBundles();
- if (usedBundles != null) {
- for (Bundle b : usedBundles) {
- if (b != null)
- addChild(new BundleNode(b));
- }
- }
- } else {
- Bundle provider = serviceReference.getBundle();
- addChild(new BundleNode(provider));
- }
-
- for (String key : serviceReference.getPropertyKeys()) {
- addChild(new TreeParent(key + "="
- + serviceReference.getProperty(key)));
- }
-
- }
-
- public ServiceReference getServiceReference() {
- return serviceReference;
- }
-
- public boolean isPublished() {
- return published;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.osgi;
-
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-
-/** Label provider showing the sate of bundles */
-class StateLabelProvider extends ColumnLabelProvider {
- private static final long serialVersionUID = -7885583135316000733L;
-
- @Override
- public Image getImage(Object element) {
- int state;
- if (element instanceof Bundle)
- state = ((Bundle) element).getState();
- else if (element instanceof BundleNode)
- state = ((BundleNode) element).getBundle().getState();
- else if (element instanceof ServiceReferenceNode)
- if (((ServiceReferenceNode) element).isPublished())
- return OsgiExplorerImages.SERVICE_PUBLISHED;
- else
- return OsgiExplorerImages.SERVICE_REFERENCED;
- else
- return null;
-
- switch (state) {
- case Bundle.UNINSTALLED:
- return OsgiExplorerImages.INSTALLED;
- case Bundle.INSTALLED:
- return OsgiExplorerImages.INSTALLED;
- case Bundle.RESOLVED:
- return OsgiExplorerImages.RESOLVED;
- case Bundle.STARTING:
- return OsgiExplorerImages.STARTING;
- case Bundle.STOPPING:
- return OsgiExplorerImages.STARTING;
- case Bundle.ACTIVE:
- return OsgiExplorerImages.ACTIVE;
- default:
- return null;
- }
- }
-
- @Override
- public String getText(Object element) {
- return null;
- }
-
- @Override
- public String getToolTipText(Object element) {
- Bundle bundle = (Bundle) element;
- Integer state = bundle.getState();
- switch (state) {
- case Bundle.UNINSTALLED:
- return "UNINSTALLED";
- case Bundle.INSTALLED:
- return "INSTALLED";
- case Bundle.RESOLVED:
- return "RESOLVED";
- case Bundle.STARTING:
- String activationPolicy = bundle.getHeaders()
- .get(Constants.BUNDLE_ACTIVATIONPOLICY).toString();
-
- // .get("Bundle-ActivationPolicy").toString();
- // FIXME constant triggers the compilation failure
- if (activationPolicy != null
- && activationPolicy.equals(Constants.ACTIVATION_LAZY))
- // && activationPolicy.equals("lazy"))
- // FIXME constant triggers the compilation failure
- // && activationPolicy.equals(Constants.ACTIVATION_LAZY))
- return "<<LAZY>>";
- return "STARTING";
- case Bundle.STOPPING:
- return "STOPPING";
- case Bundle.ACTIVE:
- return "ACTIVE";
- default:
- return null;
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.useradmin;
-
-import java.util.ArrayList;
-
-import org.argeo.cms.ArgeoLogger;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Display log lines for all users with a virtual table.
- */
-public class AdminLogView extends ViewPart {
- public static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".adminLogView";
-
- private TableViewer viewer;
-
- private LogContentProvider logContentProvider;
- private ArgeoLogger argeoLogger;
-
- @Override
- public void createPartControl(Composite parent) {
- // FIXME doesn't return a monospace font in RAP
- Font font = JFaceResources.getTextFont();
- Table table = new Table(parent, SWT.VIRTUAL | SWT.MULTI | SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
- table.setFont(font);
-
- viewer = new TableViewer(table);
- viewer.setLabelProvider(new LabelProvider());
- logContentProvider = new LogContentProvider(viewer) {
- private static final long serialVersionUID = -3401776448301180724L;
-
- @Override
- protected StringBuffer prefix(String username, Long timestamp,
- String level, String category, String thread) {
- return super
- .prefix(username, timestamp, level, category, thread)
- .append(norm(level, 5))
- .append(' ')
- .append(norm(username != null ? username
- : "<anonymous>", 16)).append(' ');
- }
- };
- viewer.setContentProvider(logContentProvider);
- // viewer.setUseHashlookup(true);
- viewer.setInput(new ArrayList<String>());
-
- if (argeoLogger != null)
- argeoLogger.registerForAll(logContentProvider, 1000, true);
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- @Override
- public void dispose() {
- if (argeoLogger != null)
- argeoLogger.unregisterForAll(logContentProvider);
- }
-
- public void setArgeoLogger(ArgeoLogger argeoLogger) {
- this.argeoLogger = argeoLogger;
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.useradmin;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.argeo.cms.ArgeoLogListener;
-import org.eclipse.jface.viewers.ILazyContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-
-/** A content provider maintaining an array of lines */
-class LogContentProvider implements ILazyContentProvider, ArgeoLogListener {
- private static final long serialVersionUID = -2084872367738339721L;
-
- private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
-
- private final Long start;
- /** current - start = line number. first line is number '1' */
- private Long current;
-
- // TODO make it configurable
- private final Integer maxLineBufferSize = 10 * 1000;
-
- private final TableViewer viewer;
- private LinkedList<LogLine> lines;
-
- public LogContentProvider(TableViewer viewer) {
- this.viewer = viewer;
- start = System.currentTimeMillis();
- lines = new LinkedList<LogLine>();
- current = start;
- }
-
- public synchronized void dispose() {
- lines.clear();
- lines = null;
- }
-
- @SuppressWarnings("unchecked")
- public synchronized void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- List<String> lin = (List<String>) newInput;
- if (lin == null)
- return;
- for (String line : lin) {
- addLine(line);
- }
- this.viewer.setItemCount(lines.size());
- }
-
- public void updateElement(int index) {
- viewer.replace(lines.get(index), index);
- }
-
- public synchronized void appendLog(String username, Long timestamp,
- String level, String category, String thread, Object msg,
- String[] exception) {
- // check if valid
- if (lines == null)
- return;
-
- String message = msg.toString();
- int count = 0;
- String prefix = prefix(username, timestamp, level, category, thread)
- .toString();
- // String suffix = suffix(username, timestamp, level, category, thread);
- for (String line : message.split("\n")) {
- addLine(count == 0 ? prefix + line : line);
- count++;
- }
-
- if (exception != null) {
- for (String ste : exception) {
- addLine(ste);
- }
- }
-
- viewer.getTable().getDisplay().asyncExec(new Runnable() {
- public void run() {
- if (lines == null)
- return;
- viewer.setItemCount(lines.size());
- // doesn't work with syncExec
- scrollToLastLine();
- }
- });
- }
-
- protected StringBuffer prefix(String username, Long timestamp,
- String level, String category, String thread) {
- StringBuffer buf = new StringBuffer("");
- buf.append(dateFormat.format(new Date(timestamp))).append(" ");
- // buf.append(level).append(" ");
- return buf;
- }
-
- /** Normalize string to the given size */
- protected String norm(String str, Integer size) {
- int length = str.length();
- if (length == size)
- return str;
- else if (length > size)
- return str.substring(0, size);
- else {
- char[] arr = new char[size - length];
- Arrays.fill(arr, ' ');
- return str + new String(arr);
- }
- }
-
- // protected String suffix(String username, Long timestamp, String level,
- // String category, String thread) {
- // return "";
- // }
-
- /** Scroll to the last line */
- protected synchronized void scrollToLastLine() {
- // we try to show last line with two methods
- // viewer.reveal(lines.peekLast());
-
- Table table = viewer.getTable();
- TableItem ti = table.getItem(table.getItemCount() - 1);
- table.showItem(ti);
- }
-
- protected synchronized LogLine addLine(String line) {
- // check for maximal size and purge if necessary
- while (lines.size() >= maxLineBufferSize) {
- for (int i = 0; i < maxLineBufferSize / 10; i++) {
- lines.poll();
- }
- }
-
- current++;
- LogLine logLine = new LogLine(current, line);
- lines.add(logLine);
- return logLine;
- }
-
- private class LogLine {
- private Long linenumber;
- private String message;
-
- public LogLine(Long linenumber, String message) {
- this.linenumber = linenumber;
- this.message = message;
- }
-
- @Override
- public int hashCode() {
- return linenumber.intValue();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof LogLine)
- return ((LogLine) obj).linenumber.equals(linenumber);
- else
- return false;
- }
-
- @Override
- public String toString() {
- return message;
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.useradmin;
-
-import java.util.ArrayList;
-
-import org.argeo.cms.ArgeoLogListener;
-import org.argeo.cms.ArgeoLogger;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Display log lines with a virtual table. Register and unregisters a
- * {@link ArgeoLogListener} via OSGi services.
- */
-public class LogView extends ViewPart {
- public static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".logView";
-
- private TableViewer viewer;
-
- private LogContentProvider logContentProvider;
- private ArgeoLogger argeoLogger;
-
- @Override
- public void createPartControl(Composite parent) {
- Font font = JFaceResources.getTextFont();
- Table table = new Table(parent, SWT.VIRTUAL | SWT.MULTI | SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
- table.setFont(font);
-
- viewer = new TableViewer(table);
- viewer.setLabelProvider(new LabelProvider());
- logContentProvider = new LogContentProvider(viewer);
- viewer.setContentProvider(logContentProvider);
- // viewer.setUseHashlookup(true);
- viewer.setInput(new ArrayList<String>());
-
- if (argeoLogger != null)
- argeoLogger.register(logContentProvider, 1000);
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- @Override
- public void dispose() {
- if (argeoLogger != null)
- argeoLogger.unregister(logContentProvider);
- }
-
- public void setArgeoLogger(ArgeoLogger argeoLogger) {
- this.argeoLogger = argeoLogger;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.useradmin;
-
-import java.util.TreeSet;
-
-import org.argeo.cms.auth.CurrentUser;
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.part.ViewPart;
-
-/** Information about the currently logged in user */
-public class UserProfile extends ViewPart {
- public static String ID = WorkbenchUiPlugin.PLUGIN_ID + ".userProfile";
-
- private TableViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new GridLayout(2, false));
-
- // Authentication authentication = CurrentUser.getAuthentication();
- // EclipseUiUtils.createGridLL(parent, "Name", authentication
- // .getPrincipal().toString());
- EclipseUiUtils.createGridLL(parent, "User ID",
- CurrentUser.getUsername());
-
- // roles table
- Table table = new Table(parent, SWT.V_SCROLL | SWT.BORDER);
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- table.setLinesVisible(false);
- table.setHeaderVisible(false);
- viewer = new TableViewer(table);
- viewer.setContentProvider(new RolesContentProvider());
- viewer.setLabelProvider(new LabelProvider());
- getViewSite().setSelectionProvider(viewer);
- viewer.setInput(getViewSite());
- }
-
- @Override
- public void setFocus() {
- viewer.getTable();
- }
-
- private class RolesContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -4576917440167866233L;
-
- public Object[] getElements(Object inputElement) {
- return new TreeSet<String>(CurrentUser.roles()).toArray();
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.util;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.cms.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.Parameterization;
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.menus.CommandContributionItem;
-import org.eclipse.ui.menus.CommandContributionItemParameter;
-import org.eclipse.ui.services.IServiceLocator;
-
-/**
- * Centralises useful and generic methods when dealing with commands in an
- * Eclipse Workbench context
- */
-public class CommandUtils {
-
- /**
- * Commodities the refresh of a single command with no parameter in a
- * Menu.aboutToShow method to simplify further development
- *
- * Note: that this method should be called with a false show command flag to
- * remove a contribution that have been previously contributed
- */
- public static void refreshCommand(IMenuManager menuManager, IServiceLocator locator, String cmdId, String label,
- ImageDescriptor icon, boolean showCommand) {
- refreshParameterizedCommand(menuManager, locator, cmdId, label, icon, showCommand, null);
- }
-
- /**
- * Commodities the refresh the contribution of a command with a map of
- * parameters in a context menu
- *
- * The command ID is used has contribution item ID
- */
- public static void refreshParameterizedCommand(IMenuManager menuManager, IServiceLocator locator, String cmdId,
- String label, ImageDescriptor icon, boolean showCommand, Map<String, String> params) {
- refreshParameterizedCommand(menuManager, locator, cmdId, cmdId, label, icon, showCommand, params);
- }
-
- /**
- * Commodities the refresh the contribution of a command with a map of
- * parameters in a context menu
- *
- * @param menuManager
- * @param locator
- * @param contributionId
- * @param commandId
- * @param label
- * @param icon
- * @param showCommand
- * @param params
- */
- public static void refreshParameterizedCommand(IMenuManager menuManager, IServiceLocator locator,
- String contributionId, String commandId, String label, ImageDescriptor icon, boolean showCommand,
- Map<String, String> params) {
- IContributionItem ici = menuManager.find(contributionId);
- if (ici != null)
- menuManager.remove(ici);
- if (showCommand) {
- CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter(locator,
- null, commandId, SWT.PUSH);
-
- // Set Params
- contributionItemParameter.label = label;
- contributionItemParameter.icon = icon;
-
- if (params != null)
- contributionItemParameter.parameters = params;
-
- CommandContributionItem cci = new CommandContributionItem(contributionItemParameter);
- cci.setId(contributionId);
- menuManager.add(cci);
- }
- }
-
- /** Helper to call a command without parameter easily */
- public static void callCommand(String commandID) {
- callCommand(commandID, null);
- }
-
- /** Helper to call a command with a single parameter easily */
- public static void callCommand(String commandID, String parameterID, String parameterValue) {
- Map<String, String> params = new HashMap<String, String>();
- params.put(parameterID, parameterValue);
- callCommand(commandID, params);
- }
-
- /**
- * Helper to call a command with a map of parameters easily
- *
- * @param paramMap
- * a map that links various command IDs with corresponding String
- * values.
- */
- public static void callCommand(String commandID, Map<String, String> paramMap) {
- try {
- IWorkbench iw = WorkbenchUiPlugin.getDefault().getWorkbench();
- IHandlerService handlerService = (IHandlerService) iw.getService(IHandlerService.class);
- ICommandService cmdService = (ICommandService) iw.getActiveWorkbenchWindow()
- .getService(ICommandService.class);
- Command cmd = cmdService.getCommand(commandID);
-
- ArrayList<Parameterization> parameters = null;
- ParameterizedCommand pc;
-
- if (paramMap != null) {
- // Set parameters of the command to launch :
- parameters = new ArrayList<Parameterization>();
- Parameterization parameterization;
-
- for (String id : paramMap.keySet()) {
- parameterization = new Parameterization(cmd.getParameter(id), paramMap.get(id));
- parameters.add(parameterization);
- }
- pc = new ParameterizedCommand(cmd, parameters.toArray(new Parameterization[parameters.size()]));
- } else
- pc = new ParameterizedCommand(cmd, null);
-
- // execute the command
- handlerService.executeCommand(pc, null);
- } catch (Exception e) {
- throw new EclipseUiException("Unexpected error while" + " calling the command " + commandID, e);
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.util;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.Job;
-
-/**
- * Propagate authentication to an eclipse job. Typically to execute a privileged
- * action outside the UI thread
- */
-public abstract class PrivilegedJob extends Job {
- private final Subject subject;
-
- public PrivilegedJob(String jobName) {
- this(jobName, AccessController.getContext());
- }
-
- public PrivilegedJob(String jobName,
- AccessControlContext accessControlContext) {
- super(jobName);
- subject = Subject.getSubject(accessControlContext);
-
- // Must be called *before* the job is scheduled,
- // it is required for the progress window to appear
- setUser(true);
- }
-
- @Override
- protected IStatus run(final IProgressMonitor progressMonitor) {
- PrivilegedAction<IStatus> privilegedAction = new PrivilegedAction<IStatus>() {
- public IStatus run() {
- return doRun(progressMonitor);
- }
- };
- return Subject.doAs(subject, privilegedAction);
- }
-
- /**
- * Implement here what should be executed with default context
- * authentication
- */
- protected abstract IStatus doRun(IProgressMonitor progressMonitor);
-}
+++ /dev/null
-package org.argeo.cms.ui.workbench.util;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.argeo.cms.auth.CurrentUser;
-import org.eclipse.ui.AbstractSourceProvider;
-
-/**
- * Provides the roles of the current user as a variable to be used for activity
- * binding
- */
-public class RolesSourceProvider extends AbstractSourceProvider {
- public final static String ROLES_VARIABLE = "roles";
- private final static String[] PROVIDED_SOURCE_NAMES = new String[] { ROLES_VARIABLE };
-
- public Map<String, Set<String>> getCurrentState() {
- Map<String, Set<String>> stateMap = new HashMap<String, Set<String>>();
- stateMap.put(ROLES_VARIABLE, CurrentUser.roles());
- return stateMap;
- }
-
- public String[] getProvidedSourceNames() {
- return PROVIDED_SOURCE_NAMES;
- }
-
- public void updateRoles() {
- fireSourceChanged(0, getCurrentState());
- }
-
- public void dispose() {
- }
-}
+++ /dev/null
-package org.argeo.eclipse.spring;\r
-\r
-import static java.text.MessageFormat.format;\r
-\r
-import org.argeo.api.cms.CmsLog;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.osgi.framework.Bundle;\r
-import org.osgi.framework.BundleContext;\r
-import org.osgi.framework.BundleException;\r
-import org.osgi.framework.FrameworkUtil;\r
-import org.osgi.framework.InvalidSyntaxException;\r
-import org.osgi.util.tracker.ServiceTracker;\r
-import org.springframework.context.ApplicationContext;\r
-\r
-/** Tracks Spring application context published as services. */\r
-class ApplicationContextTracker {\r
- private final static CmsLog log = CmsLog\r
- .getLog(ApplicationContextTracker.class);\r
-\r
- private static final String FILTER = "(&(objectClass=org.springframework.context.ApplicationContext)" //$NON-NLS-1$\r
- + "(org.springframework.context.service.name={0}))"; //$NON-NLS-1$\r
-\r
- public final static String APPLICATION_CONTEXT_TRACKER_TIMEOUT = "org.argeo.eclipse.spring.applicationContextTrackerTimeout";\r
-\r
- private static Long defaultTimeout = Long.parseLong(System.getProperty(\r
- APPLICATION_CONTEXT_TRACKER_TIMEOUT, "30000"));\r
-\r
- @SuppressWarnings("rawtypes")\r
- private ServiceTracker applicationContextServiceTracker;\r
-\r
- /**\r
- * @param contributorBundle\r
- * OSGi bundle for which the Spring application context is to be\r
- * tracked. Must not be null!\r
- * @param factoryBundleContext\r
- * BundleContext object which can be used to track services\r
- * @throws IllegalArgumentException\r
- * if the given bundle is null.\r
- */\r
- @SuppressWarnings({ "unchecked", "rawtypes" })\r
- public ApplicationContextTracker(final Bundle contributorBundle,\r
- final BundleContext factoryBundleContext) {\r
- final String filter = format(FILTER,\r
- contributorBundle.getSymbolicName());\r
- try {\r
- applicationContextServiceTracker = new ServiceTracker(\r
- factoryBundleContext, FrameworkUtil.createFilter(filter),\r
- null);\r
- // applicationContextServiceTracker.open();\r
- } catch (final InvalidSyntaxException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- public void open() {\r
- if (applicationContextServiceTracker != null) {\r
- applicationContextServiceTracker.open();\r
- }\r
- }\r
-\r
- public void close() {\r
- if (applicationContextServiceTracker != null) {\r
- applicationContextServiceTracker.close();\r
- }\r
- }\r
-\r
- public ApplicationContext getApplicationContext() {\r
- ApplicationContext applicationContext = null;\r
- if (applicationContextServiceTracker != null) {\r
- try {\r
- applicationContext = (ApplicationContext) applicationContextServiceTracker\r
- .waitForService(defaultTimeout);\r
- } catch (InterruptedException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- return applicationContext;\r
- }\r
-\r
- @Override\r
- protected void finalize() throws Throwable {\r
- close();\r
- super.finalize();\r
- }\r
-\r
- static ApplicationContext getApplicationContext(String bundleSymbolicName) {\r
- Bundle contributorBundle = Platform.getBundle(bundleSymbolicName);\r
- return getApplicationContext(contributorBundle);\r
- }\r
-\r
- static ApplicationContext getApplicationContext(\r
- final Bundle contributorBundle) {\r
- if (log.isTraceEnabled())\r
- log.trace("Get application context for bundle " + contributorBundle);\r
-\r
- // Start if not yet started (also if in STARTING state, may be lazy)\r
- if (contributorBundle.getState() != Bundle.ACTIVE) {\r
- if (log.isTraceEnabled())\r
- log.trace("Starting bundle: "\r
- + contributorBundle.getSymbolicName());\r
- // Thread startBundle = new Thread("Start bundle "\r
- // + contributorBundle.getSymbolicName()) {\r
- // public void run() {\r
- try {\r
- contributorBundle.start();\r
- } catch (BundleException e) {\r
- log.error("Cannot start bundle " + contributorBundle, e);\r
- }\r
- // }\r
- // };\r
- // startBundle.start();\r
- // try {\r
- // startBundle.join(10 * 1000l);\r
- // } catch (InterruptedException e) {\r
- // // silent\r
- // }\r
- }\r
-\r
- final ApplicationContextTracker applicationContextTracker = new ApplicationContextTracker(\r
- contributorBundle, contributorBundle.getBundleContext());\r
- ApplicationContext applicationContext = null;\r
- try {\r
- applicationContextTracker.open();\r
- applicationContext = applicationContextTracker\r
- .getApplicationContext();\r
- } finally {\r
- applicationContextTracker.close();\r
- }\r
- return applicationContext;\r
- }\r
-}\r
+++ /dev/null
-package org.argeo.eclipse.spring;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.EclipseUiException;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.IHandler;
-import org.eclipse.core.commands.IHandlerListener;
-import org.springframework.context.ApplicationContext;
-
-/** Allows to declare Eclipse commands as Spring beans */
-public class SpringCommandHandler implements IHandler {
- private final static CmsLog log = CmsLog
- .getLog(SpringCommandHandler.class);
-
- public void addHandlerListener(IHandlerListener handlerListener) {
- }
-
- public void dispose() {
- }
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String commandId = event.getCommand().getId();
- String bundleSymbolicName = commandId.substring(0,
- commandId.lastIndexOf('.'));
- try {
- if (log.isTraceEnabled())
- log.trace("Execute " + event + " via spring command handler "
- + this);
- // TODO: make it more flexible and robust
- ApplicationContext applicationContext = ApplicationContextTracker
- .getApplicationContext(bundleSymbolicName);
- if (applicationContext == null)
- throw new EclipseUiException(
- "No application context found for "
- + bundleSymbolicName);
-
- // retrieve the command via its id
- String beanName = event.getCommand().getId();
-
- if (!applicationContext.containsBean(beanName)) {
- if (beanName.startsWith(bundleSymbolicName))
- beanName = beanName
- .substring(bundleSymbolicName.length() + 1);
- }
-
- if (!applicationContext.containsBean(beanName))
- throw new ExecutionException("No bean found with name "
- + beanName + " in bundle " + bundleSymbolicName);
- Object bean = applicationContext.getBean(beanName);
-
- if (!(bean instanceof IHandler))
- throw new ExecutionException("Bean with name " + beanName
- + " and class " + bean.getClass()
- + " does not implement the IHandler interface.");
-
- IHandler handler = (IHandler) bean;
- return handler.execute(event);
- } catch (Exception e) {
- // TODO: use eclipse error management
- // log.error(e);
- throw new ExecutionException("Cannot execute Spring command "
- + commandId + " in bundle " + bundleSymbolicName, e);
- }
- }
-
- public boolean isEnabled() {
- return true;
- }
-
- public boolean isHandled() {
- return true;
- }
-
- public void removeHandlerListener(IHandlerListener handlerListener) {
- }
-}
+++ /dev/null
-package org.argeo.eclipse.spring;\r
-\r
-import org.argeo.eclipse.ui.EclipseUiException;\r
-import org.eclipse.core.runtime.CoreException;\r
-import org.eclipse.core.runtime.IConfigurationElement;\r
-import org.eclipse.core.runtime.IExecutableExtension;\r
-import org.eclipse.core.runtime.IExecutableExtensionFactory;\r
-import org.eclipse.core.runtime.IExtension;\r
-import org.springframework.context.ApplicationContext;\r
-\r
-/**\r
- * The Spring Extension Factory builds a bridge between the Eclipse Extension\r
- * Registry and the Spring Framework (especially Spring Dynamic Modules).\r
- * \r
- * It allows you to define your extension as a spring bean within the spring\r
- * application context of your bundle. If you would like to use this bean as an\r
- * instance of an extension (an Eclipse RCP view, for example) you define the\r
- * extension with this spring extension factory as the class to be created.\r
- * \r
- * To let the spring extension factory pick the right bean from your application\r
- * context you need to set the bean id to the same value as the id of the view\r
- * within the view definition, for example. This is important if your extension\r
- * definition contains more than one element, where each element has its own id.\r
- * \r
- * If the extension definition elements themselves have no id attribute the\r
- * spring extension factory uses the id of the extension itself to identify the\r
- * bean.\r
- * \r
- * original code from: <a href=\r
- * "http://martinlippert.blogspot.com/2008/10/new-version-of-spring-extension-factory.html"\r
- * >Blog entry</a>\r
- */\r
-public class SpringExtensionFactory implements IExecutableExtensionFactory,\r
- IExecutableExtension {\r
-\r
- private Object bean;\r
-\r
- public Object create() throws CoreException {\r
- if (bean == null)\r
- throw new EclipseUiException("No underlying bean for extension");\r
- return bean;\r
- }\r
-\r
- public void setInitializationData(IConfigurationElement config,\r
- String propertyName, Object data) throws CoreException {\r
- String bundleSymbolicName = config.getContributor().getName();\r
- ApplicationContext applicationContext = ApplicationContextTracker\r
- .getApplicationContext(bundleSymbolicName);\r
- if (applicationContext == null)\r
- throw new EclipseUiException(\r
- "Cannot find application context for bundle "\r
- + bundleSymbolicName);\r
-\r
- String beanName = getBeanName(data, config);\r
- if (beanName == null)\r
- throw new EclipseUiException("Cannot find bean name for extension "\r
- + config);\r
-\r
- if (!applicationContext.containsBean(beanName)) {\r
- if (beanName.startsWith(bundleSymbolicName))\r
- beanName = beanName.substring(bundleSymbolicName.length() + 1);\r
- }\r
-\r
- if (!applicationContext.containsBean(beanName))\r
- throw new EclipseUiException("No bean with name '" + beanName + "'");\r
-\r
- this.bean = applicationContext.getBean(beanName);\r
- if (this.bean instanceof IExecutableExtension) {\r
- ((IExecutableExtension) this.bean).setInitializationData(config,\r
- propertyName, data);\r
- }\r
- }\r
-\r
- private String getBeanName(Object data, IConfigurationElement config) {\r
-\r
- // try the specific bean id the extension defines\r
- if (data != null && data.toString().length() > 0) {\r
- return data.toString();\r
- }\r
-\r
- // try the id of the config element\r
- if (config.getAttribute("id") != null) {\r
- return config.getAttribute("id");\r
- }\r
-\r
- // try the id of the extension element itself\r
- if (config.getParent() != null\r
- && config.getParent() instanceof IExtension) {\r
- IExtension extensionDefinition = (IExtension) config.getParent();\r
- return extensionDefinition.getSimpleIdentifier();\r
- }\r
-\r
- return null;\r
- }\r
-}\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.ext.rap.ui.workbench</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments />
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments />
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:util="http://www.springframework.org/schema/util"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
- http://www.springframework.org/schema/util\r
- http://www.springframework.org/schema/util/spring-util-2.5.xsd">\r
-\r
- <service interface="org.eclipse.rap.rwt.application.ApplicationConfiguration">\r
- <service-properties>\r
- <beans:entry key="contextName" value="ui" />\r
- </service-properties>\r
- <beans:bean\r
- class="org.eclipse.rap.ui.internal.servlet.WorkbenchApplicationConfiguration" />\r
- </service>\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-Bundle-SymbolicName: org.argeo.ext.rap.ui.workbench;singleton:=true
-Bundle-ActivationPolicy: lazy
-
-Fragment-Host: org.eclipse.rap.ui.workbench
+++ /dev/null
-source.. = src/,\
- ext/test/
+++ /dev/null
-<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.legacy.commons</groupId>
- <artifactId>argeo-commons-legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.ext.rap.ui.workbench</artifactId>
- <name>Extension RAP Workbench</name>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>argeo-commons-legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <name>Commons Legacy</name>
- <packaging>pom</packaging>
- <properties>
- <version.argeo-tp-extras>2.1.13</version.argeo-tp-extras>
- </properties>
- <modules>
- <module>org.argeo.cms.ui.workbench</module>
- <module>org.argeo.cms.ui.workbench.rap</module>
- <module>org.argeo.ext.rap.ui.workbench</module>
- <module>dep</module>
- </modules>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.argeo.tp.extras</groupId>
- <artifactId>argeo-tp-extras</artifactId>
- <version>${version.argeo-tp-extras}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <repositories>
- <repository>
- <id>argeo</id>
- <url>http://forge.argeo.org/data/java/argeo-2.1/</url>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>daily</updatePolicy>
- <checksumPolicy>warn</checksumPolicy>
- </releases>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- <repository>
- <id>argeo-extras</id>
- <url>http://forge.argeo.org/data/java/argeo-extras-2.1/</url>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>daily</updatePolicy>
- <checksumPolicy>warn</checksumPolicy>
- </releases>
- </repository>
- </repositories>
- <profiles>
- <profile>
- <id>localrepo</id>
- <repositories>
- <repository>
- <id>argeo-extras</id>
- <url>http://localhost:7080/data/java/argeo-extras-2.1</url>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>daily</updatePolicy>
- <checksumPolicy>warn</checksumPolicy>
- </releases>
- </repository>
- </repositories>
- </profile>
- </profiles>
-
-</project>
\ No newline at end of file
+++ /dev/null
--include: ../../cnf/maven.bnd
\ No newline at end of file
+++ /dev/null
--include: ../../cnf/maven.bnd
\ No newline at end of file
+++ /dev/null
-/target/
-/org.argeo.slc.dep.backend-maven.target
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-properties.1.name=org.eclipse.equinox.p2.type.category
-properties.1.value=true
\ No newline at end of file
+++ /dev/null
-<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>
- <artifactId>legacy-dep</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.dep.backend</artifactId>
- <name>SLC Backend</name>
- <dependencies>
- <!-- SLC Minimal -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.dep.spring</artifactId>
- <version>2.3-SNAPSHOT</version>
- <type>pom</type>
- </dependency>
-
- <!-- SLC Libs -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.slc</groupId> -->
- <!-- <artifactId>org.argeo.slc.lib.repo</artifactId> -->
- <!-- <version>1.1.14-SNAPSHOT</version> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.slc</groupId> -->
- <!-- <artifactId>org.argeo.slc.lib.jcr</artifactId> -->
- <!-- <version>1.1.14-SNAPSHOT</version> -->
- <!-- </dependency> -->
-
- <!-- Extensions -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.support</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.server.repo</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.slc</groupId> -->
- <!-- <artifactId>org.argeo.slc.server.repo.webapp</artifactId> -->
- <!-- <version>2.1.1-SNAPSHOT</version> -->
- <!-- </dependency> -->
-
- <!-- UI -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.client.ui</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.client.ui.dist</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.client.rap</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Legacy Argeo Commons platform (Eclipse 3) -->
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.dep.cms.platform</artifactId>
- <version>${version.argeo-commons-legacy}</version>
- <type>pom</type>
- </dependency>
-
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>com.googlecode.javaewah.JavaEWAH</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>org.eclipse.jgit</artifactId>
- </dependency>
- </dependencies>
- <profiles>
- <profile>
- <id>rpmbuild</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-source</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <descriptorRefs>
- <descriptorRef>a2-source</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>rpm-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rpm-argeo</id>
- <phase>package</phase>
- <goals>
- <goal>rpm</goal>
- </goals>
- <configuration>
- <name>argeo-slc-platform${argeo.rpm.suffix}</name>
- <mappings>
- <mapping>
- <directory>/usr/share/osgi</directory>
- <username>root</username>
- <groupname>root</groupname>
- <filemode>644</filemode>
- <directoryIncluded>true</directoryIncluded>
- <sources>
- <source>
- <location>${project.build.directory}/${project.artifactId}-${project.version}-a2-source</location>
- <includes>
- <include>**/*.jar</include>
- </includes>
- </source>
- </sources>
- </mapping>
- </mappings>
- <requires>
- <require>argeo-cms-platform${argeo.rpm.suffix}</require>
- <require>argeo-slc-spring${argeo.rpm.suffix}</require>
- </requires>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
+++ /dev/null
-/target/
-/*.target
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<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>
- <artifactId>legacy-dep</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.dep.spring</artifactId>
- <name>SLC Agent based on Spring</name>
- <dependencies>
- <!-- Parent dependencies -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.dep.minimal</artifactId>
- <version>2.3-SNAPSHOT</version>
- <type>pom</type>
- </dependency>
-
- <!-- Spring-based Agent -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.spring</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.support</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.agent</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.agent.jcr</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Transitional fake Java 8 APIs, required by old version of Spring,
- in the process of being removed -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.legacy.fake.java8</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Spring dependencies -->
- <dependency>
- <groupId>org.argeo.tp.apache</groupId>
- <artifactId>org.apache.log4j</artifactId>
- </dependency>
- <!-- Not strictly Spring dependencies but used by the old approach -->
- <dependency>
- <groupId>org.argeo.tp.apache.ant</groupId>
- <artifactId>org.apache.ant</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.apache.ant</groupId>
- <artifactId>org.apache.ant.launch</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.javax</groupId>
- <artifactId>javax.mail</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>com.jcraft.jsch</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.apache.commons</groupId>
- <artifactId>org.apache.commons.vfs</artifactId>
- </dependency>
-
- <!-- Base Spring dependency -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.javax</groupId>
- <artifactId>javax.el</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.extender</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.io</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>org.aspectj.weaver</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>org.aopalliance</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.expression</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.instrument</artifactId>
- </dependency>
-
- <!-- Spring -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.aspects</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context.support</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.tx</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.web.servlet</artifactId>
- </dependency>
-
- <!-- CLI Agent -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.slc</groupId> -->
- <!-- <artifactId>org.argeo.slc.launcher</artifactId> -->
- <!-- <version>1.1.12-SNAPSHOT</version> -->
- <!-- </dependency> -->
- <!-- <dependency> -->
- <!-- <groupId>org.argeo.slc</groupId> -->
- <!-- <artifactId>org.argeo.slc.agent.cli</artifactId> -->
- <!-- <version>2.1.1-SNAPSHOT</version> -->
- <!-- </dependency> -->
- </dependencies>
- <profiles>
- <profile>
- <id>rpmbuild</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-source</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <descriptorRefs>
- <descriptorRef>a2-source</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>rpm-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rpm-argeo</id>
- <phase>package</phase>
- <goals>
- <goal>rpm</goal>
- </goals>
- <configuration>
- <name>argeo-slc-spring${argeo.rpm.suffix}</name>
- <mappings>
- <mapping>
- <directory>/usr/share/osgi</directory>
- <username>root</username>
- <groupname>root</groupname>
- <filemode>644</filemode>
- <directoryIncluded>true</directoryIncluded>
- <sources>
- <source>
- <location>${project.build.directory}/${project.artifactId}-${project.version}-a2-source</location>
- <includes>
- <include>**/*.jar</include>
- </includes>
- </source>
- </sources>
- </mapping>
- </mappings>
- <requires>
- <require>argeo-cms-node${argeo.rpm.suffix}</require>
- <require>argeo-slc${argeo.rpm.suffix}</require>
- <require>argeo-slc-tp${argeo.rpm.suffix}</require>
- <require>argeo-slc-spring-tp${argeo.rpm.suffix}</require>
- </requires>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- <profile>
- <id>rpmbuild-tp</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>prepare-source-tp</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <descriptorRefs>
- <descriptorRef>a2-source-tp</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>rpm-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rpm-tp</id>
- <phase>package</phase>
- <goals>
- <goal>rpm</goal>
- </goals>
- <configuration>
- <name>argeo-slc-spring-tp${argeo.rpm.suffix}</name>
- <projversion>${version.argeo-tp}</projversion>
- <release>${argeo.rpm.release.tp}</release>
- <mappings>
- <mapping>
- <directory>/usr/share/osgi</directory>
- <username>root</username>
- <groupname>root</groupname>
- <filemode>644</filemode>
- <directoryIncluded>false</directoryIncluded>
- <sources>
- <source>
- <location>${project.build.directory}/${project.artifactId}-${project.version}-a2-source-tp</location>
- <includes>
- <include>**/*.jar</include>
- </includes>
- </source>
- </sources>
- </mapping>
- </mappings>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>legacy-dep</artifactId>
- <name>SLC Legacy Dependencies</name>
- <packaging>pom</packaging>
- <modules>
- <module>org.argeo.slc.dep.spring</module>
- <module>org.argeo.slc.dep.backend</module>
- </modules>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <SLC-ModularDistribution>default</SLC-ModularDistribution>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>properties-maven-plugin</artifactId>
- <configuration>
- <quiet>true</quiet>
- <files>
- <file>../../../cnf/${version.context}.bnd</file>
- </files>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.argeo.maven.plugins</groupId>
- <artifactId>argeo-osgi-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-descriptors</id>
- <goals>
- <goal>descriptors</goal>
- </goals>
- <phase>generate-resources</phase>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <attach>false</attach>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.tp.equinox</groupId>
- <artifactId>org.eclipse.osgi</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.sdk</groupId>
- <artifactId>org.junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.sdk</groupId>
- <artifactId>org.hamcrest</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <profiles>
- <profile>
- <id>check-osgi</id>
- <build>
- <plugins>
- <plugin>
- <groupId>org.argeo.maven.plugins</groupId>
- <artifactId>argeo-osgi-plugin</artifactId>
- <executions>
- <execution>
- <id>check-osgi</id>
- <phase>test</phase>
- <goals>
- <goal>equinox</goal>
- </goals>
- <configuration>
- <onlyCheck>true</onlyCheck>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.init</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>lib</artifactId>
- <packaging>pom</packaging>
- <name>SLC Standard Libs</name>
- <description>SLC execution modules for generic tasks, to be used as parent pom</description>
- <properties>
- <additionalImports.slc-lib>
- com.jcraft.jsch;resolution:=optional,
- org.apache.commons.exec;resolution:=optional,
- </additionalImports.slc-lib>
- </properties>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <SLC-ExecutionModule>default</SLC-ExecutionModule>
- <!-- Minimal imports + some optional convenience imports -->
- <Import-Package>
- org.argeo.security.jackrabbit;resolution:="optional",
- org.springframework.cglib.proxy;resolution:="optional",
- org.springframework.cglib.core;resolution:="optional",
- org.springframework.cglib.reflect;resolution:="optional",
- org.aopalliance.aop;resolution:="optional",
- org.argeo.slc.runtime,
- org.argeo.slc.core.execution;resolution:="optional",
- org.argeo.slc.core.execution.tasks;resolution:="optional",
- org.argeo.slc.execution,
- org.argeo.slc.osgi;resolution:="optional",
- org.argeo.slc.test,
- org.springframework.aop;resolution:="optional",
- org.springframework.aop.framework;resolution:="optional",
- org.springframework.aop.scope;resolution:="optional",
- org.springframework.beans.factory.config;resolution:="optional",
- org.springframework.core.io;resolution:="optional",
- ${additionalImports.slc-lib},
- *
- </Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.dep.minimal</artifactId>
- <version>2.3-SNAPSHOT</version>
- <type>pom</type>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11"/>>>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-/bin/
-/target/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.legacy.fake.java8</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-Export-Package: javax.*;version=0.0.0,\
-org.omg.*;version=0.0.0
+++ /dev/null
-bin.includes = META-INF/
-jars.compile.order = .
-source.. = src/
-output.. = target/classes/
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.legacy.fake.java8</artifactId>
- <name>Legacy Fake Java 8 APIs</name>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-RequiredExecutionEnvironment>JavaSE-11</Bundle-RequiredExecutionEnvironment>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
+++ /dev/null
-package javax.rmi;
-
-public class Fake {
-
-}
+++ /dev/null
-package javax.xml.ws;
-
-public class Fake {
-
-}
+++ /dev/null
-package org.omg.CORBA;
-
-public class Fake {
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.agent.jcr</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:util="http://www.springframework.org/schema/util"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
- http://www.springframework.org/schema/util\r
- http://www.springframework.org/schema/util/spring-util-2.5.xsd">\r
-\r
- <!-- REFERENCES -->\r
- <reference id="repository" interface="javax.jcr.Repository"\r
- filter="(cn=slc)" />\r
-\r
-<!-- <reference id="authenticationManager" -->\r
-<!-- interface="org.springframework.security.authentication.AuthenticationManager" /> -->\r
-\r
- <reference id="modulesManager"\r
- interface="org.argeo.slc.execution.ExecutionModulesManager" />\r
-\r
- <!-- SERVICES -->\r
-<!-- <service ref="attachmentUploader" interface="org.argeo.slc.core.attachment.AttachmentUploader" /> -->\r
-\r
- <service interface="org.argeo.slc.execution.ExecutionModulesListener"\r
- ref="executionModulesListener" />\r
-\r
- <service ref="agent" interface="org.argeo.slc.execution.SlcAgent" />\r
- <service ref="agentCli" interface="org.argeo.slc.execution.SlcAgentCli" />\r
-\r
- <service ref="fileSystemManager" interface="org.apache.commons.vfs2.FileSystemManager" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean id="agent" class="org.argeo.slc.jcr.execution.JcrAgent"\r
- init-method="init" destroy-method="destroy">\r
- <property name="defaultModulePrefix" value="org.argeo.slc.lib" />\r
- <property name="repository" ref="repository" />\r
- <property name="modulesManager" ref="modulesManager" />\r
- </bean>\r
-\r
- <bean id="agentCli" class="org.argeo.slc.core.execution.DefaultAgentCli">\r
- <property name="agent" ref="agent" />\r
-<!-- <property name="authenticationManager" ref="authenticationManager" /> -->\r
- </bean>\r
-\r
- <bean id="executionModulesListener" class="org.argeo.slc.jcr.execution.JcrExecutionModulesListener"\r
- init-method="init" destroy-method="destroy">\r
- <property name="agent" ref="agent" />\r
- <property name="repository" ref="repository" />\r
- <property name="modulesManager" ref="modulesManager" />\r
- </bean>\r
-\r
- <!-- Thread-bound session is used when multiple threads with various authentication \r
- will call the component -->\r
-<!-- <bean id="session" class="org.argeo.security.jcr.SecureThreadBoundSession"> -->\r
-<!-- <property name="repository" ref="repository" /> -->\r
-<!-- </bean> -->\r
-\r
-<!-- <bean id="attachmentUploader" class="org.argeo.slc.jcr.execution.JcrAttachmentUploader"> -->\r
-<!-- </bean> -->\r
-\r
-\r
- <bean\r
- class="org.argeo.slc.spring.AuthenticatedApplicationContextInitialization">\r
- </bean>\r
-\r
-\r
- <bean name="fileSystemManager" class="org.apache.commons.vfs2.impl.StandardFileSystemManager"\r
- init-method="init" destroy-method="close" />\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-Import-Package: org.argeo.slc.jcr,\
-org.argeo.security.jackrabbit,\
-org.apache.commons.vfs2.provider.bzip2,\
-org.apache.commons.vfs2.provider.compressed,\
-org.apache.commons.vfs2.provider.ftp,\
-org.apache.commons.vfs2.provider.ftps,\
-org.apache.commons.vfs2.provider.gzip,\
-org.apache.commons.vfs2.provider.http,\
-org.apache.commons.vfs2.provider.https,\
-org.apache.commons.vfs2.provider.jar,\
-org.apache.commons.vfs2.provider.local,\
-org.apache.commons.vfs2.provider.ram,\
-org.apache.commons.vfs2.provider.res,\
-org.apache.commons.vfs2.provider.sftp,\
-org.apache.commons.vfs2.provider.tar,\
-org.apache.commons.vfs2.provider.url,\
-org.apache.commons.vfs2.provider.temp,\
-org.apache.commons.vfs2.provider.webdav,\
-org.apache.commons.vfs2.provider.zip,\
-org.osgi.*;version=0.0.0,\
-org.argeo.cms.auth,\
-*
+++ /dev/null
-bin.includes = META-INF/,\
- .
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.agent.jcr</artifactId>
- <name>SLC Agent JCR</name>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.agent</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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
- xsi:schemaLocation="\r
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean\r
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">\r
- <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />\r
- <property name="locations">\r
- <value>osgibundle:agent.properties</value>\r
- </property>\r
- </bean>\r
-\r
- <!-- Manager -->\r
- <bean id="modulesManager" class="org.argeo.slc.osgi.OsgiExecutionModulesManager"\r
- init-method="init" destroy-method="destroy">\r
- <property name="bundlesManager" ref="bundlesManager" />\r
- </bean>\r
-\r
- <bean id="bundlesManager" class="org.argeo.slc.osgi.BundlesManager">\r
- <property name="defaultTimeout" value="${slc.agent.osgi.defaultTimeout}" />\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:util="http://www.springframework.org/schema/util"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <!-- REFERENCES -->\r
- <!-- No <set> so that the equals methods are not called -->\r
- <list id="executionContexts" interface="org.argeo.slc.execution.ExecutionContext"\r
- cardinality="0..N">\r
- <listener ref="modulesManager" bind-method="register"\r
- unbind-method="unregister" />\r
- </list>\r
-\r
- <list id="executionFlows" interface="org.argeo.slc.execution.ExecutionFlow"\r
- cardinality="0..N">\r
- <listener ref="modulesManager" bind-method="register"\r
- unbind-method="unregister" />\r
- </list>\r
-\r
- <list id="executionModulesListeners" interface="org.argeo.slc.execution.ExecutionModulesListener"\r
- cardinality="0..N">\r
- <listener ref="modulesManager" bind-method="register"\r
- unbind-method="unregister" />\r
- </list>\r
-\r
- <list id="executionFlowDescriptorConverters"\r
- interface="org.argeo.slc.execution.ExecutionFlowDescriptorConverter"\r
- cardinality="0..N">\r
- <listener ref="modulesManager" />\r
- </list>\r
- <reference id="userTransaction" interface="org.argeo.osgi.transaction.WorkTransaction" />\r
- <reference id="userAdmin" interface="org.osgi.service.useradmin.UserAdmin" />\r
-\r
- <!-- SERVICES -->\r
- <service ref="modulesManager" interface="org.argeo.slc.execution.ExecutionModulesManager" />\r
-\r
- <!-- LABEL -->\r
-<!-- <beans:bean class="org.argeo.cms.spring.osgi.OsgiModuleLabel"> -->\r
-<!-- <beans:property name="bundleContext" ref="bundleContext" /> -->\r
-<!-- </beans:bean> -->\r
-\r
- <!-- ROLES -->\r
-<!-- <reference id="userAdminService" interface="org.argeo.security.UserAdminService" /> -->\r
-\r
- <beans:bean class="org.argeo.maintenance.SimpleRoleRegistration"\r
- init-method="run">\r
- <beans:property name="role" value="org.argeo.slc.user" />\r
- <beans:property name="userAdmin" ref="userAdmin" />\r
- <beans:property name="userTransaction" ref="userTransaction" />\r
-<!-- <beans:property name="userAdminService" ref="userAdminService" /> -->\r
- </beans:bean>\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-slc.agent.osgi.defaultTimeout=60000
+++ /dev/null
-Import-Package: org.osgi.*;version=0.0.0,\
-*
\ No newline at end of file
+++ /dev/null
-bin.includes = META-INF/,\
- .
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.agent</artifactId>
- <name>SLC Agent</name>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11"/>>>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<projectDescription>\r
- <name>org.argeo.slc.client.rap</name>\r
- <comment></comment>\r
- <projects>\r
- </projects>\r
- <buildSpec>\r
- <buildCommand>\r
- <name>org.eclipse.jdt.core.javabuilder</name>\r
- <arguments>\r
- </arguments>\r
- </buildCommand>\r
- <buildCommand>\r
- <name>org.eclipse.pde.ManifestBuilder</name>\r
- <arguments>\r
- </arguments>\r
- </buildCommand>\r
- <buildCommand>\r
- <name>org.eclipse.pde.SchemaBuilder</name>\r
- <arguments>\r
- </arguments>\r
- </buildCommand>\r
- </buildSpec>\r
- <natures>\r
- <nature>org.eclipse.pde.PluginNature</nature>\r
- <nature>org.eclipse.jdt.core.javanature</nature>\r
- </natures>\r
-</projectDescription>\r
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <!-- RAP Specific open JCR file service -->
- <!-- <bean id="openJcrFileService" class="org.argeo.slc.client.rap.OpenJcrFileService" -->
- <!-- scope="prototype" init-method="init" destroy-method="destroy"> -->
- <!-- <property name="repoService" ref="repoService" /> -->
- <!-- <property name="repositoryFactory" ref="repositoryFactory" /> -->
- <!-- <property name="keyring" ref="keyring" /> -->
- <!-- <property name="nodeRepository" ref="nodeRepository" /> -->
- <!-- </bean> -->
-
- <bean id="org.argeo.slc.client.rap.openJcrFile" class="org.argeo.slc.client.ui.specific.OpenJcrFile"
- scope="prototype">
- <property name="repoService" ref="repoService" />
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
- <bean id="repoService" class="org.argeo.slc.repo.core.RepoServiceImpl">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans\r
- xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:osgi="http://www.springframework.org/schema/osgi"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"\r
- osgi:default-timeout="30000">\r
-\r
- <beans:description>SLC UI RAP</beans:description>\r
-\r
- <reference id="nodeRepository"\r
- interface="javax.jcr.Repository" />\r
- <reference id="repositoryFactory"\r
- interface="javax.jcr.RepositoryFactory" />\r
- <reference id="keyring"\r
- interface="org.argeo.cms.security.CryptoKeyring" />\r
-</beans:beans>\r
+++ /dev/null
-Bundle-SymbolicName: org.argeo.slc.client.rap;singleton=true
-Bundle-ActivationPolicy: lazy
-Bundle-Activator: org.argeo.slc.client.rap.SlcRapPlugin
-Require-Bundle: org.eclipse.ui;resolution:=optional,\
-org.eclipse.core.runtime,\
-org.eclipse.rap.ui;resolution:=optional,\
-org.eclipse.rap.ui.workbench;resolution:=optional
-
-Import-Package: javax.jcr.nodetype,\
-javax.servlet,\
-javax.servlet.http,\
-org.argeo.eclipse.spring,\
-org.argeo.slc.repo.core,\
-org.argeo.cms.ui.util,\
-org.argeo.api.cms,\
-*
-
\ No newline at end of file
+++ /dev/null
-source.. = src/main/java/\r
-output.. = target/classes/\r
-bin.includes = plugin.xml,\\r
- META-INF/,\\r
- .\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<?eclipse version="3.6"?>\r
-<plugin>\r
- <extension\r
- point="org.eclipse.rap.ui.entrypoint">\r
- <entrypoint\r
- id="org.argeo.slc.client.rap.slcSecureRap"\r
- class="org.argeo.slc.client.rap.SlcSecureRap"\r
- path="/slc">\r
- </entrypoint>\r
- </extension>\r
- \r
- <!-- COMMANDS --> \r
- <extension\r
- point="org.eclipse.ui.commands">\r
- <command\r
- id="org.argeo.slc.client.rap.openJcrFile"\r
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"\r
- name="Open Workspace Editor">\r
- <commandParameter\r
- id="param.repoNodePath"\r
- name="Repo node path">\r
- </commandParameter>\r
- <commandParameter\r
- id="param.repoUri"\r
- name="Repo URI">\r
- </commandParameter>\r
- <commandParameter\r
- id="param.workspaceName"\r
- name="Workspace name">\r
- </commandParameter>\r
- <commandParameter\r
- id="param.filePath"\r
- name="File Path">\r
- </commandParameter>\r
- </command>\r
- </extension>\r
-</plugin>\r
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.rap</artifactId>
- <name>SLC Client RAP</name>
- <packaging>jar</packaging>
- <dependencies>
- <!-- SLC -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.repo</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Argeo common distribution for Secured UI -->
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench.rap</artifactId>
- <version>${version.argeo-commons-legacy}</version>
- </dependency>
-
- <!-- RAP workbench -->
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
+++ /dev/null
-package org.argeo.slc.client.rap;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-//import org.eclipse.rap.rwt.service.IServiceHandler;
-
-/**
- * Basic Default service handler that retrieves a file from a NT_FILE JCR node
- * and launch the download.
- */
-public class OpenJcrFileService {//implements IServiceHandler {
-
- /* DEPENDENCY INJECTION */
- final private Node fileNode;
-
- public OpenJcrFileService(Node fileNode) {
- this.fileNode = fileNode;
- }
-
- public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
- // Get the file content
- byte[] download = getFileAsByteArray();
-
- // Send the file in the response
- //HttpServletResponse response = RWT.getResponse();
- response.setContentType("application/octet-stream");
- response.setContentLength(download.length);
- String contentDisposition = null;
- try {
- contentDisposition = "attachment; filename=\""
- + JcrUtils.lastPathElement(fileNode.getPath()) + "\"";
- } catch (RepositoryException e) {
- throw new SlcException("Error while getting file Path " + fileNode,
- e);
- }
- response.setHeader("Content-Disposition", contentDisposition);
-
- try {
- response.getOutputStream().write(download);
- } catch (IOException ioe) {
- throw new SlcException("Error while writing the file " + fileNode
- + " to the servlet response", ioe);
- }
- }
-
- protected byte[] getFileAsByteArray() {
-
- Session businessSession = null;
- try {
- boolean isValid = true;
- Node child = null;
- if (!fileNode.isNodeType(NodeType.NT_FILE))
- isValid = false;
- else {
- child = fileNode.getNode(Property.JCR_CONTENT);
- if (!(child.isNodeType(NodeType.NT_RESOURCE) || child
- .hasProperty(Property.JCR_DATA)))
- isValid = false;
- }
-
- if (!isValid)
- return null;
-
- byte[] ba = null;
- InputStream fis = null;
- try {
- fis = (InputStream) child.getProperty(Property.JCR_DATA)
- .getBinary().getStream();
- ba = IOUtils.toByteArray(fis);
- } catch (Exception e) {
- throw new SlcException("Stream error while opening file "
- + fileNode, e);
- } finally {
- IOUtils.closeQuietly(fis);
- }
- return ba;
-
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while "
- + "opening file node " + fileNode, e);
- } finally {
- JcrUtils.logoutQuietly(businessSession);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.rap;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- *
- * Enable life-cycle management of RAP specific services
- */
-public class SlcRapPlugin extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.argeo.slc.client.rap"; //$NON-NLS-1$
-
- // The shared instance
- private static SlcRapPlugin plugin;
-
- /**
- * The constructor
- */
- public SlcRapPlugin() {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
- * )
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static SlcRapPlugin getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given plug-in
- * relative path
- *
- * @param path
- * the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.rap;
-
-import org.argeo.cms.ui.workbench.rap.RapWindowAdvisor;
-import org.argeo.cms.ui.workbench.rap.RapWorkbenchAdvisor;
-import org.argeo.cms.ui.workbench.rap.RapWorkbenchLogin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-/**
- * This class controls all aspects of the application's execution and is
- * contributed through the plugin.xml.
- */
-public class SlcSecureRap extends RapWorkbenchLogin {
-
- @Override
- protected RapWorkbenchAdvisor createRapWorkbenchAdvisor(
- final String username) {
- return new RapWorkbenchAdvisor(username) {
- @Override
- public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
- return new SlcRapWorkbenchWindowAdvisor(configurer, username);
- }
-
- };
- }
-
- /** Workaround for resize issue */
- class SlcRapWorkbenchWindowAdvisor extends RapWindowAdvisor {
-
- public SlcRapWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer, String username) {
- super(configurer, username);
- }
-
- public void preWindowOpen() {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- configurer.setShowCoolBar(true);
- configurer.setShowMenuBar(false);
- configurer.setShowStatusLine(false);
- configurer.setShowPerspectiveBar(true);
- configurer.setTitle("Argeo Secure UI"); //$NON-NLS-1$
- // Full screen, see
- // http://dev.eclipse.org/newslists/news.eclipse.technology.rap/msg02697.html
- configurer.setShellStyle(SWT.NO_TRIM);
- Rectangle bounds = Display.getCurrent().getBounds();
- configurer.setInitialSize(new Point(bounds.width, bounds.height));
- }
-
- @Override
- public void postWindowCreate() {
- Shell shell = getWindowConfigurer().getWindow().getShell();
- shell.setMaximized(true);
- }
-
- @Override
- public void postWindowOpen() {
- String defaultPerspective = getWindowConfigurer()
- .getWorkbenchConfigurer().getWorkbench()
- .getPerspectiveRegistry().getDefaultPerspective();
- if (defaultPerspective == null) {
- IWorkbenchWindow window = getWindowConfigurer().getWindow();
- if (window == null)
- return;
-
- IWorkbenchAction openPerspectiveDialogAction = ActionFactory.OPEN_PERSPECTIVE_DIALOG
- .create(window);
- openPerspectiveDialogAction.run();
- }
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.specific;
-
-import java.net.URL;
-import java.util.UUID;
-
-import javax.jcr.Node;
-import javax.jcr.Session;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.rap.OpenJcrFileService;
-import org.argeo.slc.repo.RepoService;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.rap.rwt.RWT;
-//import org.eclipse.rap.rwt.service.IServiceHandler;
-//import org.eclipse.rap.rwt.service.IServiceManager;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Rap specific command handler to open a file retrieved from a distant JCR
- * Repository. It creates and register a service instantiated with the
- * corresponding JCR node, forwards the request, and un register the service on
- * dispose
- *
- * This command and the corresponding service are specific for RAP version [1.3,
- * 2)
- */
-public class OpenJcrFile extends AbstractHandler {
-
- // Use (new OpenJcrFileCmdId()).getCmdId() instead.
- // public final String ID = SlcRapPlugin.PLUGIN_ID + ".openJcrFile";
-
- public final static String PARAM_REPO_NODE_PATH = "param.repoNodePath";
- public final static String PARAM_REPO_URI = "param.repoUri";
- public final static String PARAM_WORKSPACE_NAME = "param.workspaceName";
- public final static String PARAM_FILE_PATH = "param.filePath";
-
- private RepoService repoService;
- private String currentServiceId;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String repoNodePath = event.getParameter(PARAM_REPO_NODE_PATH);
- String repoUri = event.getParameter(PARAM_REPO_URI);
- String wkspName = event.getParameter(PARAM_WORKSPACE_NAME);
- String filePath = event.getParameter(PARAM_FILE_PATH);
-
- // TODO sanity check
- if (filePath == null || "".equals(filePath.trim()))
- return null;
- Session businessSession = null;
- try {
- businessSession = repoService.getRemoteSession(repoNodePath,
- repoUri, wkspName);
- Node result = businessSession.getNode(filePath);
-
- // Create a temporary service. No better solution has been found
- // yet.
- currentServiceId = UUID.randomUUID().toString();
- OpenJcrFileService ojfs = new OpenJcrFileService(result);
- // FIXME replace it
-// IServiceManager manager = RWT.getServiceManager();
-// manager.registerServiceHandler(currentServiceId, ojfs);
- String urlStr = createFullDownloadUrl(currentServiceId);
- URL url = new URL(urlStr);
- PlatformUI.getWorkbench().getBrowserSupport()
- .createBrowser("DownloadDialog").openURL(url);
- } catch (Exception e) {
- throw new SlcException("Unable to open Jcr File for path "
- + filePath, e);
- }
-
- return null;
- }
-
- @Override
- public void dispose() {
-// IServiceManager manager = RWT.getServiceManager();
-// manager.unregisterServiceHandler(currentServiceId);
- super.dispose();
- }
-
- private String createFullDownloadUrl(String serviceId) {
- StringBuilder url = new StringBuilder();
- url.append(RWT.getRequest().getRequestURL());
-
- StringBuilder params = new StringBuilder();
- params.append("?");
- // FIXME commented out so that it builds
- //params.append(IServiceHandler.REQUEST_PARAM).append("=");
- params.append(serviceId);
- String encodedURL = RWT.getResponse().encodeURL(params.toString());
- url.append(encodedURL);
- return url.toString();
- }
-
- /* Dependency Injection */
- public void setRepoService(RepoService repoService) {
- this.repoService = repoService;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.specific;
-
-import org.argeo.slc.client.rap.SlcRapPlugin;
-
-/**
- * Workaround a single sourcing problem:
- *
- * final static variable are imported at compilation time (we build against RCP)
- * and we still must have a different ID (the prefix must be the PLUGIN ID) for
- * RAP and RCP in order to be able to inject beans in the corresponding commands
- */
-public class OpenJcrFileCmdId {
-
- public String getCmdId() {
- return SlcRapPlugin.PLUGIN_ID + ".openJcrFile";
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.client.ui.dist</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <!-- DISTRIBUTIONS MANAGEMENT -->
- <bean id="normalizeDistribution"
- class="org.argeo.slc.client.ui.dist.commands.NormalizeDistribution">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="openModuleEditor" class="org.argeo.slc.client.ui.dist.commands.OpenModuleEditor"
- scope="prototype">
- <property name="repoService" ref="repoService" />
- </bean>
-
- <!-- REPOSITORY MANAGEMENT -->
- <bean id="registerRepository"
- class="org.argeo.slc.client.ui.dist.commands.RegisterRepository">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="unregisterRemoteRepo"
- class="org.argeo.slc.client.ui.dist.commands.UnregisterRemoteRepo"
- scope="prototype">
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="displayRepoInformation"
- class="org.argeo.slc.client.ui.dist.commands.DisplayRepoInformation"
- scope="prototype">
- <property name="repoService" ref="repoService" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
-
- <!-- WORKSPACE MANAGEMENT -->
- <bean id="openWorkspaceEditor"
- class="org.argeo.slc.client.ui.dist.commands.OpenWorkspaceEditor"
- scope="prototype">
- <property name="localRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="fetch" class="org.argeo.slc.client.ui.dist.commands.Fetch"
- scope="prototype">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="manageWorkspaceAuth"
- class="org.argeo.slc.client.ui.dist.commands.ManageWorkspaceAuth"
- scope="prototype">
- <property name="repository" ref="javaRepository" />
- </bean>
-
- <bean id="publishWorkspace" class="org.argeo.slc.client.ui.dist.commands.PublishWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="normalizeWorkspace"
- class="org.argeo.slc.client.ui.dist.commands.NormalizeWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="openGenerateBinariesWizard"
- class="org.argeo.slc.client.ui.dist.commands.OpenGenerateBinariesWizard">
- <property name="repoService" ref="repoService" />
- </bean>
-
- <!-- WORKSPACE CRUD -->
- <bean id="createWorkspace" class="org.argeo.slc.client.ui.dist.commands.CreateWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="copyWorkspace" class="org.argeo.slc.client.ui.dist.commands.CopyWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="copyLocalJavaWorkspace"
- class="org.argeo.slc.client.ui.dist.commands.CopyLocalJavaWorkspace">
- <property name="javaRepoManager">
- <bean factory-bean="slcRepoManager" factory-method="getJavaRepoManager" />
- </property>
- <property name="javaRepository" ref="javaRepository" />
- </bean>
-
- <bean id="createLocalJavaWorkspace"
- class="org.argeo.slc.client.ui.dist.commands.CreateLocalJavaWorkspace">
- <property name="javaRepoManager">
- <bean factory-bean="slcRepoManager" factory-method="getJavaRepoManager" />
- </property>
- </bean>
-
- <bean id="mergeWorkspaces" class="org.argeo.slc.client.ui.dist.commands.MergeWorkspaces">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="deleteWorkspace" class="org.argeo.slc.client.ui.dist.commands.DeleteWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <!-- ADVANCED -->
- <bean id="runInOsgi" class="org.argeo.slc.client.ui.dist.commands.RunInOsgi"
- scope="prototype">
- <property name="repository" ref="javaRepository" />
- </bean>
-
- <!-- LEGACY -->
- <!-- <bean id="org.argeo.slc.client.ui.dist.openGenericJcrQueryEditor" class="org.argeo.eclipse.ui.jcr.commands.OpenGenericJcrQueryEditor"
- scope="prototype"> <property name="editorId" value="org.argeo.slc.client.ui.dist.genericJcrQueryEditor"
- /> </bean> -->
- <bean id="refreshDistributionsView"
- class="org.argeo.slc.client.ui.dist.commands.RefreshDistributionsView"
- scope="prototype">
- </bean>
-
- <bean id="org.argeo.slc.client.ui.dist.deleteArtifacts" class="org.argeo.slc.client.ui.dist.commands.DeleteArtifacts"
- scope="prototype">
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
- <bean id="distWorkspaceEditor"
- class="org.argeo.slc.client.ui.dist.editors.DistWorkspaceEditor"
- scope="prototype">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="localRepository" ref="nodeRepository" />
- </bean>
-
- <bean id="artifactVersionEditor"
- class="org.argeo.slc.client.ui.dist.editors.ArtifactVersionEditor"
- scope="prototype">
- <property name="repoService" ref="repoService" />
- </bean>
-
- <bean id="modularDistVersionEditor"
- class="org.argeo.slc.client.ui.dist.editors.ModularDistVersionEditor"
- scope="prototype">
- <property name="repoService" ref="repoService" />
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
- <bean id="repoService" class="org.argeo.slc.repo.core.RepoServiceImpl">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- <property name="nodeRepository" ref="nodeRepository" />
- </bean>
-
- <!-- For the record <property name="session"> <bean factory-bean="repository"
- factory-method="login" /> </property> -->
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:osgi="http://www.springframework.org/schema/osgi"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"\r
- osgi:default-timeout="30000">\r
-\r
- <reference id="javaRepository" interface="javax.jcr.Repository"\r
- filter="(cn=java)" />\r
-\r
- <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
- <reference id="keyring" interface="org.argeo.cms.security.CryptoKeyring" />\r
-\r
- <reference id="nodeRepository" interface="javax.jcr.Repository"\r
- filter="(cn=ego)" />\r
-\r
- <reference id="slcRepoManager" interface="org.argeo.slc.repo.SlcRepoManager" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:util="http://www.springframework.org/schema/util"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/util
- http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
- <!-- Views -->
-<!-- <bean id="artifactsBrowser" class="org.argeo.slc.client.ui.dist.views.ArtifactsBrowser" -->
-<!-- scope="prototype"> -->
-<!-- <property name="jcrSession" ref="slcSession" /> -->
-<!-- </bean> -->
-<!-- <bean id="queryArtifactsForm" class="org.argeo.slc.client.ui.dist.views.QueryArtifactsForm" -->
-<!-- scope="prototype"> -->
-<!-- <property name="session" ref="slcSession" /> -->
-<!-- <property name="columnProperties"> -->
-<!-- <list> -->
-<!-- <value>slc:artifactVersion.jcr:uuid</value> -->
-<!-- <value>slc:artifactVersion.slc:groupId</value> -->
-<!-- <value>slc:artifactVersion.slc:artifactId</value> -->
-<!-- <value>slc:artifactVersion.slc:artifactVersion</value> -->
-<!-- </list> -->
-<!-- </property> -->
-<!-- </bean> -->
-<!-- <bean id="queryBundlesForm" class="org.argeo.slc.client.ui.dist.views.QueryBundlesForm" -->
-<!-- scope="prototype"> -->
-<!-- <property name="session" ref="slcSession" /> -->
-<!-- <property name="columnProperties"> -->
-<!-- <list> -->
-<!-- <value>slc:artifactVersion.jcr:uuid</value> -->
-<!-- <value>slc:bundleArtifact.slc:symbolic-name</value> -->
-<!-- <value>slc:artifactVersion.slc:groupId</value> -->
-<!-- <value>slc:bundleArtifact.slc:bundle-version</value> -->
-<!-- <value>slc:bundleArtifact.slc:Fragment-Host</value> -->
-<!-- </list> -->
-<!-- </property> -->
-<!-- </bean> -->
-
-<!-- <bean id="queryArtifactsText" class="org.argeo.slc.client.ui.dist.views.QueryArtifactsText" -->
-<!-- scope="prototype"> -->
-<!-- <property name="session" ref="slcSession" /> -->
-<!-- </bean> -->
-
- <bean id="distributionsView" class="org.argeo.slc.client.ui.dist.views.DistributionsView"
- scope="prototype">
- <!-- <property name="repositoryFactory" ref="repositoryFactory" /> -->
- <!-- <property name="keyring" ref="keyring" /> -->
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="treeContentProvider" ref="distTreeContentProvider" />
- </bean>
-
- <!-- Corresponding content provider -->
- <bean id="distTreeContentProvider"
- class="org.argeo.slc.client.ui.dist.controllers.DistTreeContentProvider"
- scope="prototype">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <!-- ANONYMOUS DISTRIBUTION VIEW -->
- <bean id="anonymousDistributionsView"
- class="org.argeo.slc.client.ui.dist.views.AnonymousDistributionsView"
- scope="prototype">
- <property name="treeContentProvider" ref="anonymousDistTreeContentProvider" />
- </bean>
-
- <!-- Corresponding content provider -->
- <bean id="anonymousDistTreeContentProvider"
- class="org.argeo.slc.client.ui.dist.controllers.AnonymousDistTreeContentProvider"
- scope="prototype">
- <property name="repositoryFactory" ref="repositoryFactory" />
- </bean>
-
- <!-- <bean id="distributionPerspective" class="org.argeo.slc.client.ui.dist.DistributionPerspective"
- scope="prototype"> <property name="repositoryFactory" ref="repositoryFactory"
- /> <property name="nodeRepository" ref="nodeRepository" /> </bean> -->
-</beans>
\ No newline at end of file
+++ /dev/null
-Bundle-SymbolicName: org.argeo.slc.client.ui.dist;singleton=true
-Bundle-ActivationPolicy: lazy
-Require-Bundle: org.eclipse.ui;resolution:=optional,\
-org.eclipse.core.runtime,\
-org.eclipse.rap.ui;resolution:=optional,\
-org.eclipse.rap.ui.workbench;resolution:=optional
-
-Bundle-Activator: org.argeo.slc.client.ui.dist.DistPlugin
-Import-Package: org.argeo.eclipse.spring,\
-javax.jcr.nodetype,\
-javax.jcr.security,\
-aQute.lib.*;resolution:=optional,\
-org.springframework.beans.factory,\
-org.osgi.*;version=0.0.0,\
-*
-
\ No newline at end of file
+++ /dev/null
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <!-- PERSPECTIVES -->
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- name="SLC Factory"
- class="org.argeo.slc.client.ui.dist.DistributionPerspective"
- id="org.argeo.slc.client.ui.dist.distributionPerspective"
- icon="icons/distribution_perspective.gif">
- </perspective>
- <perspective
- name="SLC Distribution"
- class="org.argeo.slc.client.ui.dist.AnonymousDistributionPerspective"
- id="org.argeo.slc.client.ui.dist.anonymousDistributionPerspective"
- icon="icons/repo.gif">
- </perspective>
- </extension>
- <!-- VIEWS -->
- <extension
- point="org.eclipse.ui.views">
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.distributionsView"
- icon="icons/search.gif"
- name="Distributions">
- </view>
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.anonymousDistributionsView"
- icon="icons/search.gif"
- name="Public Repository">
- </view>
- <view
- class="org.argeo.slc.client.ui.dist.views.HelpView"
- id="org.argeo.slc.client.ui.dist.helpView"
- icon="icons/help.gif"
- name="About">
- </view>
- <!--
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.artifactsBrowser"
- icon="icons/packageBrowser.gif"
- name="Artifacts browser">
- </view>
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.queryArtifactsForm"
- icon="icons/searchForm.gif"
- name="Artifacts Form">
- </view>
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.queryBundlesForm"
- icon="icons/searchForm.gif"
- name="Bundles Form">
- </view>
- <view
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.queryArtifactsText"
- icon="icons/search.gif"
- name="Query builder">
- </view>
- -->
- <view
- name="Progress View"
- icon="icons/pview.gif"
- category="org.eclipse.ui"
- class="org.eclipse.ui.ExtensionFactory:progressView"
- id="org.eclipse.ui.views.ProgressView">
- </view>
- </extension>
- <!-- EDITORS -->
- <extension
- point="org.eclipse.ui.editors">
- <!-- <editor
- class="org.argeo.slc.client.ui.dist.editors.GenericBundleEditor"
- id="org.argeo.slc.client.ui.dist.genericBundleEditor"
- name="Bundle editor"
- icon="icons/artifactVersionBase.gif"
- default="false">
- </editor> -->
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.artifactVersionEditor"
- name="Artifact Version Editor"
- icon="icons/artifactVersionBase.gif"
- default="false">
- </editor>
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.modularDistVersionEditor"
- name="Modular Distribution Version Editor"
- icon="icons/modularDistributionVersion.gif"
- default="false">
- </editor>
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- id="org.argeo.slc.client.ui.dist.distWorkspaceEditor"
- name="Distribution workspace editor"
- icon="icons/distribution_perspective.gif"
- default="false">
- </editor>
- </extension>
-
- <!-- COMMANDS -->
- <extension
- point="org.eclipse.ui.commands">
-
- <!-- Distribution Managemnt -->
- <command
- id="org.argeo.slc.client.ui.dist.normalizeDistribution"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Normalize Distribution">
- <commandParameter
- id="workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
-
- <command
- id="org.argeo.slc.client.ui.dist.openModuleEditor"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Open Workspace Editor">
- <commandParameter
- id="param.repoNodePath"
- name="Repo node path">
- </commandParameter>
- <commandParameter
- id="param.repoUri"
- name="Repo URI">
- </commandParameter>
- <commandParameter
- id="param.workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="param.modulePath"
- name="Module path name">
- </commandParameter>
- </command>
-
- <!-- Repository Management -->
- <command
- id="org.argeo.slc.client.ui.dist.registerRepository"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Add Repository">
- </command>
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.slc.client.ui.dist.unregisterRemoteRepo"
- name="Unregister remote repository">
- <commandParameter
- id="org.argeo.slc.client.ui.dist.repoNodePath"
- name="Remote Repo path">
- </commandParameter>
- </command>
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.slc.client.ui.dist.displayRepoInformation"
- name="Display repository information">
- </command>
-
- <!-- Workspace Management -->
- <command
- id="org.argeo.slc.client.ui.dist.openWorkspaceEditor"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Open Workspace Editor">
- <commandParameter
- id="param.repoNodePath"
- name="Repo node path">
- </commandParameter>
- <commandParameter
- id="param.repoUri"
- name="Repo URI">
- </commandParameter>
- <commandParameter
- id="param.workspaceName"
- name="Workspace name">
- </commandParameter>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.fetch"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Fetch repository">
- <commandParameter
- id="targetRepoPath"
- name="Target repo uri">
- </commandParameter>
- </command>
-
- <!-- <command
- defaultHandler="org.argeo.slc.client.ui.dist.commands.MarkAsRelevantCategory"
- id="org.argeo.slc.client.ui.dist.markAsRelevantCategory"
- name="Mark as relevant category">
- </command> -->
-
- <command
- id="org.argeo.slc.client.ui.dist.openGenerateBinariesWizard"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Generate Binaries...">
- <commandParameter
- id="param.repoNodePath"
- name="Repo node path">
- </commandParameter>
- <commandParameter
- id="param.workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="param.modulePath"
- name="Module path name">
- </commandParameter>
- </command>
-
- <command
- id="org.argeo.slc.client.ui.dist.normalizeWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Normalize Workspace">
- <commandParameter
- id="workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.manageWorkspaceAuth"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Manage workspace authorizations">
- <commandParameter
- id="org.argeo.slc.client.ui.dist.workspaceName"
- name="Workspace Name">
- </commandParameter>
- </command>
-
- <command
- id="org.argeo.slc.client.ui.dist.publishWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Publish selected workspace">
- <commandParameter
- id="workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
-
- <command
- id="org.argeo.slc.client.ui.dist.mergeWorkspaces"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Copy chosen Workspace">
- <commandParameter
- id="srcWkspName"
- name="Source Workspace Name">
- </commandParameter>
- <commandParameter
- id="srcRepoPath"
- name="Source Repo Node path ">
- </commandParameter>
- <commandParameter
- id="targetWkspName"
- name="Target Workspace Name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
-
- <!-- Workspaces CRUD -->
- <!-- Generic new and copy workspace -->
- <command
- id="org.argeo.slc.client.ui.dist.createWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Create Workspace">
- <commandParameter
- id="workspacePrefix"
- name="Workspace prefix">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.copyWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Copy chosen Workspace">
- <commandParameter
- id="srcWkspName"
- name="Source Workspace Name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
- <!-- Specific for local java workspaces -->
- <command
- id="org.argeo.slc.client.ui.dist.createLocalJavaWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Create Local Java Workspace">
- <commandParameter
- id="workspacePrefix"
- name="Workspace prefix">
- </commandParameter>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.copyLocalJavaWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Copy chosen local Java Workspace">
- <commandParameter
- id="srcWkspName"
- name="Source Workspace Name">
- </commandParameter>
- </command>
-
- <!-- Not terminated delete command - does not really work -->
- <command
- id="org.argeo.slc.client.ui.dist.deleteWorkspace"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Delete chosen Workspace">
- <commandParameter
- id="workspaceName"
- name="Workspace name">
- </commandParameter>
- <commandParameter
- id="targetRepoPath"
- name="Target repo node path">
- </commandParameter>
- </command>
-
- <!-- Advanced commands -->
- <command
- id="org.argeo.slc.client.ui.dist.doNothing"
- defaultHandler="org.argeo.slc.client.ui.dist.commands.DoNothing"
- name="Advanced">
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.runInOsgi"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Run in OSGi">
- <commandParameter
- id="workspaceName"
- name="Workspace Name">
- </commandParameter>
- <commandParameter
- id="modulePath"
- name="Module Path"
- optional="true">
- </commandParameter>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.refreshDistributionsView"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Refresh Distributions View">
- </command>
-
- <!-- Legacy -->
- <command
- defaultHandler="org.argeo.slc.client.ui.dist.commands.RefreshArtifactBrowser"
- id="org.argeo.slc.client.ui.dist.refreshArtifactBrowser"
- name="Refresh Artifact Browser">
- </command>
-
- <command
- defaultHandler="org.argeo.slc.client.ui.dist.commands.ShowSizeColumn"
- id="org.argeo.slc.client.ui.dist.showSizeColumn"
- name="Show size column">
- <state
- id="org.argeo.slc.client.ui.dist.showSizeColumn.toggleState">
- <class class="org.eclipse.jface.commands.ToggleState">
- <parameter
- name="default"
- value="true" />
- </class>
- </state>
- </command>
- <command
- id="org.argeo.slc.client.ui.dist.deleteArtifacts"
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- name="Remove selected artifacts">
- </command>
- </extension>
-
- <!-- MENU CONTRIBUTIONS -->
- <extension
- id="menu:org.eclipse.ui.main.menu"
- point="org.eclipse.ui.menus">
- <!-- Distributions view tool bar -->
- <menuContribution
- locationURI="toolbar:org.argeo.slc.client.ui.dist.distributionsView">
- <command
- commandId="org.argeo.slc.client.ui.dist.registerRepository"
- icon="icons/addRepo.gif"
- label="Register repository"
- tooltip="Register a remote repository">
- </command>
- <command
- commandId="org.argeo.slc.client.ui.dist.doNothing"
- id="org.argeo.slc.client.ui.dist.advancedMenu"
- icon="icons/more.gif"
- tooltip="Access to advanced commands"
- style="pulldown">
- </command>
- </menuContribution>
- <menuContribution locationURI="menu:org.argeo.slc.client.ui.dist.advancedMenu">
- <command
- commandId="org.argeo.slc.client.ui.dist.refreshDistributionsView"
- icon="icons/refresh.png"
- label="Refresh"
- tooltip="Force the full refresh of the distribution tree (close all open connections)">
- </command>
- <!-- <command
- commandId="org.argeo.slc.client.ui.dist.runInOSGi"
- icon="icons/showSize.gif"
- label="Run in OSGi"
- tooltip="Run in a spearate OSGi runtime">
- </command>
- -->
- </menuContribution>
- <!-- Anonymous distribution view toolbar -->
- <menuContribution
- locationURI="toolbar:org.argeo.slc.client.ui.dist.anonymousDistributionsView">
- <command
- commandId="org.argeo.slc.client.ui.dist.refreshDistributionsView"
- icon="icons/refresh.png"
- label="Refresh"
- tooltip="Force the full refresh of the distribution tree (close all open connections)">
- </command>
- </menuContribution>
- <!-- Artifact Browser Tool bar -->
- <menuContribution
- locationURI="toolbar:org.argeo.slc.client.ui.dist.artifactsBrowser">
- <command
- commandId="org.argeo.slc.client.ui.dist.showSizeColumn"
- icon="icons/showSize.gif"
- style="toggle"
- label="Show sizes"
- tooltip="Warning: showing size column might reduce overall browser reactivity">
- </command>
- <command
- commandId="org.argeo.slc.client.ui.dist.refreshArtifactBrowser"
- icon="icons/refresh.png"
- label="Refresh"
- tooltip="Refresh the whole browser">
- </command>
- </menuContribution>
- <!-- Queries -->
- <!-- <menuContribution
- allPopups="false"
- locationURI="menu:org.eclipse.ui.main.menu?after=edit">
- <menu label="Queries"
- mnemonic="Queries"
- id="org.argeo.slc.client.ui.dist.queryMenu">
- <command
- commandId="org.argeo.slc.client.ui.dist.openGenericJcrQueryEditor"
- disabledIcon="icons/saveDisabled.gif"
- icon="icons/results.gif"
- label="JCR Query"
- style="push"
- tooltip="Open JCR query editor">
- </command>
- </menu>
- </menuContribution> -->
- </extension>
- <extension
- point="org.eclipse.ui.activities">
- <!-- TODO: find a way to exclude evrything -->
- <activityPatternBinding
- activityId="org.argeo.slc.client.ui.slcActivity"
- isEqualityPattern="true"
- pattern="org.argeo.slc.client.ui.dist/org.argeo.slc.client.ui.dist.distributionPerspective">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.argeo.security.ui.adminActivity"
- isEqualityPattern="true"
- pattern="org.argeo.slc.client.ui.dist/org.argeo.slc.client.ui.dist.distributionPerspective">
- </activityPatternBinding>
- </extension>
-</plugin>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.ui.dist</artifactId>
- <name>SLC Client UI Distribution</name>
- <packaging>jar</packaging>
- <dependencies>
- <!-- Commons UI -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.swt</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.rap</groupId>
- <artifactId>org.argeo.swt.specific.rap</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench</artifactId>
- <version>${version.argeo-commons-legacy}</version>
- </dependency>
-
-
- <!-- SLC repo -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.api</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.repo</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.spring</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.server.repo</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Argeo Base dependencies -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- <!-- RAP workbench -->
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist;
-
-import org.argeo.slc.client.ui.dist.views.AnonymousDistributionsView;
-import org.argeo.slc.client.ui.dist.views.HelpView;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Simple default perspective that presents public repositories */
-public class AnonymousDistributionPerspective implements IPerspectiveFactory {
-
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".anonymousDistributionPerspective";
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout main = layout.createFolder("main", IPageLayout.LEFT,
- 0.3f, editorArea);
- main.addView(AnonymousDistributionsView.ID);
- main.addView(HelpView.ID);
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist;
-
-import org.argeo.slc.SlcNames;
-import org.osgi.framework.Constants;
-
-/** Constants used across the application. */
-public interface DistConstants {
-
- /*
- * MISCEALLENEOUS
- */
- public final static String DATE_TIME_FORMAT = "MM/dd/yyyy, HH:mm";
- public final static String DATE_FORMAT = "MM/dd/yyyy";
- // this should be directly retrieved from JCR APIs once we have solved the
- // problem of the translation of name space to shortcut, typically
- // {http://www.jcp.org/jcr/1.0} to jcr:
- public final static String JCR_IDENTIFIER = "jcr:uuid";
- public final static String JCR_MIXIN_TYPES = "jcr:mixinTypes";
-
- // FIXME: should be defined in SlcNames
- public final static String SLC_BUNDLE_NAME = SlcNames.SLC_
- + Constants.BUNDLE_NAME;
- public final static String SLC_BUNDLE_LICENCE = SlcNames.SLC_
- + "Bundle-License";
- public final static String SLC_BUNDLE_VENDOR = SlcNames.SLC_
- + Constants.BUNDLE_VENDOR;
-
- public final static String SLC_BUNDLE_DESCRIPTION = SlcNames.SLC_
- + Constants.BUNDLE_DESCRIPTION;
-
- public final String DEFAULT_PUBLIC_REPOSITORY_URI = "vm:///java";
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist;
-
-import org.eclipse.swt.graphics.Image;
-
-/** Shared icons. */
-public class DistImages {
-
- public final static Image IMG_ARTIFACT_BASE = DistPlugin
- .getImageDescriptor("icons/artifactBase.gif").createImage();
- public final static Image IMG_PACKAGE = DistPlugin.getImageDescriptor(
- "icons/package.gif").createImage();
- public final static Image IMG_BUNDLE = DistPlugin.getImageDescriptor(
- "icons/packages.gif").createImage();
- public final static Image IMG_ARTIFACT_VERSION_BASE = DistPlugin
- .getImageDescriptor("icons/artifactVersionBase.gif").createImage();
- public final static Image IMG_FILE = DistPlugin.getImageDescriptor(
- "icons/file.gif").createImage();
-
- /* WORKSPACES */
- public final static Image IMG_WKSP = DistPlugin.getImageDescriptor(
- "icons/distribution_perspective.gif").createImage();
-
- /* REPOSITORIES */
- public final static Image IMG_REPO = DistPlugin.getImageDescriptor(
- "icons/repo.gif").createImage();
- public final static Image IMG_HOME_REPO = DistPlugin.getImageDescriptor(
- "icons/homeRepo.gif").createImage();
- public final static Image IMG_REPO_READONLY = DistPlugin
- .getImageDescriptor("icons/repoReadOnly.gif").createImage();
- public final static Image IMG_ADD_REPO = DistPlugin.getImageDescriptor(
- "icons/addRepo.gif").createImage();
- public final static Image IMG_REMOVE_REPO = DistPlugin.getImageDescriptor(
- "icons/artifactBase.gif").createImage();
- public final static Image IMG_FETCH_REPO = DistPlugin.getImageDescriptor(
- "icons/fetchRepo.png").createImage();
-
- /* DISTRIBUTIONS */
- public final static Image IMG_WKSP_GROUP = DistPlugin.getImageDescriptor(
- "icons/wkspGroup.gif").createImage();
- public final static Image IMG_DISTGRP = DistPlugin.getImageDescriptor(
- "icons/distGrp.gif").createImage();
- public final static Image IMG_DISTGRP_READONLY = DistPlugin
- .getImageDescriptor("icons/distGrpReadOnly.gif").createImage();
-
- public final static Image IMG_MODULAR_DIST_BASE = DistPlugin
- .getImageDescriptor("icons/packages.gif").createImage();
- public final static Image IMG_MODULAR_DIST_VERSION = DistPlugin
- .getImageDescriptor("icons/packages.gif").createImage();
-
- public final static Image IMG_GROUP_BASE = DistPlugin.getImageDescriptor(
- "icons/packages.gif").createImage();
-
- /* Various */
- public final static Image CHECKED = DistPlugin.getImageDescriptor(
- "icons/checked.gif").createImage();
- public final static Image UNCHECKED = DistPlugin.getImageDescriptor(
- "icons/unchecked.gif").createImage();
- public final static Image IMG_CLEAR = DistPlugin.getImageDescriptor(
- "icons/clear.gif").createImage();
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/** Default activator for the distribution bundle */
-public class DistPlugin extends AbstractUIPlugin {
- public final static String PLUGIN_ID = "org.argeo.slc.client.ui.dist";
-
- private static DistPlugin plugin;
-
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- public static DistPlugin getDefault() {
- return plugin;
- }
-
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist;
-
-import org.argeo.slc.client.ui.dist.views.DistributionsView;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Manage a set of software repositories */
-public class DistributionPerspective implements IPerspectiveFactory {
-
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".distributionPerspective";
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout main = layout.createFolder("main", IPageLayout.LEFT,
- 0.3f, editorArea);
- main.addView(DistributionsView.ID);
- IFolderLayout bottom = layout.createFolder("bottom",
- IPageLayout.BOTTOM, 0.75f, editorArea);
- bottom.addView("org.eclipse.ui.views.ProgressView");
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.jar.Manifest;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-import aQute.bnd.osgi.Builder;
-import aQute.bnd.osgi.Constants;
-import aQute.bnd.osgi.Jar;
-
-public class BndProcess extends AbstractHandler implements Constants {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- Builder b = new Builder();
- b.setProperty(EXPORT_PACKAGE, "org.osgi.framework");
- b.setProperty(PRIVATE_PACKAGE, "*");
- b.addClasspath(new File(
- "/home/mbaudier/.m2/repository/org/eclipse/osgi/org.eclipse.osgi/3.6.1/org.eclipse.osgi-3.6.1.jar"));
-
- Jar jar = b.build();
- Manifest m = jar.getManifest();
- jar.write(new File(b.getBsn() + ".jar"));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return null;
- }
-
- public static void main(String[] args) {
- try {
- new BndProcess().execute(null);
- } catch (ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.security.Privilege;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.ui.workbench.util.PrivilegedJob;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.JavaRepoManager;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Create a copy of the chosen workspace in the local Java repository using a
- * JavaRepoManager.
- */
-public class CopyLocalJavaWorkspace extends AbstractHandler {
- private static final CmsLog log = CmsLog
- .getLog(CopyLocalJavaWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".copyLocalJavaWorkspace";
- public final static String DEFAULT_LABEL = "Copy Java Workspace...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/addItem.gif");
-
- public final static String PARAM_SOURCE_WORKSPACE_NAME = "srcWkspName";
-
- // DEPENDENCY INJECTION
- private Repository javaRepository;
- private JavaRepoManager javaRepoManager;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String wkspName = event.getParameter(PARAM_SOURCE_WORKSPACE_NAME);
-
- InputDialog inputDialog = new InputDialog(HandlerUtil
- .getActiveWorkbenchWindow(event).getShell(),
- "New copy of workspace " + wkspName,
- "Choose a name for the workspace to create", "", null);
- int result = inputDialog.open();
- if (result == Window.OK) {
- String newWorkspaceName = inputDialog.getValue();
-
- if (newWorkspaceName == null || newWorkspaceName.trim().equals("")
- || newWorkspaceName.trim().equals(wkspName.trim())) {
- ErrorDialog
- .openError(HandlerUtil.getActiveShell(event),
- "Non valid workspace name", newWorkspaceName
- + " is not a valid workspace name.",
- new Status(IStatus.ERROR, "not valid", 0,
- "Error", null));
- return null;
- }
- Job copyWkspJob = new CopyWkspJob(javaRepoManager, javaRepository,
- wkspName, newWorkspaceName, HandlerUtil
- .getActiveWorkbenchWindow(event).getShell()
- .getDisplay());
- copyWkspJob.setUser(true);
- copyWkspJob.schedule();
- }
- return null;
- }
-
- private static class CopyWkspJob extends PrivilegedJob {
-
- private JavaRepoManager javaRepoManager;
- private Repository javaRepository;
- private String srcWkspName;
- private String targetWkspName;
- private Display display;
-
- public CopyWkspJob(JavaRepoManager javaRepoManager,
- Repository javaRepository, String srcWkspName,
- String targetWkspName, Display display) {
- super("Duplicate workspace");
- this.javaRepoManager = javaRepoManager;
- this.javaRepository = javaRepository;
- this.srcWkspName = srcWkspName;
- this.targetWkspName = targetWkspName;
- this.display = display;
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- long begin = System.currentTimeMillis();
-
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- monitor.beginTask("Copy workspace", -1);
- monitor.subTask("Copying nodes");
-
- Session srcSession = null;
- Session targetSession = null;
- try {
- // Initialize source
- srcSession = javaRepository.login(srcWkspName);
- Node srcRootNode = srcSession.getRootNode();
-
- // Create the workspace -
- // FIXME will throw an error if workspace already exists
- javaRepoManager.createWorkspace(targetWkspName);
- targetSession = javaRepository.login(targetWkspName);
- Node newRootNode = targetSession.getRootNode();
-
- RepoUtils.copy(srcRootNode, newRootNode, monitor);
- targetSession.save();
- JcrUtils.addPrivilege(targetSession, "/",
- SlcConstants.ROLE_SLC, Privilege.JCR_ALL);
- monitor.worked(1);
-
- display.asyncExec(new Runnable() {
- public void run() {
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- }
- });
-
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while creating the new workspace.",
- re);
- } finally {
- JcrUtils.logoutQuietly(srcSession);
- JcrUtils.logoutQuietly(targetSession);
- }
-
- monitor.done();
- long duration = (System.currentTimeMillis() - begin) / 1000;// in
- // s
- if (log.isDebugEnabled())
- log.debug("Duplicated local java workspace " + srcWkspName
- + " to workspace " + targetWkspName + " in "
- + (duration / 60) + "min " + (duration % 60) + "s");
- return Status.OK_STATUS;
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setJavaRepository(Repository javaRepository) {
- this.javaRepository = javaRepository;
- }
-
- public void setJavaRepoManager(JavaRepoManager javaRepoManager) {
- this.javaRepoManager = javaRepoManager;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.security.Privilege;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.security.Keyring;
-import org.argeo.cms.ui.workbench.util.PrivilegedJob;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Create a copy of the chosen workspace in a remote repository */
-public class CopyWorkspace extends AbstractHandler {
- private static final CmsLog log = CmsLog.getLog(CopyWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".copyWorkspace";
- public final static String DEFAULT_LABEL = "Duplicate...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/addItem.gif");
-
- public final static String PARAM_SOURCE_WORKSPACE_NAME = "srcWkspName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String wkspName = event.getParameter(PARAM_SOURCE_WORKSPACE_NAME);
-
- InputDialog inputDialog = new InputDialog(HandlerUtil
- .getActiveWorkbenchWindow(event).getShell(),
- "New copy of workspace " + wkspName,
- "Choose a name for the workspace to create", "", null);
- int result = inputDialog.open();
- if (result == Window.OK) {
- String newWorkspaceName = inputDialog.getValue();
-
- if (newWorkspaceName == null || newWorkspaceName.trim().equals("")
- || newWorkspaceName.trim().equals(wkspName.trim())) {
- ErrorDialog
- .openError(HandlerUtil.getActiveShell(event),
- "Non valid workspace name", newWorkspaceName
- + " is not a valid workspace name.",
- new Status(IStatus.ERROR, "not valid", 0,
- "Error", null));
- return null;
- }
- Job copyWkspJob = new CopyWkspJob(repositoryFactory, keyring,
- nodeRepository, targetRepoPath, wkspName, newWorkspaceName,
- HandlerUtil.getActiveWorkbenchWindow(event).getShell()
- .getDisplay());
- copyWkspJob.setUser(true);
- copyWkspJob.schedule();
- }
- return null;
- }
-
- private static class CopyWkspJob extends PrivilegedJob {
-
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository localRepository;
- private String targetRepoPath;
- private String srcWkspName;
- private String targetWkspName;
- private Display display;
-
- public CopyWkspJob(RepositoryFactory repositoryFactory,
- Keyring keyring, Repository localRepository,
- String targetRepoPath, String srcWkspName,
- String targetWkspName, Display display) {
- super("Duplicate workspace");
- this.repositoryFactory = repositoryFactory;
- this.keyring = keyring;
- this.localRepository = localRepository;
- this.targetRepoPath = targetRepoPath;
- this.srcWkspName = srcWkspName;
- this.targetWkspName = targetWkspName;
- this.display = display;
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- long begin = System.currentTimeMillis();
-
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- monitor.beginTask("Copy workspace", -1);
- monitor.subTask("Copying nodes");
-
- Session nodeSession = null;
- Session srcSession = null;
- Session newSession = null;
- try {
- nodeSession = localRepository.login();
- Node repoNode = nodeSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(
- repositoryFactory, keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, repoNode);
-
- srcSession = repository.login(credentials, srcWkspName);
-
- // Create the workspace
- srcSession.getWorkspace().createWorkspace(targetWkspName);
- Node srcRootNode = srcSession.getRootNode();
- // log in the newly created workspace
- newSession = repository.login(credentials, targetWkspName);
- Node newRootNode = newSession.getRootNode();
- RepoUtils.copy(srcRootNode, newRootNode, monitor);
- newSession.save();
- JcrUtils.addPrivilege(newSession, "/", SlcConstants.ROLE_SLC,
- Privilege.JCR_ALL);
-
- display.asyncExec(new Runnable() {
- public void run() {
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- }
- });
- monitor.worked(1);
-
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while creating the new workspace.",
- re);
- } finally {
- JcrUtils.logoutQuietly(newSession);
- JcrUtils.logoutQuietly(srcSession);
- JcrUtils.logoutQuietly(nodeSession);
- }
-
- monitor.done();
- long duration = (System.currentTimeMillis() - begin) / 1000;// in
- // s
- if (log.isDebugEnabled())
- log.debug("Created workspace " + targetWkspName + " in "
- + (duration / 60) + "min " + (duration % 60) + "s");
- return Status.OK_STATUS;
- }
-
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.JavaRepoManager;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Create a new empty workspace in the default local java repository */
-public class CreateLocalJavaWorkspace extends AbstractHandler {
- private static final CmsLog log = CmsLog
- .getLog(CreateLocalJavaWorkspace.class);
-
- // Exposes commands meta-info
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".createLocalJavaWorkspace";
- public final static String DEFAULT_LABEL = "Create local Java workspace...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/addItem.gif");
-
- // Parameters
- public final static String PARAM_WORKSPACE_PREFIX = "workspacePrefix";
-
- /* DEPENDENCY INJECTION */
- private JavaRepoManager javaRepoManager;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String prefix = event.getParameter(PARAM_WORKSPACE_PREFIX);
- // TODO : add an input validator
- InputDialog inputDialog = new InputDialog(HandlerUtil
- .getActiveWorkbenchWindow(event).getShell(), "Workspace name?",
- "Choose a name for the workspace to create",
- prefix == null ? "" : prefix + "-", null);
- int result = inputDialog.open();
-
- String enteredName = inputDialog.getValue();
- final String legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXZY0123456789_";
- char[] arr = enteredName.toUpperCase().toCharArray();
- int count = 0;
- for (int i = 0; i < arr.length; i++) {
- if (legalChars.indexOf(arr[i]) == -1)
- count = count + 7;
- else
- count++;
- }
-
- if (count > 60) {
- ErrorFeedback.show("Workspace name '" + enteredName
- + "' is too long or contains"
- + " too many special characters such as '.' or '-'.");
- return null;
- }
-
- String workspaceName = enteredName;
- // Canceled by user
- if (result == Dialog.CANCEL || workspaceName == null
- || "".equals(workspaceName.trim()))
- return null;
-
- // FIXME will throw an exception if this workspace name is already used.
- javaRepoManager.createWorkspace(workspaceName);
-
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- if (log.isTraceEnabled())
- log.trace("WORKSPACE " + workspaceName + " CREATED");
-
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setJavaRepoManager(JavaRepoManager javaRepoManager) {
- this.javaRepoManager = javaRepoManager;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.security.Privilege;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Create a new empty workspace in a remote repository */
-public class CreateWorkspace extends AbstractHandler {
- private static final CmsLog log = CmsLog.getLog(CreateWorkspace.class);
-
- // Exposes commands meta-info
- public final static String ID = DistPlugin.PLUGIN_ID + ".createWorkspace";
- public final static String DEFAULT_LABEL = "Create workspace...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/addItem.gif");
-
- // Parameters
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
- public final static String PARAM_WORKSPACE_PREFIX = "workspacePrefix";
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String prefix = event.getParameter(PARAM_WORKSPACE_PREFIX);
-
- Session nodeSession = null;
- Session session = null;
- try {
- nodeSession = nodeRepository.login();
- Node repoNode = nodeSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(repositoryFactory,
- keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, repoNode);
-
- // TODO : add an input validator
- InputDialog inputDialog = new InputDialog(HandlerUtil
- .getActiveWorkbenchWindow(event).getShell(),
- "Workspace name?",
- "Choose a name for the workspace to create",
- prefix == null ? "" : prefix + "-", null);
- int result = inputDialog.open();
-
- String enteredName = inputDialog.getValue();
-
- final String legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXZY0123456789_";
- char[] arr = enteredName.toUpperCase().toCharArray();
- int count = 0;
- for (int i = 0; i < arr.length; i++) {
- if (legalChars.indexOf(arr[i]) == -1)
- count = count + 7;
- else
- count++;
- }
-
- if (log.isTraceEnabled())
- log.trace("Translated workspace name length: " + count
- + " (name: " + enteredName + " )");
-
- if (count > 60) {
- ErrorFeedback.show("Workspace name '" + enteredName
- + "' is too long or contains"
- + " too many special characters such as '.' or '-'.");
- return null;
- }
-
- String workspaceName = enteredName;
-
- // Canceled by user
- if (result == Dialog.CANCEL || workspaceName == null
- || "".equals(workspaceName.trim()))
- return null;
-
- session = repository.login(credentials);
- session.getWorkspace().createWorkspace(workspaceName);
- JcrUtils.logoutQuietly(session);
- // init new workspace
- session = repository.login(credentials, workspaceName);
- JcrUtils.addPrivilege(session, "/", SlcConstants.ROLE_SLC,
- Privilege.JCR_ALL);
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- if (log.isTraceEnabled())
- log.trace("WORKSPACE " + workspaceName + " CREATED");
-
- } catch (RepositoryException re) {
- ErrorFeedback.show(
- "Unexpected error while creating the new workspace.", re);
- } finally {
- JcrUtils.logoutQuietly(session);
- JcrUtils.logoutQuietly(nodeSession);
- }
- return null;
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import java.util.Iterator;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Delete chosen artifacts from the current workspace */
-public class DeleteArtifacts extends AbstractHandler {
- // private static final CmsLog log = CmsLog.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".deleteArtifacts";
- public final static String DEFAULT_LABEL = "Delete selected items";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/removeItem.gif");
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
-
- if (activePart instanceof IEditorPart) {
- ISelection selector = ((IEditorPart) activePart)
- .getEditorSite().getSelectionProvider().getSelection();
- if (selector != null
- && selector instanceof IStructuredSelection) {
- Iterator<?> it = ((IStructuredSelection) selector)
- .iterator();
-
- String msg = "Your are about to definitively remove the "
- + ((IStructuredSelection) selector).size()
- + " selected artifacts.\n"
- + "Are you sure you want to proceed?";
-
- boolean result = MessageDialog.openConfirm(DistPlugin
- .getDefault().getWorkbench().getDisplay()
- .getActiveShell(), "Confirm Deletion", msg);
-
- if (result) {
- while (it.hasNext()) {
- Node node = (Node) it.next();
- if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
- // we remove the artifactVersion, that is the
- // parent
- node.getParent().remove();
- node.getSession().save();
- }
- }
- }
- }
- }
- // CommandHelpers.callCommand(RefreshDistributionOverviewPage.ID);
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while deleting artifacts.", re);
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/**
- * Delete chosen workspace in the current repository.
- *
- * Due to current version of JackRabbit, it only cleans it for the time being,
- * removing all nodes of type {@code NodeType.NT_FOLDER} and
- * {@code NodeType.NT_UNSTRUCTURED}
- */
-public class DeleteWorkspace extends AbstractHandler {
- // private static final CmsLog log = CmsLog.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".deleteWorkspace";
- public final static String DEFAULT_LABEL = "Clear";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/removeItem.gif");
-
- public final static String PARAM_WORKSPACE_NAME = "workspaceName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
-
- Session nodeSession = null;
- Session session = null;
- try {
- nodeSession = nodeRepository.login();
- Node repoNode = nodeSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(repositoryFactory,
- keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, repoNode);
-
- String msg = "Your are about to completely delete workspace ["
- + workspaceName + "].\n Do you really want to proceed?";
- boolean result = MessageDialog.openConfirm(DistPlugin.getDefault()
- .getWorkbench().getDisplay().getActiveShell(),
- "Confirm workspace deletion", msg);
-
- if (result) {
- // msg =
- // "There is no possible turning back, are your REALLY sure you want to proceed ?";
- msg = "WARNING: \nCurrent Jackrabbit version used does "
- + "not support workspace deletion.\n"
- + "Thus, the workspace will only be cleaned so "
- + "that you can launch fetch process again.\n\n"
- + "Do you still want to proceed?";
- result = MessageDialog.openConfirm(DistPlugin.getDefault()
- .getWorkbench().getDisplay().getActiveShell(),
- "Confirm workspace deletion", msg);
- }
-
- if (result) {
- session = repository.login(credentials, workspaceName);
- // TODO use this with a newer version of Jackrabbit
- // Workspace wsp = session.getWorkspace();
- // wsp.deleteWorkspace(workspaceName);
- NodeIterator nit = session.getRootNode().getNodes();
- while (nit.hasNext()) {
- Node node = nit.nextNode();
- if (node.isNodeType(NodeType.NT_FOLDER)
- || node.isNodeType(NodeType.NT_UNSTRUCTURED)) {
- // String path = node.getPath();
- node.remove();
- session.save();
- }
- }
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while deleting workspace ["
- + workspaceName + "].", re);
- } finally {
- JcrUtils.logoutQuietly(session);
- JcrUtils.logoutQuietly(nodeSession);
- }
- return null;
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Repository;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.repo.RepoService;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Open a dialog that displays various information on the current repository.
- */
-public class DisplayRepoInformation extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID + ".displayRepoInformation";
- public final static String DEFAULT_LABEL = "Information";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/help.gif");
-
- /* DEPENDENCY INJECTION */
- private RepoService repoService;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IStructuredSelection iss = (IStructuredSelection) HandlerUtil
- .getActiveSite(event).getSelectionProvider().getSelection();
- if (iss.getFirstElement() instanceof RepoElem) {
- RepoElem re = (RepoElem) iss.getFirstElement();
-
- Session defaultSession = null;
- try {
- defaultSession = repoService.getRemoteSession(re.getRepoNodePath(),
- re.getUri(), null);
-
- InformationDialog inputDialog = new InformationDialog(
- HandlerUtil.getActiveSite(event).getShell());
- inputDialog.create();
- // TODO add more information.
- inputDialog.loginTxt.setText(defaultSession.getUserID());
- inputDialog.nameTxt.setText(re.getLabel());
- inputDialog.uriTxt.setText(re.getUri());
- inputDialog.readOnlyBtn.setSelection(re.isReadOnly());
-
- inputDialog.open();
- // } catch (RepositoryException e) {
- // throw new SlcException("Unexpected error while "
- // + "getting repository information.", e);
- } finally {
- JcrUtils.logoutQuietly(defaultSession);
- }
- }
- return null;
- }
-
- private class InformationDialog extends Dialog {
- Text nameTxt;
- Text uriTxt;
- Text loginTxt;
- Button readOnlyBtn;
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- // No Cancel button
- createButton(parent, IDialogConstants.OK_ID, "OK", true);
- }
-
- public InformationDialog(Shell parentShell) {
- super(parentShell);
- }
-
- protected Point getInitialSize() {
- return new Point(500, 250);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- GridLayout layout = new GridLayout(2, false);
- layout.horizontalSpacing = 15;
- composite.setLayout(layout);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
- composite.setLayoutData(gd);
-
- nameTxt = createLT(composite, "Name");
- uriTxt = createLT(composite, "URI");
- loginTxt = createLT(composite, "Logged as");
- readOnlyBtn = createLC(composite, "Read only");
- parent.pack();
- return composite;
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label) {
- new Label(parent, SWT.RIGHT).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.NONE);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- text.setEditable(false);
- return text;
- }
-
- /** Creates label and check. */
- protected Button createLC(Composite parent, String label) {
- new Label(parent, SWT.RIGHT).setText(label);
- Button check = new Button(parent, SWT.CHECK);
- check.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- check.setEnabled(false);
- return check;
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Repository information");
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepoService(RepoService repoService) {
- this.repoService = repoService;
- }
-
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-/** Util command used to enable sub menus in various toolbars. Does nothing */
-public class DoNothing extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID + ".doNothing";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.client.ui.dist.wizards.FetchWizard;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Wrap a {@code RepoSync} as an Eclipse command. Open a wizard that enable
- * definition of the fetch process parameters
- */
-public class Fetch extends AbstractHandler {
- // private final static CmsLog log = CmsLog.getLog(Fetch.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".fetch";
- public final static String DEFAULT_LABEL = "Fetch...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/fetchRepo.png");
-
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- // DEPENDENCY INJECTION
- private Keyring keyring;
- private RepositoryFactory repositoryFactory;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- Session currSession = null;
- try {
- // Target Repository
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- currSession = nodeRepository.login();
- Node targetRepoNode = currSession.getNode(targetRepoPath);
-
- FetchWizard wizard = new FetchWizard(keyring, repositoryFactory,
- nodeRepository);
- wizard.setTargetRepoNode(targetRepoNode);
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
-
- int result = dialog.open();
- if (result == Dialog.OK)
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Unable te retrieve repo node from path", e);
- } finally {
- JcrUtils.logoutQuietly(currSession);
- }
- }
-
- // DEPENDENCY INJECTION
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setNodeRepository(Repository repository) {
- this.nodeRepository = repository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.wizards.ChangeRightsWizard;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Open a dialog to manage rights on the current workspace's root node */
-public class ManageWorkspaceAuth extends AbstractHandler {
- // private static final Log log =
- // LogFactory.getLog(ManageWorkspaceAuth.class);
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".manageWorkspaceAuth";
- public final static String DEFAULT_LABEL = "Manage Rights";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/changeRights.gif");
-
- public final static String PARAM_WORKSPACE_NAME = DistPlugin.PLUGIN_ID
- + ".workspaceName";
-
- /* DEPENDENCY INJECTION */
- private Repository repository;
- private Session session;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
- try {
- session = repository.login(workspaceName);
- ChangeRightsWizard wizard = new ChangeRightsWizard(session);
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- dialog.open();
- return null;
- } catch (RepositoryException re) {
- throw new SlcException("Cannot log in the repository "
- + repository + " in workspace " + workspaceName, re);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.NoSuchWorkspaceException;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryResult;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-
-/** Merge two workspaces */
-public class MergeWorkspaces extends AbstractHandler {
- private final static CmsLog log = CmsLog.getLog(MergeWorkspaces.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".mergeWorkspaces";
- public final static String DEFAULT_LABEL = "Merge";
-
- public final static String PARAM_SOURCE_WORKSPACE_NAME = "srcWkspName";
- public final static String PARAM_SOURCE_REPO_PATH = "srcRepoPath";
- public final static String PARAM_TARGET_WORKSPACE_NAME = "targetWkspName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String targetWkspName = event.getParameter(PARAM_TARGET_WORKSPACE_NAME);
- String sourceRepoPath = event.getParameter(PARAM_SOURCE_REPO_PATH);
- String sourceWkspName = event.getParameter(PARAM_SOURCE_WORKSPACE_NAME);
-
- Session nodeSession = null;
- try {
- nodeSession = nodeRepository.login();
- Node srcRepoNode = nodeSession.getNode(sourceRepoPath);
- Repository srcRepository = RepoUtils.getRepository(repositoryFactory, keyring, srcRepoNode);
- Credentials srcCredentials = RepoUtils.getRepositoryCredentials(keyring, srcRepoNode);
-
- Node targetRepoNode = nodeSession.getNode(targetRepoPath);
- Repository targetRepository = RepoUtils.getRepository(repositoryFactory, keyring, targetRepoNode);
- Credentials targetCredentials = RepoUtils.getRepositoryCredentials(keyring, targetRepoNode);
-
- // String msg = "Are you sure you want to merge distribution ["
- // + sourceWkspName + "] in distribution [" + targetWkspName
- // + "] ?";
- //
- // boolean result = MessageDialog.openConfirm(
- // HandlerUtil.getActiveShell(event), "Confirm Merge", msg);
-
- // if (result) {
- // Open sessions here since the background thread
- // won't necessarily be authenticated.
- // Job should close the sessions.
- Session sourceSession = srcRepository.login(srcCredentials, sourceWkspName);
- Session targetSession;
- try {
- targetSession = targetRepository.login(targetCredentials, targetWkspName);
- } catch (NoSuchWorkspaceException e) {
- Session defaultSession = targetRepository.login(targetCredentials);
- try {
- defaultSession.getWorkspace().createWorkspace(targetWkspName);
- } catch (Exception e1) {
- throw new SlcException("Cannot create new workspace " + targetWkspName, e);
- } finally {
- JcrUtils.logoutQuietly(defaultSession);
- }
- targetSession = targetRepository.login(targetCredentials, targetWkspName);
- }
-
- Job workspaceMergeJob = new WorkspaceMergeJob(sourceSession, targetSession);
- workspaceMergeJob.setUser(true);
- workspaceMergeJob.schedule();
- } catch (RepositoryException re) {
- throw new SlcException("Unexpected error while merging workspaces.", re);
- } finally {
- JcrUtils.logoutQuietly(nodeSession);
- }
- return null;
- }
-
- private static class WorkspaceMergeJob extends Job {
- private Session sourceSession;
- private Session targetSession;
-
- public WorkspaceMergeJob(Session sourceSession, Session targetSession) {
- super("Workspace merge");
- this.sourceSession = sourceSession;
- this.targetSession = targetSession;
- }
-
- @Override
- protected IStatus run(IProgressMonitor eclipseMonitor) {
- long begin = System.currentTimeMillis();
- try {
- Query countQuery = sourceSession.getWorkspace().getQueryManager()
- .createQuery("select file from [nt:file] as file", Query.JCR_SQL2);
- QueryResult result = countQuery.execute();
- Long expectedCount = result.getNodes().getSize();
- if (log.isDebugEnabled())
- log.debug("Will copy " + expectedCount + " files...");
-
- JcrMonitor monitor = new EclipseJcrMonitor(eclipseMonitor);
- eclipseMonitor.beginTask("Copy files", expectedCount.intValue());
-
- Long count = JcrUtils.copyFiles(sourceSession.getRootNode(), targetSession.getRootNode(), true, monitor,
- true);
-
- monitor.done();
- long duration = (System.currentTimeMillis() - begin) / 1000;// in
- // s
- if (log.isDebugEnabled())
- log.debug("Copied " + count + " files in " + (duration / 60) + "min " + (duration % 60) + "s");
-
- return Status.OK_STATUS;
- } catch (RepositoryException e) {
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID, "Cannot merge", e);
- } finally {
- JcrUtils.logoutQuietly(sourceSession);
- JcrUtils.logoutQuietly(targetSession);
- }
- }
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Binary;
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryResult;
-import javax.jcr.util.TraversingItemVisitor;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-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.argeo.slc.repo.maven.AetherUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.argeo.slc.repo.osgi.NormalizeGroup;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.aether.artifact.DefaultArtifact;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Legacy - Make sure than Maven and OSGi metadata are consistent */
-public class NormalizeDistribution extends AbstractHandler implements SlcNames {
- private final static CmsLog log = CmsLog
- .getLog(NormalizeDistribution.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".normalizeDistribution";
- public final static String DEFAULT_LABEL = "Legacy Normalization...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/normalize.gif");
-
- public final static String PARAM_WORKSPACE_NAME = "workspaceName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-
- private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
- private JarFileIndexer jarFileIndexer = new JarFileIndexer();
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String wkspName = event.getParameter(PARAM_WORKSPACE_NAME);
-
- Session nodeSession = null;
- NormalizeJob job;
- try {
-
- NormalizationDialog dialog = new NormalizationDialog(
- HandlerUtil.getActiveShell(event));
- if (dialog.open() != Dialog.OK)
- return null;
-
- nodeSession = nodeRepository.login();
- Node repoNode = nodeSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(repositoryFactory,
- keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, repoNode);
-
- String version = dialog.getVersion();
- Boolean overridePoms = dialog.getOverridePoms();
-
- job = new NormalizeJob(repository.login(credentials, wkspName),
- version, overridePoms);
- job.setUser(true);
- job.schedule();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot normalize " + wkspName, e);
- } finally {
- JcrUtils.logoutQuietly(nodeSession);
- }
- return null;
- }
-
- 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
- Node targetSourceJarNode = session.getNode(targetSourceJarPath);
- artifactIndexer.index(targetSourceJarNode);
- jarFileIndexer.index(targetSourceJarNode);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot add PDE sources for " + sourcesNode,
- e);
- } finally {
- JcrUtils.closeQuietly(origBinary);
- JcrUtils.closeQuietly(osgiBinary);
- }
-
- }
-
- private class NormalizeJob extends Job {
- private Session session;
- private String version;
- private Boolean overridePoms;
-
- public NormalizeJob(Session session, String version,
- Boolean overridePoms) {
- super("Normalize Distribution");
- this.session = session;
- this.version = version;
- this.overridePoms = overridePoms;
- }
-
- @Override
- protected IStatus run(IProgressMonitor progressMonitor) {
-
- try {
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- // normalize artifacts
- Query countQuery = session
- .getWorkspace()
- .getQueryManager()
- .createQuery("select file from [nt:file] as file",
- Query.JCR_SQL2);
- QueryResult result = countQuery.execute();
- Long expectedCount = result.getNodes().getSize();
- monitor.beginTask("Normalize artifacts of "
- + session.getWorkspace().getName(),
- expectedCount.intValue());
- NormalizingTraverser tiv = new NormalizingTraverser(monitor);
- session.getNode(artifactBasePath).accept(tiv);
-
- // normalize groups
- Query groupQuery = session
- .getWorkspace()
- .getQueryManager()
- .createQuery(
- "select group from [" + SlcTypes.SLC_GROUP_BASE
- + "] as group", Query.JCR_SQL2);
- NodeIterator groups = groupQuery.execute().getNodes();
- monitor.beginTask("Normalize groups of "
- + session.getWorkspace().getName(),
- (int) groups.getSize());
- while (groups.hasNext()) {
- NormalizeGroup.processGroupNode(groups.nextNode(), version,
- overridePoms, monitor);
- }
- } catch (Exception e) {
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID,
- "Cannot normalize distribution "
- + session.getWorkspace().getName(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return Status.OK_STATUS;
- }
-
- }
-
- private class NormalizingTraverser extends TraversingItemVisitor {
- JcrMonitor monitor;
-
- public NormalizingTraverser(JcrMonitor monitor) {
- super();
- this.monitor = monitor;
- }
-
- @Override
- protected void entering(Property property, int level)
- throws RepositoryException {
- }
-
- @Override
- protected void entering(Node node, int level)
- throws RepositoryException {
- if (node.isNodeType(NodeType.NT_FILE)) {
- if (node.getName().endsWith("-sources.jar")) {
- monitor.subTask(node.getName());
- packageSourcesAsPdeSource(node);
- node.getSession().save();
- monitor.worked(1);
- if (log.isDebugEnabled())
- log.debug("Processed source artifact " + node.getPath());
- } else if (node.getName().endsWith(".jar")) {
- if (jarFileIndexer.support(node.getPath()))
- if (artifactIndexer.support(node.getPath())) {
- monitor.subTask(node.getName());
- artifactIndexer.index(node);
- jarFileIndexer.index(node);
- node.getSession().save();
- monitor.worked(1);
- if (log.isDebugEnabled())
- log.debug("Processed artifact "
- + node.getPath());
- }
- } else {
- monitor.worked(1);
- }
- }
- }
-
- @Override
- protected void leaving(Property property, int level)
- throws RepositoryException {
- }
-
- @Override
- protected void leaving(Node node, int level) throws RepositoryException {
- }
-
- }
-
- public class NormalizationDialog extends TitleAreaDialog {
- private static final long serialVersionUID = -3103886455862638580L;
-
- private Text versionT;
- private String version;
- private Button overridePomsC;
- private Boolean overridePoms;
-
- public NormalizationDialog(Shell parentShell) {
- super(parentShell);
- }
-
- protected Point getInitialSize() {
- return new Point(300, 250);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- false));
- versionT = createLT(composite, "Version");
- overridePomsC = createLC(composite, "Override POMs");
- setMessage("Configure normalization", IMessageProvider.NONE);
-
- parent.pack();
- return composite;
- }
-
- @Override
- protected void okPressed() {
- version = versionT.getText();
- overridePoms = overridePomsC.getSelection();
- super.okPressed();
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER
- | SWT.NONE);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return text;
- }
-
- /** Creates label and check. */
- protected Button createLC(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Button check = new Button(parent, SWT.CHECK);
- check.setSelection(false);
- check.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return check;
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Normalize...");
- }
-
- public String getVersion() {
- return version;
- }
-
- public Boolean getOverridePoms() {
- return overridePoms;
- }
-
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryResult;
-import javax.jcr.util.TraversingItemVisitor;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.JarFileIndexer;
-import org.argeo.slc.repo.ModularDistributionIndexer;
-import org.argeo.slc.repo.PdeSourcesIndexer;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/**
- * Force the indexing of a given workspace by making sure than Maven and OSGi
- * metadata are consistent. This mechanism normally relies on JCR Listeners but
- * must sometimes be triggered manually
- */
-public class NormalizeWorkspace extends AbstractHandler implements SlcNames {
- private final static CmsLog log = CmsLog.getLog(NormalizeWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".normalizeWorkspace";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin.getImageDescriptor("icons/normalize.gif");
-
- public final static String PARAM_WORKSPACE_NAME = "workspaceName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- private String artifactBasePath = RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH;
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository repository;
-
- // Relevant default node indexers
- private PdeSourcesIndexer pdeSourceIndexer = new PdeSourcesIndexer();
- // WARNING Order is important: must be called in the following order.
- private ModularDistributionIndexer modularDistributionIndexer = new ModularDistributionIndexer();
- private JarFileIndexer jarFileIndexer = new JarFileIndexer();
- private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String wkspName = event.getParameter(PARAM_WORKSPACE_NAME);
-
- Session currSession = null;
- NormalizeJob job;
- try {
- String msg = "Your are about to normalize workspace: " + wkspName
- + ".\nThis will index OSGi bundles and Maven artifacts, "
- + "it will also convert Maven sources to PDE Sources if needed.\n"
- + "Note that no information will be overwritten: " + "all existing information are kept."
- + "\n\n Do you really want to proceed ?";
-
- if (!MessageDialog.openConfirm(DistPlugin.getDefault().getWorkbench().getDisplay().getActiveShell(),
- "Confirm workspace normalization", msg))
- return null;
-
- currSession = repository.login();
- Node repoNode = currSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(repositoryFactory, keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(keyring, repoNode);
-
- job = new NormalizeJob(repository.login(credentials, wkspName));
- job.setUser(true);
- job.schedule();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot normalize " + wkspName, e);
- } finally {
- JcrUtils.logoutQuietly(currSession);
- }
- return null;
- }
-
- private class NormalizeJob extends Job {
- private Session session;
-
- public NormalizeJob(Session session) {
- super("Normalize Distribution");
- this.session = session;
- }
-
- @Override
- protected IStatus run(IProgressMonitor progressMonitor) {
- try {
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- // Normalize artifacts
- Query countQuery = session.getWorkspace().getQueryManager()
- .createQuery("select file from [nt:file] as file", Query.JCR_SQL2);
- QueryResult result = countQuery.execute();
- Long expectedCount = result.getNodes().getSize();
- monitor.beginTask("Normalize artifacts of " + session.getWorkspace().getName(),
- expectedCount.intValue());
- NormalizingTraverser tiv = new NormalizingTraverser(monitor);
- Node artifactBaseNode = session.getNode(artifactBasePath);
- artifactBaseNode.accept(tiv);
- } catch (Exception e) {
- log.error("Error normalizing workspace " + session.getWorkspace().getName() + ": " + e.getMessage());
- if (log.isErrorEnabled())
- e.printStackTrace();
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID,
- "Cannot normalize distribution " + session.getWorkspace().getName(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return Status.OK_STATUS;
- }
- }
-
- private class NormalizingTraverser extends TraversingItemVisitor {
- JcrMonitor monitor;
-
- public NormalizingTraverser(JcrMonitor monitor) {
- super();
- this.monitor = monitor;
- }
-
- @Override
- protected void entering(Property property, int level) throws RepositoryException {
- }
-
- @Override
- protected void entering(Node node, int level) throws RepositoryException {
- if (node.getPath().startsWith(RepoConstants.DIST_DOWNLOAD_BASEPATH))
- return;
-
- if (node.isNodeType(NodeType.NT_FILE)) {
- if (node.getName().endsWith("-sources.jar")) {
- monitor.subTask(node.getName());
- pdeSourceIndexer.index(node);
- node.getSession().save();
- monitor.worked(1);
- if (log.isDebugEnabled())
- log.debug("Processed source artifact " + node.getPath());
- } else if (node.getName().endsWith("-javadoc.jar")) {
- if (log.isDebugEnabled())
- log.debug("Skip indexing of Javadoc jar " + node.getPath());
- } else if (node.getName().endsWith(".jar")) {
- if (jarFileIndexer.support(node.getPath()))
- if (artifactIndexer.support(node.getPath())) {
- monitor.subTask(node.getName());
- modularDistributionIndexer.index(node);
- jarFileIndexer.index(node);
- artifactIndexer.index(node);
- if (node.getSession().hasPendingChanges()) {
- node.getSession().save();
- if (log.isDebugEnabled())
- log.debug("Processed jar artifact " + node.getPath());
- }
- monitor.worked(1);
- }
- } else if (node.getName().endsWith(".pom")) {
- // Removed: we do not support binaries concept anymore.
- // if (distBundleIndexer.support(node.getPath()))
- // distBundleIndexer.index(node);
- if (artifactIndexer.support(node.getPath()))
- artifactIndexer.index(node);
- if (node.getSession().hasPendingChanges()) {
- node.getSession().save();
- if (log.isDebugEnabled())
- log.debug("Processed pom artifact " + node.getPath());
- }
- monitor.worked(1);
- } else {
- monitor.worked(1);
- }
- }
- }
-
- @Override
- protected void leaving(Property property, int level) throws RepositoryException {
- }
-
- @Override
- protected void leaving(Node node, int level) throws RepositoryException {
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setNodeRepository(Repository nodeRepository) {
- this.repository = nodeRepository;
- }
-
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.client.ui.dist.wizards.GenerateBinariesWizard;
-import org.argeo.slc.repo.RepoService;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Open a {@code GenerateBinariesWizard} wizard for the selected node */
-public class OpenGenerateBinariesWizard extends AbstractHandler {
- // private static final CmsLog log = CmsLog.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".openGenerateBinariesWizard";
- public final static String DEFAULT_LABEL = "Generate Aether Index";
- public final static ImageDescriptor DEFAULT_ICON = null;
-
- /* DEPENDENCY INJECTION */
- private RepoService repoService;
-
- // Absolute Coordinates of the current group node
- public final static String PARAM_REPO_NODE_PATH = "param.repoNodePath";
- public final static String PARAM_WORKSPACE_NAME = "param.workspaceName";
- public final static String PARAM_MODULE_PATH = "param.modulePath";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchPart activePart = DistPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActivePart();
-
- String repoNodePath = event.getParameter(PARAM_REPO_NODE_PATH);
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
- String modulePath = event.getParameter(PARAM_MODULE_PATH);
-
- GenerateBinariesWizard wizard = new GenerateBinariesWizard(repoService,
- repoNodePath, workspaceName, modulePath);
-
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- int result = dialog.open();
-
- if (result == Dialog.OK
- && (activePart instanceof RefreshDistributionsView))
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
-
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepoService(RepoService repoService) {
- this.repoService = repoService;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.editors.ArtifactVersionEditor;
-import org.argeo.slc.client.ui.dist.editors.ModularDistVersionEditor;
-import org.argeo.slc.client.ui.dist.editors.ModuleEditorInput;
-import org.argeo.slc.repo.RepoService;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Open the relevant editor for a given module node of a given repository
- * workspace. For the time being, modules can be artifacts or
- * modularDistributions
- */
-public class OpenModuleEditor extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID + ".openModuleEditor";
- public final static String DEFAULT_LABEL = "Open relevant editor";
-
- // use local node repo and repository factory to retrieve and log to
- // relevant repository
- public final static String PARAM_REPO_NODE_PATH = "param.repoNodePath";
- // use URI and repository factory to retrieve and ANONYMOUSLY log in
- // relevant repository
- public final static String PARAM_REPO_URI = "param.repoUri";
- public final static String PARAM_WORKSPACE_NAME = "param.workspaceName";
- public final static String PARAM_MODULE_PATH = "param.modulePath";
-
- /* DEPENDENCY INJECTION */
- private RepoService repoService;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String repoNodePath = event.getParameter(PARAM_REPO_NODE_PATH);
- String repoUri = event.getParameter(PARAM_REPO_URI);
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
- String modulePath = event.getParameter(PARAM_MODULE_PATH);
-
- Session businessSession = null;
- try {
- businessSession = repoService.getRemoteSession(repoNodePath,
- repoUri, workspaceName);
-
- Node module = businessSession.getNode(modulePath);
- ModuleEditorInput mei = new ModuleEditorInput(repoNodePath,
- repoUri, workspaceName, modulePath);
-
- // Choose correct editor based on its mixin
- if (module.isNodeType(SlcTypes.SLC_MODULAR_DISTRIBUTION))
- HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
- .openEditor(mei, ModularDistVersionEditor.ID);
- else
- HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
- .openEditor(mei, ArtifactVersionEditor.ID);
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while "
- + "getting repoNode info for repoNode at path "
- + repoNodePath, e);
- } catch (PartInitException e) {
- throw new SlcException("Unexpected error while "
- + "opening editor for workspace " + workspaceName
- + " with URI " + repoUri + " and repoNode at path "
- + repoNodePath, e);
- } finally {
- JcrUtils.logoutQuietly(businessSession);
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepoService(RepoService repoService) {
- this.repoService = repoService;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.editors.DistWkspEditorInput;
-import org.argeo.slc.client.ui.dist.editors.DistWorkspaceEditor;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Open a distribution workspace editor for a given workspace in a repository
- */
-public class OpenWorkspaceEditor extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".openWorkspaceEditor";
- public final static String DEFAULT_LABEL = "Open editor";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/distribution_perspective.gif");
-
- // Use local node repo and repository factory to retrieve and log to
- // relevant repository
- public final static String PARAM_REPO_NODE_PATH = "param.repoNodePath";
- // Use URI and repository factory to retrieve and ANONYMOUSLY log in
- // relevant repository
- public final static String PARAM_REPO_URI = "param.repoUri";
- public final static String PARAM_WORKSPACE_NAME = "param.workspaceName";
-
- /* DEPENDENCY INJECTION */
- private Repository localRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String repoNodePath = event.getParameter(PARAM_REPO_NODE_PATH);
- String repoUri = event.getParameter(PARAM_REPO_URI);
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
-
- Session defaultSession = null;
- if (repoNodePath != null && repoUri == null) {
- try {
- defaultSession = localRepository.login();
- if (defaultSession.nodeExists(repoNodePath)) {
- Node repoNode = defaultSession.getNode(repoNodePath);
- repoUri = repoNode.getProperty(ArgeoNames.ARGEO_URI)
- .getString();
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while "
- + "getting repoNode at path " + repoNodePath, e);
- } finally {
- JcrUtils.logoutQuietly(defaultSession);
- }
- }
-
- DistWkspEditorInput wei = new DistWkspEditorInput(repoNodePath,
- repoUri, workspaceName);
- try {
- HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
- .openEditor(wei, DistWorkspaceEditor.ID);
- } catch (PartInitException e) {
- throw new SlcException("Unexpected error while "
- + "opening editor for workspace " + workspaceName
- + " with URI " + repoUri + " and repoNode at path "
- + repoNodePath, e);
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setLocalRepository(Repository localRepository) {
- this.localRepository = localRepository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.security.Privilege;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/** Publish the current workspace by giving READ_ONLY rights to anonymous */
-public class PublishWorkspace extends AbstractHandler {
- // private static final CmsLog log = CmsLog.getLog(PublishWorkspace.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".publishWorkspace";
- public final static String DEFAULT_LABEL = "Make Public";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/publish.gif");
-
- public final static String PARAM_WORKSPACE_NAME = "workspaceName";
- public final static String PARAM_TARGET_REPO_PATH = "targetRepoPath";
-
- // DEPENDENCY INJECTION
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- private String publicRole = SlcConstants.USER_ANONYMOUS;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String targetRepoPath = event.getParameter(PARAM_TARGET_REPO_PATH);
- String workspaceName = event.getParameter(PARAM_WORKSPACE_NAME);
-
- Session nodeSession = null;
- Session session = null;
-
- try {
- nodeSession = nodeRepository.login(CmsConstants.HOME_WORKSPACE);
- Node repoNode = nodeSession.getNode(targetRepoPath);
- Repository repository = RepoUtils.getRepository(repositoryFactory,
- keyring, repoNode);
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, repoNode);
-
- String msg = "Are you sure you want to publish this distribution: "
- + workspaceName + " ?";
- boolean result = MessageDialog.openConfirm(DistPlugin.getDefault()
- .getWorkbench().getDisplay().getActiveShell(),
- "Confirm publication", msg);
-
- if (result) {
- session = repository.login(credentials, workspaceName);
- JcrUtils.addPrivilege(session, "/", publicRole,
- Privilege.JCR_READ);
- session.save();
- JcrUtils.logoutQuietly(session);
- // CommandHelpers.callCommand(RefreshDistributionsView.ID);
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while publishing workspace "
- + workspaceName, re);
- } finally {
- JcrUtils.logoutQuietly(session);
- JcrUtils.logoutQuietly(nodeSession);
- }
- return null;
- }
-
- /* 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
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.slc.client.ui.dist.views.ArtifactsBrowser;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Force the refresh of the artifact browser view */
-public class RefreshArtifactBrowser extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ArtifactsBrowser view = (ArtifactsBrowser) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(ArtifactsBrowser.ID);
- view.refresh(null);
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.views.AnonymousDistributionsView;
-import org.argeo.slc.client.ui.dist.views.DistributionsView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IWorkbenchPart;
-
-/** Force refresh of the Distributions View */
-public class RefreshDistributionsView extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".refreshDistributionsView";
- public final static String DEFAULT_LABEL = "Refresh the distribution view";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/refresh.png");
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchPart activePart = DistPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActivePart();
- if (activePart instanceof DistributionsView)
- ((DistributionsView) activePart).refresh();
- else if (activePart instanceof AnonymousDistributionsView)
- ((AnonymousDistributionsView) activePart).refresh();
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.security.Keyring;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.client.ui.dist.wizards.RegisterRepoWizard;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Register a remote repository by creating a node in the current local node. */
-public class RegisterRepository extends AbstractHandler implements ArgeoNames,
- SlcNames {
-
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".registerRepository";
- public final static String DEFAULT_LABEL = "Register a repository...";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/addRepo.gif");
-
- /* DEPENDENCY INJECTION */
- private RepositoryFactory repositoryFactory;
- private Repository nodeRepository;
- private Keyring keyring;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- RegisterRepoWizard wizard = new RegisterRepoWizard(keyring,
- repositoryFactory, nodeRepository);
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), wizard);
- int result = dialog.open();
- if (result == Dialog.OK)
- CommandHelpers.callCommand(RefreshDistributionsView.ID);
- return null;
- }
-
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.net.URL;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.Session;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.core.execution.tasks.JvmProcess;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/** <b>UNDER DEVELOPMENT</b>. Download and prepare an OSGi runtime */
-public class RunInOsgi extends AbstractHandler implements SlcNames {
- private final static CmsLog log = CmsLog.getLog(RunInOsgi.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".runInOsgi";
- public final static String DEFAULT_LABEL = "Run in OSGi";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin
- .getImageDescriptor("icons/runInOsgi.gif");
-
- public final static String PARAM_WORKSPACE_NAME = "workspaceName";
- public final static String PARAM_MODULE_PATH = "modulePath";
-
- /* DEPENDENCY INJECTION */
- private Repository repository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- String workspace = event.getParameter(PARAM_WORKSPACE_NAME);
- String modulePath = event.getParameter(PARAM_MODULE_PATH);
- String port = System.getProperty("argeo.server.port.http");
- // String localMavenBase = System.getProperty("user.home")
- // + "/.m2/repository";
-
- InputStream jarStream = null;
- OutputStream out = null;
- Writer writer = null;
- Session session = null;
- try {
- // Bundle distPluginBundle = DistPlugin.getDefault().getBundle();
- // File baseDir = distPluginBundle.getBundleContext().getDataFile(
- // "runInOSGi");
- File baseDir = new File(System.getProperty("java.io.tmpdir")
- + "/runInOSGi-" + System.getProperty("user.name"));
- if (baseDir.exists())
- FileUtils.deleteDirectory(baseDir);
- File libDir = new File(baseDir, "lib");
- libDir.mkdirs();
- File confDir = new File(baseDir, "configuration");
- confDir.mkdirs();
- File dataDir = new File(baseDir, "data");
- dataDir.mkdirs();
-
- session = repository.login(workspace);
-
- // NodeIterator bundles = listBundleArtifacts(session);
- // if (log.isDebugEnabled())
- // log.debug("## Copying to " + libDir);
- //
- // File equinoxJar = null;
- // List<File> files = new ArrayList<File>();
- // bundles: while (bundles.hasNext()) {
- // Node bundleNode = bundles.nextNode();
- // String symbolicName = JcrUtils.get(bundleNode,
- // SLC_SYMBOLIC_NAME);
- //
- // // skip sources
- // if (symbolicName.endsWith(".source"))
- // continue bundles;
- // // skip eclipse
- // if (symbolicName.startsWith("org.eclipse")
- // && !symbolicName.equals("org.eclipse.osgi"))
- // continue bundles;
- // if (symbolicName.equals("org.polymap.openlayers.rap.widget"))
- // continue bundles;
- //
- // File targetFile = new File(libDir, bundleNode.getName());
- // out = new FileOutputStream(targetFile);
- // jarStream = bundleNode.getNode(Node.JCR_CONTENT)
- // .getProperty(Property.JCR_DATA).getBinary().getStream();
- // IOUtils.copy(jarStream, out);
- // if (symbolicName.equals("org.eclipse.osgi"))
- // equinoxJar = targetFile;
- // else
- // files.add(targetFile);
- // if (log.isDebugEnabled())
- // log.debug("Copied " + targetFile.getName());
- //
- // IOUtils.closeQuietly(out);
- // IOUtils.closeQuietly(jarStream);
- // }
- //
- // StringBuffer osgiBundles = new StringBuffer("osgi.bundles=");
- // for (int i = 0; i < files.size(); i++) {
- // if (i != 0)
- // osgiBundles.append(',');
- // osgiBundles.append(files.get(i).getName());
- // }
-
- String equinoxJar = null;
-
- Node distModule = session.getNode(modulePath);
- NodeIterator coordinates = distModule.getNode(SLC_MODULES)
- .getNodes();
- StringBuilder conf = new StringBuilder(1024 * 1024);
- conf.append("osgi.clean=true\n");
- conf.append("osgi.console=7777\n");
- // conf.append("osgi.console.enable.builtin=true\n");
-
- conf.append("osgi.bundles=");
- coords: while (coordinates.hasNext()) {
- Node coord = coordinates.nextNode();
- // String category =
- // coord.getProperty(SLC_CATEGORY).getString();
- String name = coord.getProperty(SLC_NAME).getString();
- String version = coord.getProperty(SLC_VERSION).getString();
- Artifact artifact = RepoUtils.asArtifact(coord);
- String path = MavenConventionsUtils.artifactPath("", artifact);
- String url = "http://localhost:" + port + "/data/public/java/"
- + workspace + path;
- if (log.isDebugEnabled())
- log.debug(url);
- File f = new File(libDir, name + "-" + version + ".jar");
- FileUtils.copyURLToFile(new URL(url), f);
- if (name.equals("org.eclipse.osgi")) {
- // File f = new File(localMavenBase + path);
- // if (!f.exists())
- // FileUtils.copyURLToFile(new URL(url), f);
- equinoxJar = f.getCanonicalPath();
- continue coords;
- }
- conf.append(f.getName());
- if (coordinates.hasNext())
- conf.append(",\\\n");
- }
-
- File confIni = new File(confDir, "config.ini");
- writer = new FileWriter(confIni);
- writer.write(conf.toString());
- IOUtils.closeQuietly(writer);
-
- // Map<String, String> configuration = new HashMap<String,
- // String>();
- // configuration.put("osgi.configuration.area",
- // confDir.getCanonicalPath());
- // configuration.put("osgi.instance.area",
- // dataDir.getCanonicalPath());
- // // Do clean
- // configuration.put("osgi.clean", "true");
-
- JvmProcess osgiRuntime = new JvmProcess();
- osgiRuntime.setExecDir(baseDir.getCanonicalPath());
- if (equinoxJar == null)
- throw new SlcException("Cannot find OSGi runtime.");
- osgiRuntime.setMainJar(equinoxJar);
- osgiRuntime.arg("-configuration", confDir.getCanonicalPath()).arg(
- "-data", dataDir.getCanonicalPath());
- // .arg("-console", "7777").arg("-clean");
- osgiRuntime.setLogCommand(true);
- osgiRuntime.afterPropertiesSet();
- Job job = new RunInOsgiJob(osgiRuntime);
- job.schedule();
- // osgiRuntime.run();
-
- // Map<String, String> configuration = new HashMap<String,
- // String>();
- // configuration.put("osgi.configuration.area",
- // confDir.getCanonicalPath());
- // configuration.put("osgi.instance.area",
- // dataDir.getCanonicalPath());
- // // Do clean
- // configuration.put("osgi.clean", "true");
- // ServiceLoader<FrameworkFactory> ff = ServiceLoader
- // .load(FrameworkFactory.class);
- // FrameworkFactory frameworkFactory = ff.iterator().next();
- // Framework framework =
- // frameworkFactory.newFramework(configuration);
- // framework.start();
- // BundleContext testBundleContext = framework.getBundleContext();
-
- // for (int i = 0; i < files.size(); i++) {
- // testBundleContext.installBundle("file://"
- // + files.get(i).getCanonicalPath());
- // }
- //
- // Bundle[] testBundles = testBundleContext.getBundles();
- // for (Bundle bundle : testBundles) {
- // if (log.isDebugEnabled())
- // log.debug(bundle.getSymbolicName() + " "
- // + bundle.getVersion());
- // }
-
- } catch (Exception e) {
- ErrorFeedback.show("Cannot run in OSGi", e);
- } finally {
- IOUtils.closeQuietly(jarStream);
- IOUtils.closeQuietly(out);
- IOUtils.closeQuietly(writer);
- JcrUtils.logoutQuietly(session);
- }
-
- return null;
- }
-
- // private NodeIterator listBundleArtifacts(Session session)
- // throws RepositoryException {
-
- // QueryManager queryManager = session.getWorkspace().getQueryManager();
- // QueryObjectModelFactory factory = queryManager.getQOMFactory();
- //
- // final String bundleArtifactsSelector = "bundleArtifacts";
- // Selector source = factory.selector(SlcTypes.SLC_BUNDLE_ARTIFACT,
- // bundleArtifactsSelector);
- //
- // Ordering order = factory.ascending(factory.propertyValue(
- // bundleArtifactsSelector, SlcNames.SLC_SYMBOLIC_NAME));
- // Ordering[] orderings = { order };
- //
- // QueryObjectModel query = factory.createQuery(source, null, orderings,
- // null);
- //
- // QueryResult result = query.execute();
- // return result.getNodes();
- // }
-
- private class RunInOsgiJob extends Job {
- final JvmProcess osgiRuntime;
-
- public RunInOsgiJob(JvmProcess osgiRuntime) {
- super("OSGi Test");
- this.osgiRuntime = osgiRuntime;
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- osgiRuntime.setSynchronous(false);
- osgiRuntime.run();
- while (!monitor.isCanceled()) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // silent
- }
-
- if (monitor.isCanceled()) {
- osgiRuntime.kill();
- return Status.CANCEL_STATUS;
- }
- if (!osgiRuntime.isRunning())
- break;
- }
- return Status.OK_STATUS;
- }
-
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.views.ArtifactsBrowser;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.State;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Change visible state of the ArtifactBrower size column */
-public class ShowSizeColumn extends AbstractHandler {
- public final static String ID = DistPlugin.PLUGIN_ID + ".showSizeColumn";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ArtifactsBrowser view = (ArtifactsBrowser) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .findView(ArtifactsBrowser.ID);
-
- ICommandService service = (ICommandService) PlatformUI.getWorkbench()
- .getService(ICommandService.class);
- Command command = service.getCommand(ID);
- State state = command.getState(ID + ".toggleState");
-
- boolean wasVisible = (Boolean) state.getValue();
- view.setSizeVisible(!wasVisible);
- state.setValue(!wasVisible);
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/**
- * Un-register a remote repository by deleting the corresponding RepoNode from
- * the node Repository. It does not affect the repository instance
- */
-public class UnregisterRemoteRepo extends AbstractHandler {
- // private static final CmsLog log = CmsLog
- // .getLog(UnregisterRemoteRepo.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".unregisterRemoteRepo";
- public final static String DEFAULT_LABEL = "Unregister";
- public final static ImageDescriptor DEFAULT_ICON = DistPlugin.getImageDescriptor("icons/removeItem.gif");
-
- public final static String PARAM_REPO_PATH = DistPlugin.PLUGIN_ID + ".repoNodePath";
-
- // DEPENCY INJECTION
- private Repository nodeRepository;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- Session session = null;
- String repoPath = event.getParameter(PARAM_REPO_PATH);
- if (repoPath == null)
- return null;
-
- try {
- session = nodeRepository.login(CmsConstants.HOME_WORKSPACE);
- Node rNode = session.getNode(repoPath);
- if (rNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
-
- String alias = rNode.getProperty(Property.JCR_TITLE).getString();
- String msg = "Your are about to unregister remote repository: " + alias + "\n"
- + "Are you sure you want to proceed ?";
-
- boolean result = MessageDialog.openConfirm(
- DistPlugin.getDefault().getWorkbench().getDisplay().getActiveShell(), "Confirm Delete", msg);
-
- if (result) {
- rNode.remove();
- session.save();
- }
- CommandUtils.callCommand(RefreshDistributionsView.ID);
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while unregistering remote repository.", e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return null;
- }
-
- // DEPENCY INJECTION
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-}
\ No newline at end of file
+++ /dev/null
-<html>
-<head></head>
-<body>
-Eclipse commands wrapping Runnable objects define in non-ui specific code.
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import javax.jcr.RepositoryFactory;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-/**
- * Enable browsing in local public slc distribution repositories. For the time
- * being, it supports only one repository at a time. Repository factory must be
- * injected
- */
-public class AnonymousDistTreeContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = -4149180221319229128L;
-
- // List<RepoElem> repositories = new ArrayList<RepoElem>();
- private RepoElem publicRepo;
-
- private RepositoryFactory repositoryFactory;
-
- /**
- * @param input
- * the URI to the public repository to browse
- */
- public Object[] getElements(Object input) {
- String uri = (String) input;
- publicRepo = new RepoElem(repositoryFactory, uri,
- "Argeo Public Repository");
- // force connection and creation of the children UI object
- publicRepo.login();
- return publicRepo.getChildren();
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- // @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof TreeParent)
- return ((TreeParent) parentElement).getChildren();
- else
- return null;
- }
-
- // @Override
- public Object getParent(Object element) {
- if (element instanceof TreeParent)
- return ((TreeParent) element).getParent();
- return null;
- }
-
- // @Override
- public boolean hasChildren(Object element) {
- if (element instanceof TreeParent)
- return ((TreeParent) element).hasChildren();
- else
- return false;
- }
-
- public void dispose() {
- publicRepo.dispose();
- }
-
- /*
- * DEPENDENCY INJECTION
- */
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.graphics.Image;
-
-/** Retrieve artifact information to be displayed in an artifact tree or table */
-public class ArtifactLabelProvider extends ColumnLabelProvider implements
- DistConstants, SlcTypes {
- private static final long serialVersionUID = 8672622174076959016L;
-
- // To be able to change column order easily
- public static final int COLUMN_TREE = 0;
- public static final int COLUMN_DATE = 1;
- public static final int COLUMN_SIZE = 2;
-
- // Utils
- protected static DateFormat timeFormatter = new SimpleDateFormat(
- DATE_TIME_FORMAT);
-
- public void update(ViewerCell cell) {
- int colIndex = cell.getColumnIndex();
- Object element = cell.getElement();
- cell.setText(getColumnText(element, colIndex));
- if (element instanceof Node && colIndex == 0) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SLC_ARTIFACT_BASE))
- cell.setImage(DistImages.IMG_ARTIFACT_BASE);
- else if (node.isNodeType(SLC_ARTIFACT_VERSION_BASE))
- cell.setImage(DistImages.IMG_ARTIFACT_VERSION_BASE);
- } catch (RepositoryException e) {
- // Silent
- }
- }
- }
-
- @Override
- public Image getImage(Object element) {
-
- if (element instanceof Node) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SLC_ARTIFACT_BASE)) {
- return DistImages.IMG_ARTIFACT_BASE;
- } else if (node.isNodeType(SLC_ARTIFACT_VERSION_BASE)) {
- return DistImages.IMG_ARTIFACT_VERSION_BASE;
- }
- } catch (RepositoryException e) {
- // Silent
- }
- }
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex) {
- try {
- if (element instanceof Node) {
- Node node = (Node) element;
- switch (columnIndex) {
- case COLUMN_TREE:
- return node.getName();
- case COLUMN_SIZE:
- long size = JcrUtils.getNodeApproxSize(node) / 1024;
- if (size > 1024)
- return size / 1024 + " MB";
- else
- return size + " KB";
- case COLUMN_DATE:
- if (node.hasProperty(Property.JCR_LAST_MODIFIED))
- return timeFormatter.format(node
- .getProperty(Property.JCR_LAST_MODIFIED)
- .getDate().getTime());
- else
- return null;
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexepected error while getting property values", re);
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.jcr.util.JcrItemsComparator;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-/** Enable specific browsing of an artifact tree */
-public class ArtifactsTreeContentProvider implements ITreeContentProvider,
- SlcTypes {
- private static final long serialVersionUID = -8097817288192073987L;
-
- // Utils
- private boolean sortChildren = true;
- private JcrItemsComparator itemComparator = new JcrItemsComparator();
-
- public Object[] getElements(Object parent) {
- return getChildren(parent);
- }
-
- public Object getParent(Object child) {
- return null;
- }
-
- public Object[] getChildren(Object parent) {
- Object[] elements = null;
- try {
- if (parent instanceof Node) {
- Node node = (Node) parent;
- NodeIterator ni = node.getNodes();
- List<Node> nodesList = new ArrayList<Node>();
- while (ni.hasNext()) {
- nodesList.add(ni.nextNode());
- }
- if (sortChildren) {
- Node[] arr = (Node[]) nodesList.toArray(new Node[nodesList
- .size()]);
- Arrays.sort(arr, itemComparator);
- return arr;
- } else
- return nodesList.toArray();
-
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while listing node properties", e);
- }
- return elements;
- }
-
- public boolean hasChildren(Object parent) {
- try {
- if (parent instanceof Node) {
- Node curNode = (Node) parent;
- // We manually stop digging at this level
- if (curNode.isNodeType(SLC_ARTIFACT_VERSION_BASE))
- return false;
- else if (curNode.hasNodes())
- return true;
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while checking if property is multiple",
- e);
- }
- return false;
- }
-
- public void setSortChildren(boolean sortChildren) {
- this.sortChildren = sortChildren;
- }
-
- public boolean getSortChildren() {
- return sortChildren;
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public void dispose() {
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import javax.jcr.Credentials;
-import javax.jcr.NoSuchWorkspaceException;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoUtils;
-
-/**
- * Provide shortcuts to retrieve sessions, repositories and workspaces that are
- * persisted in the current user node using path only.
- */
-public class DistSessionFactory {
-
- /* DEPENDENCY INJECTION */
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Repository nodeRepository;
-
- /**
- * Returns a new session on the given workspace. This session *must* be
- * disposed by the caller. If the workspace does not exist and
- * createIfNeeded==true, tries to create it
- *
- * */
- public Session getSessionFromWorkspacePath(String path,
- boolean createIfNeeded) {
- Session nodeSession = null;
- try {
- nodeSession = nodeRepository.login();
- Node localWksp = nodeSession.getNode(path);
- Repository repository = RepoUtils.getRepository(repositoryFactory,
- keyring, localWksp.getParent());
- Credentials credentials = RepoUtils.getRepositoryCredentials(
- keyring, localWksp.getParent());
-
- String wkspName = JcrUtils.lastPathElement(path);
- Session session = null;
- try {
- session = repository.login(credentials, wkspName);
- } catch (NoSuchWorkspaceException e) {
- if (createIfNeeded) {
- Session defaultSession = repository.login(credentials);
- try {
- defaultSession.getWorkspace().createWorkspace(wkspName);
- } catch (Exception e1) {
- throw new SlcException("Cannot create new workspace "
- + wkspName, e);
- } finally {
- JcrUtils.logoutQuietly(defaultSession);
- }
- session = repository.login(credentials, wkspName);
- } else
- throw new SlcException("Workspace" + wkspName
- + "does not exists and should not be created", e);
- }
- return session;
- } catch (RepositoryException e) {
- throw new SlcException("cannot create session" + " for workspace "
- + path, e);
- } finally {
- JcrUtils.logoutQuietly(nodeSession);
- }
- }
-
- /*
- * DEPENDENCY INJECTION
- */
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import org.argeo.slc.client.ui.dist.model.DistParentElem;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionElem;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.client.ui.dist.model.WkspGroupElem;
-import org.argeo.slc.client.ui.dist.model.WorkspaceElem;
-import org.argeo.slc.client.ui.dist.utils.NameVersionComparator;
-import org.argeo.slc.client.ui.dist.utils.VersionComparator;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-
-/** Specific comparator to enhance Distribution tree browsers */
-public class DistTreeComparator extends ViewerComparator {
- private static final long serialVersionUID = -7386716562202568704L;
-
- private VersionComparator vc = new VersionComparator();
- private NameVersionComparator nvc = new NameVersionComparator();
-
- public int category(Object element) {
- if (element instanceof RepoElem)
- if (((RepoElem) element).inHome())
- // Home repository always first
- return 2;
- else
- return 5;
- else if (element instanceof WkspGroupElem)
- return 10;
- else if (element instanceof WorkspaceElem)
- return 15;
- else
- return 20;
- }
-
- public int compare(Viewer viewer, Object e1, Object e2) {
- int cat1 = category(e1);
- int cat2 = category(e2);
-
- if (cat1 != cat2) {
- return cat1 - cat2;
- }
-
- String s1, s2;
-
- if (e1 instanceof DistParentElem) {
- s1 = ((DistParentElem) e1).getName();
- s2 = ((DistParentElem) e2).getName();
- } else {
- s1 = e1.toString();
- s2 = e2.toString();
- }
-
- if (e1 instanceof WorkspaceElem)
- // Reverse order for nameversions
- return nvc.compare(viewer, s2, s1);
- else if (e1 instanceof ModularDistVersionElem)
- // Reverse order for versions
- return vc.compare(viewer, s2, s1);
- else
- return s1.compareTo(s2);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.jface.viewers.IElementComparer;
-
-/** Compares two elements of the Distribution tree */
-public class DistTreeComparer implements IElementComparer {
-
- public int hashCode(Object element) {
- if (element instanceof TreeParent)
- return ((TreeParent) element).hashCode();
- else
-
- return element.getClass().toString().hashCode();
- }
-
- public boolean equals(Object elementA, Object elementB) {
- if (!(elementA instanceof TreeParent)
- || !(elementB instanceof TreeParent)) {
- return elementA == null ? elementB == null : elementA
- .equals(elementB);
- } else {
- TreeParent tpA = ((TreeParent) elementA);
- TreeParent tpB = ((TreeParent) elementB);
- return tpA.compareTo(tpB) == 0;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.repo.RepoConstants;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-/**
- * Enables browsing in local and remote SLC software repositories. Keyring and
- * repository factory must be injected
- */
-public class DistTreeContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = -7640840211717811421L;
-
- /* DEPENDENCY INJECTION */
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
-
- // Context
- private Session nodeSession;
- List<RepoElem> repositories = new ArrayList<RepoElem>();
-
- public Object[] getElements(Object input) {
- Repository nodeRepository = (Repository) input;
- try {
- if (nodeSession != null)
- dispose();
- nodeSession = nodeRepository.login(CmsConstants.HOME_WORKSPACE);
-
- String reposPath = CmsJcrUtils.getUserHome(nodeSession).getPath() + RepoConstants.REPOSITORIES_BASE_PATH;
-
- if (!nodeSession.itemExists(reposPath))
- initializeModel(nodeSession);
-
- NodeIterator repos = nodeSession.getNode(reposPath).getNodes();
- while (repos.hasNext()) {
- Node repoNode = repos.nextNode();
- if (repoNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
- String label = repoNode.isNodeType(NodeType.MIX_TITLE)
- ? repoNode.getProperty(Property.JCR_TITLE).getString()
- : repoNode.getName();
- repositories.add(new RepoElem(repositoryFactory, keyring, repoNode, label));
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get base elements", e);
- }
- return repositories.toArray();
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- // @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof TreeParent)
- return ((TreeParent) parentElement).getChildren();
- else
- return null;
- }
-
- // @Override
- public Object getParent(Object element) {
- if (element instanceof TreeParent)
- return ((TreeParent) element).getParent();
- return null;
- }
-
- // @Override
- public boolean hasChildren(Object element) {
- if (element instanceof TreeParent)
- return ((TreeParent) element).hasChildren();
- else
- return false;
- }
-
- public void dispose() {
- for (RepoElem repoElem : repositories)
- repoElem.dispose();
- repositories = new ArrayList<RepoElem>();
- JcrUtils.logoutQuietly(nodeSession);
- }
-
- private void initializeModel(Session nodeSession) {
- try {
- Node homeNode = CmsJcrUtils.getUserHome(nodeSession);
- if (homeNode == null) // anonymous
- throw new SlcException("User must be authenticated.");
-
- // make sure base directory is available
- Node repos = JcrUtils.mkdirs(homeNode, RepoConstants.REPOSITORIES_BASE_PATH, null);
- if (nodeSession.hasPendingChanges())
- nodeSession.save();
-
- // register default local java repository
- String alias = RepoConstants.DEFAULT_JAVA_REPOSITORY_ALIAS;
- Repository javaRepository = CmsJcrUtils.getRepositoryByAlias(repositoryFactory, alias);
- if (javaRepository != null) {
- if (!repos.hasNode(alias)) {
- Node repoNode = repos.addNode(alias, ArgeoTypes.ARGEO_REMOTE_REPOSITORY);
- repoNode.setProperty(ArgeoNames.ARGEO_URI, "vm:///" + alias);
- repoNode.addMixin(NodeType.MIX_TITLE);
- repoNode.setProperty(Property.JCR_TITLE, RepoConstants.DEFAULT_JAVA_REPOSITORY_LABEL);
- nodeSession.save();
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot initialize model", e);
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.commands.OpenModuleEditor;
-import org.argeo.slc.client.ui.dist.commands.OpenWorkspaceEditor;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionElem;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.client.ui.dist.model.WorkspaceElem;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-
-/** Listen to double-clicks on the distributions view tree. */
-public class DistTreeDoubleClickListener implements IDoubleClickListener {
-
- private TreeViewer treeViewer;
-
- public DistTreeDoubleClickListener(TreeViewer treeViewer) {
- this.treeViewer = treeViewer;
- }
-
- public void doubleClick(DoubleClickEvent event) {
- if (event.getSelection() == null || event.getSelection().isEmpty())
- return;
- Object obj = ((IStructuredSelection) event.getSelection())
- .getFirstElement();
-
- if (obj instanceof RepoElem) {
- RepoElem rpNode = (RepoElem) obj;
- if (!rpNode.isConnected()) {
- rpNode.login();
- treeViewer.refresh(obj);
- }
- } else if (obj instanceof WorkspaceElem) {
- WorkspaceElem we = (WorkspaceElem) obj;
- RepoElem repoElem = we.getRepoElem();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenWorkspaceEditor.PARAM_REPO_NODE_PATH,
- repoElem.getRepoNodePath());
- params.put(OpenWorkspaceEditor.PARAM_REPO_URI, repoElem.getUri());
- params.put(OpenWorkspaceEditor.PARAM_WORKSPACE_NAME,
- we.getWorkspaceName());
- CommandUtils.callCommand(OpenWorkspaceEditor.ID, params);
-
- } else if (obj instanceof ModularDistVersionElem) {
- ModularDistVersionElem modDistElem = (ModularDistVersionElem) obj;
- WorkspaceElem wkspElem = modDistElem.getWorkspaceElem();
- Node moduleNode = modDistElem.getModularDistVersionNode();
- RepoElem repoElem = wkspElem.getRepoElem();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenModuleEditor.PARAM_REPO_NODE_PATH,
- repoElem.getRepoNodePath());
- params.put(OpenModuleEditor.PARAM_REPO_URI, repoElem.getUri());
- params.put(OpenModuleEditor.PARAM_WORKSPACE_NAME,
- wkspElem.getWorkspaceName());
- try {
- params.put(OpenModuleEditor.PARAM_MODULE_PATH,
- moduleNode.getPath());
- } catch (RepositoryException re) {
- throw new SlcException("Cannot get path for node " + moduleNode
- + " while setting parameters for "
- + "command OpenModuleEditor", re);
- }
- CommandUtils.callCommand(OpenModuleEditor.ID, params);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.controllers;
-
-import org.argeo.cms.ui.jcr.JcrImages;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.model.DistParentElem;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionBaseElem;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionElem;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.client.ui.dist.model.WkspGroupElem;
-import org.argeo.slc.client.ui.dist.model.WorkspaceElem;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.swt.graphics.Image;
-
-/** Manage icons and labels for the Distributions tree browser */
-public class DistTreeLabelProvider extends ColumnLabelProvider {
- private static final long serialVersionUID = -7889294105284404373L;
-
- @Override
- public String getText(Object element) {
- if (element instanceof DistParentElem)
- return ((DistParentElem) element).getName();
- else
- return element.toString();
- }
-
- @Override
- public Image getImage(Object element) {
- if (element instanceof RepoElem) {
- RepoElem re = ((RepoElem) element);
- if (re.inHome())
- return DistImages.IMG_HOME_REPO;
- else if (re.isConnected())
- return JcrImages.REPOSITORY_CONNECTED;
- else
- return JcrImages.REPOSITORY_DISCONNECTED;
- } else if (element instanceof WorkspaceElem) {
- return JcrImages.WORKSPACE_CONNECTED;
- } else if (element instanceof WkspGroupElem)
- return DistImages.IMG_WKSP_GROUP;
- // else if (element instanceof GroupBaseElem)
- // return DistImages.IMG_GROUP_BASE;
- else if (element instanceof ModularDistVersionBaseElem)
- return DistImages.IMG_MODULAR_DIST_BASE;
- else if (element instanceof ModularDistVersionElem)
- return DistImages.IMG_MODULAR_DIST_VERSION;
- return super.getImage(element);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.RepoService;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.FormEditor;
-
-/** Artifact editor in a multiple repository environment */
-public class ArtifactVersionEditor extends FormEditor implements SlcNames {
- private static final long serialVersionUID = 1109872666962757000L;
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".artifactVersionEditor";
-
- /* DEPENDENCY INJECTION */
- private RepoService repoService;
-
- // Business Objects
- private Session businessSession;
- private Node artifact;
-
- private ModuleEditorInput editorInput;
-
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- editorInput = (ModuleEditorInput) input;
- businessSession = repoService.getRemoteSession(
- editorInput.getRepoNodePath(), editorInput.getUri(),
- editorInput.getWorkspaceName());
- try {
- artifact = businessSession.getNode(editorInput.getModulePath());
- } catch (RepositoryException e) {
- throw new PartInitException(
- "Unable to initialise editor for artifact "
- + editorInput.getModulePath() + " in workspace "
- + editorInput.getWorkspaceName(), e);
- }
- super.init(site, input);
- }
-
- /** Override to provide a specific part name */
- protected String getFormattedName() {
- try {
- String partName = null;
- if (artifact.hasProperty(SLC_ARTIFACT_ID))
- partName = artifact.getProperty(SLC_ARTIFACT_ID).getString();
- else
- partName = artifact.getName();
-
- if (partName.length() > 10) {
- partName = "..." + partName.substring(partName.length() - 10);
- }
- return partName;
- } catch (RepositoryException re) {
- throw new SlcException(
- "unable to get slc:artifactId Property for node "
- + artifact, re);
- }
- }
-
- @Override
- protected void addPages() {
- setPartName(getFormattedName());
-
- try {
- addPage(new BundleDetailPage(this, "Details ", artifact));
- addPage(new BundleDependencyPage(this, "Dependencies ", artifact));
- addPage(new BundleRawPage(this, "Raw Meta-Data ", artifact));
- } catch (PartInitException e) {
- throw new SlcException("Cannot add distribution editor pages", e);
- }
-
- }
-
- @Override
- public void doSave(IProgressMonitor arg0) {
- }
-
- @Override
- public void dispose() {
- JcrUtils.logoutQuietly(businessSession);
- super.dispose();
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- protected RepoService getRepoService() {
- return repoService;
- }
-
- protected Node getArtifact() {
- return artifact;
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepoService(RepoService repoService) {
- this.repoService = repoService;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Present main information of a given OSGI bundle
- */
-public class BundleDependencyPage extends FormPage implements SlcNames {
- // private final static Log log =
- // LogFactory.getLog(ArtifactDetailsPage.class);
-
- // Main business Objects
- private Node currBundle;
-
- // This page widgets
- private FormToolkit toolkit;
-
- public BundleDependencyPage(FormEditor editor, String title,
- Node currentNode) {
- super(editor, "id", title);
- this.currBundle = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- toolkit = managedForm.getToolkit();
- try {
- if (currBundle.hasProperty(DistConstants.SLC_BUNDLE_NAME))
- form.setText(currBundle.getProperty(
- DistConstants.SLC_BUNDLE_NAME).getString());
- Composite body = form.getBody();
- GridLayout layout = new GridLayout(1, false);
- layout.horizontalSpacing = layout.marginWidth = 0;
- layout.verticalSpacing = layout.marginHeight = 0;
- body.setLayout(layout);
-
- Composite part = toolkit.createComposite(body);
- createExportPackageSection(part);
- GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false);
- gd.heightHint = 180;
- part.setLayoutData(gd);
-
- part = toolkit.createComposite(body);
- createImportPackageSection(part);
- gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- // gd.heightHint = 200;
- part.setLayoutData(gd);
-
- part = toolkit.createComposite(body);
- createReqBundleSection(part);
- gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- part.setLayoutData(gd);
-
- managedForm.reflow(true);
-
- } catch (RepositoryException e) {
- throw new SlcException("unexpected error "
- + "while creating bundle details page");
- }
- }
-
- // Workaround to add an artificial level to the export package browser
- private class LevelElem {
- private String label;
- private Object parent;
-
- public LevelElem(String label, Object parent) {
- this.label = label;
- this.parent = parent;
- }
-
- public String toString() {
- return label;
- }
-
- public Object getParent() {
- return parent;
- }
- }
-
- /** Export Package Section */
- private void createExportPackageSection(Composite parent)
- throws RepositoryException {
- parent.setLayout(new GridLayout());
-
- // Define the TableViewer
-
- Section section = addSection(parent, "Export packages");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- TreeViewer viewer = new TreeViewer(section, SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.BORDER);
- final Tree tree = viewer.getTree();
- tree.setHeaderVisible(false);
- tree.setLinesVisible(true);
- tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- TreeViewerColumn col = new TreeViewerColumn(viewer, SWT.FILL);
- col.getColumn().setWidth(400);
-
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 1376400790495130862L;
-
- @Override
- public String getText(Object element) {
- if (element instanceof Node)
- return JcrUtils.get((Node) element, SlcNames.SLC_NAME);
- else
- return element.toString();
- }
-
- @Override
- public Image getImage(Object element) {
- if (element instanceof Node) {
- try {
- Node node = (Node) element;
- if (node.isNodeType(SlcTypes.SLC_EXPORTED_PACKAGE))
- return DistImages.IMG_PACKAGE;
- } catch (RepositoryException e) {
- throw new SlcException("Error retriving "
- + "image for the labelProvider", e);
- }
- }
- return null;
- }
- });
-
- viewer.setContentProvider(new ITreeContentProvider() {
- private static final long serialVersionUID = 1898086304761992568L;
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- }
-
- public Object[] getElements(Object inputElement) {
- try {
- List<Node> nodes = JcrUtils.nodeIteratorToList(listNodes(
- currBundle, SlcTypes.SLC_EXPORTED_PACKAGE,
- SlcNames.SLC_NAME));
- return nodes.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list children Nodes", e);
- }
- }
-
- public Object[] getChildren(Object parentElement) {
- // Only 2 levels for the time being
- try {
- if (parentElement instanceof LevelElem) {
- Node node = (Node) ((LevelElem) parentElement)
- .getParent();
- List<Node> nodes = JcrUtils
- .nodeIteratorToList(listNodes(node,
- SlcTypes.SLC_JAVA_PACKAGE,
- SlcNames.SLC_NAME));
- return nodes.toArray();
- } else if (parentElement instanceof Node) {
- Node pNode = (Node) parentElement;
- if (pNode.isNodeType(SlcTypes.SLC_EXPORTED_PACKAGE)) {
- if (listNodes(pNode, SlcTypes.SLC_JAVA_PACKAGE,
- SlcNames.SLC_NAME).getSize() > 0) {
- Object[] result = { new LevelElem("uses", pNode) };
- return result;
- }
- }
- }
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list children Nodes", e);
- }
- }
-
- public Object getParent(Object element) {
- // useless
- return null;
- }
-
- public boolean hasChildren(Object element) {
- try {
- if (element instanceof LevelElem)
- return true;
- else {
- Node pNode = (Node) element;
- if (pNode.isNodeType(SlcTypes.SLC_EXPORTED_PACKAGE)) {
- return listNodes(pNode, SlcTypes.SLC_JAVA_PACKAGE,
- SlcNames.SLC_NAME).getSize() > 0;
- }
- }
- return false;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot check children Nodes", e);
- }
- }
- });
-
- section.setClient(tree);
- viewer.setInput("Initialize");
- // work around a display problem : the tree table has only a few lines
- // when the tree is not expended
- // viewer.expandToLevel(2);
- }
-
- /** Import Package Section */
- private void createImportPackageSection(Composite parent)
- throws RepositoryException {
- parent.setLayout(new GridLayout());
-
- // Define the TableViewer
- // toolkit.createLabel(parent, "Import packages", SWT.NONE).setFont(
- // EclipseUiUtils.getBoldFont(parent));
-
- Section section = addSection(parent, "Import packages");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- TableViewer viewer = new TableViewer(section, SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.BORDER);
-
- final Table table = viewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Name
- TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(350);
- col.getColumn().setText("Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -7836022945221936898L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_NAME);
- }
-
- public Image getImage(Object element) {
- return DistImages.IMG_PACKAGE;
- }
-
- });
-
- // Version
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(100);
- col.getColumn().setText("Version");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -8277731617775091641L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_VERSION);
- }
- });
-
- // Optional
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(100);
- col.getColumn().setText("Optional");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -2388533169594840688L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_OPTIONAL);
- }
- });
-
- viewer.setContentProvider(new TableContentProvider(
- SlcTypes.SLC_IMPORTED_PACKAGE, SLC_NAME));
- section.setClient(table);
- viewer.setInput("Initialize");
- }
-
- /** Required Bundle Section */
- private void createReqBundleSection(Composite parent)
- throws RepositoryException {
- parent.setLayout(new GridLayout());
-
- // Define the TableViewer
- Section section = addSection(parent, "Required bundles");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // toolkit.createLabel(parent, "Required bundles", SWT.NONE).setFont(
- // EclipseUiUtils.getBoldFont(parent));
- TableViewer viewer = new TableViewer(section, SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.BORDER);
-
- final Table table = viewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Name
- TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(300);
- col.getColumn().setText("Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 4423640365819800247L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_SYMBOLIC_NAME);
- }
-
- @Override
- public Image getImage(Object element) {
- return DistImages.IMG_BUNDLE;
- }
- });
-
- // Version
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(140);
- col.getColumn().setText("Version");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 1898477425996646270L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_BUNDLE_VERSION);
- }
- });
-
- // Optional
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(100);
- col.getColumn().setText("Optional");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -7029999152302445581L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_OPTIONAL);
- }
- });
-
- viewer.setContentProvider(new TableContentProvider(
- SlcTypes.SLC_REQUIRED_BUNDLE, SLC_SYMBOLIC_NAME));
- section.setClient(table);
- viewer.setInput("Initialize");
- }
-
- /**
- * Build repository request
- *
- * FIXME Workaround for remote repository, the path to bundleartifact (for
- * instance
- * .../org/argeo/slc/org.argeo.slc.client.ui.dist/1.1.12/org.argeo.slc
- * .client.ui.dist-1.1.12/ ) is not valid for method factory.childNode(); it
- * fails parsing the "1.1.12" part, trying to cast it as a BigDecimal
- *
- * */
- private NodeIterator listNodes(Node parent, String nodeType, String orderBy)
- throws RepositoryException {
- // QueryManager queryManager = currBundle.getSession().getWorkspace()
- // .getQueryManager();
- // QueryObjectModelFactory factory = queryManager.getQOMFactory();
- //
- // final String nodeSelector = "nodes";
- // Selector source = factory.selector(nodeType, nodeSelector);
- //
- // Constraint childOf = factory.childNode(nodeSelector,
- // parent.getPath());
- //
- // Ordering order =
- // factory.ascending(factory.propertyValue(nodeSelector,
- // orderBy));
- // Ordering[] orderings = { order };
- //
- // QueryObjectModel query = factory.createQuery(source, childOf,
- // orderings, null);
- //
- // QueryResult result = query.execute();
-
- String pattern = null;
- if (SlcTypes.SLC_EXPORTED_PACKAGE.equals(nodeType))
- pattern = "slc:Export-Package*";
- else if (SlcTypes.SLC_JAVA_PACKAGE.equals(nodeType))
- pattern = "slc:uses*";
- else if (SlcTypes.SLC_IMPORTED_PACKAGE.equals(nodeType))
- pattern = "slc:Import-Package*";
- else if (SlcTypes.SLC_REQUIRED_BUNDLE.equals(nodeType))
- pattern = "slc:Require-Bundle*";
-
- return parent.getNodes(pattern);
- }
-
- private class TableContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = 4133284637336320455L;
- private String nodeType;
- private String orderBy;
-
- TableContentProvider(String nodeType, String orderBy) {
- this.nodeType = nodeType;
- this.orderBy = orderBy;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public Object[] getElements(Object arg0) {
- try {
- List<Node> nodes = JcrUtils.nodeIteratorToList(listNodes(
- currBundle, nodeType, orderBy));
- return nodes.toArray();
- } catch (RepositoryException e) {
- ErrorFeedback.show("Cannot list children Nodes", e);
- return null;
- }
- }
- }
-
- /* HELPERS */
- private Section addSection(Composite parent, String title) {
- Section section = toolkit.createSection(parent, Section.TITLE_BAR);
- section.setText(title);
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return section;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.net.URL;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.build.License;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.utils.HyperlinkAdapter;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Hyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-
-/** Show details for a given bundle. */
-public class BundleDetailPage extends FormPage implements SlcNames {
- private final static CmsLog log = CmsLog.getLog(BundleDetailPage.class);
-
- final static String PAGE_ID = "BundleDetailPage";
-
- // Business Objects
- private Node bundle;
-
- // This page widgets
- private FormToolkit tk;
-
- public BundleDetailPage(FormEditor formEditor, String title, Node bundle) {
- super(formEditor, PAGE_ID, title);
- this.bundle = bundle;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- // General settings for this page
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
- Composite body = form.getBody();
-
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = 5;
- layout.marginRight = 15;
- layout.verticalSpacing = 0;
- body.setLayout(layout);
- try {
- form.setText(bundle.hasProperty(SlcNames.SLC_SYMBOLIC_NAME) ? bundle
- .getProperty(SlcNames.SLC_SYMBOLIC_NAME).getString() : "");
- form.setMessage(bundle
- .hasProperty(DistConstants.SLC_BUNDLE_DESCRIPTION) ? bundle
- .getProperty(DistConstants.SLC_BUNDLE_DESCRIPTION)
- .getString() : "", IMessageProvider.NONE);
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get bundle name for node "
- + bundle, re);
- }
-
- // Main layout
- Composite header = tk.createComposite(body);
- header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- populateHeaderPart(header);
-
- Composite mavenSnipet = tk.createComposite(body);
- mavenSnipet.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- populateMavenSnippetPart(mavenSnipet);
- }
-
- private void populateHeaderPart(Composite parent) {
- GridLayout layout = new GridLayout(6, false);
- // layout.marginWidth = layout.horizontalSpacing = layout.marginHeight =
- // 0;
- layout.horizontalSpacing = 10;
- parent.setLayout(layout);
- try {
- // 1st Line: Category, name version
- createLT(parent, "Category",
- bundle.hasProperty(SlcNames.SLC_GROUP_ID) ? bundle
- .getProperty(SlcNames.SLC_GROUP_ID).getString()
- : "");
- createLT(parent, "Name",
- bundle.hasProperty(SlcNames.SLC_ARTIFACT_ID) ? bundle
- .getProperty(SlcNames.SLC_ARTIFACT_ID).getString()
- : "");
- createLT(parent, "Version",
- bundle.hasProperty(SlcNames.SLC_ARTIFACT_VERSION) ? bundle
- .getProperty(SlcNames.SLC_ARTIFACT_VERSION)
- .getString() : "");
-
- // 3rd Line: Vendor, licence, sources
- createLT(
- parent,
- "Vendor",
- bundle.hasProperty(DistConstants.SLC_BUNDLE_VENDOR) ? bundle
- .getProperty(DistConstants.SLC_BUNDLE_VENDOR)
- .getString() : "N/A");
-
- createLicencesLink(parent, "Licence",
- DistConstants.SLC_BUNDLE_LICENCE);
- addSourceLink(parent);
-
- // 2nd Line: The Jar itself and the Manifest
- createJarLink(parent);
- createManifestLink(parent);
-
- // Last line
- createPomLink(parent);
-
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get bundle name for node "
- + bundle, re);
- }
-
- }
-
- private void populateMavenSnippetPart(Composite parent) {
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = layout.horizontalSpacing = layout.horizontalSpacing = layout.marginHeight = 0;
- parent.setLayout(layout);
-
- Section section = tk.createSection(parent, Section.TITLE_BAR
- | Section.DESCRIPTION);
- section.setText("Maven");
- section.setDescription("Add the below tag to your Artifact pom dependencies");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Text snippetTxt = createMavenSnippet(section);
- section.setClient(snippetTxt);
- }
-
- // /////////////////////
- // HELPERS
-
- private Text createLT(Composite parent, String labelValue, String textValue) {
- Label label = tk.createLabel(parent, labelValue, SWT.RIGHT);
- // label.setFont(EclipseUiUtils.getBoldFont(parent));
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- // Add a trailing space to workaround a display glitch in RAP 1.3
- Text text = new Text(parent, SWT.LEFT);
- text.setText(textValue + " ");
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- text.setEditable(false);
- return text;
- }
-
- private void createLicencesLink(Composite parent, String label,
- String jcrPropName) throws RepositoryException {
- tk.createLabel(parent, label, SWT.NONE);
- if (bundle.hasProperty(jcrPropName)) {
-
- String licenceLinkVal = bundle.getProperty(jcrPropName).getString();
-
- // FIXME Hack until license generation is done cleanly
- // Problem is with description that contains a "," like
- // "Apache License, Version 2"
- String[] licenceVals;
- if (licenceLinkVal.contains("description="))
- licenceVals = new String[] { licenceLinkVal };
- else
- // multiple license, form non-regenerated manifests
- licenceVals = licenceLinkVal.split(", ");
-
- Composite body = tk.createComposite(parent);
- body.setLayout(new RowLayout(SWT.WRAP));
-
- for (final String value : licenceVals) {
- final License currLicense = parseLicenseString(value);
-
- Hyperlink link = tk.createHyperlink(body,
- currLicense.getName(), SWT.NONE);
- link.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- try {
- IWorkbenchBrowserSupport browserSupport = PlatformUI
- .getWorkbench().getBrowserSupport();
- IWebBrowser browser = browserSupport
- .createBrowser(
- IWorkbenchBrowserSupport.LOCATION_BAR
- | IWorkbenchBrowserSupport.NAVIGATION_BAR,
- "SLC Distribution browser",
- "SLC Distribution browser",
- "A tool tip");
- browser.openURL(new URL(currLicense.getUri()));
- } catch (Exception ex) {
- throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- }
- }
- });
- }
- } else
- tk.createLabel(parent, "N/A", SWT.NONE);
- }
-
- // TODO this must be moved to a better place once the standard has been
- // defined
- // Enable licence encoding in a single JCR Value
- private final static String LICENSE_SEPARATOR = ";";
- // The human readable name of the licence
- private final static String LICENSE_NAME = "description";
- // A link on the internet with some more info on this licence
- private final static String LICENSE_LINK = "link";
-
- private License parseLicenseString(String licenseStr) {
- String uri = null, name = null, link = null, text = null;
- // TODO enhance this
- String[] values = licenseStr.split(LICENSE_SEPARATOR);
- for (String value : values) {
- if (value.startsWith(LICENSE_NAME))
- name = value.substring(LICENSE_NAME.length() + 1); // +1 for the
- // '='
- else if (value.startsWith(LICENSE_LINK))
- link = value.substring(LICENSE_LINK.length() + 1);
- else if (uri == null)
- uri = value;
- // TODO manage text
- }
- return new SimpleLicense(name, uri, link, text);
- }
-
- class SimpleLicense implements License {
- private final String name;
- private final String uri;
- private final String link;
- private final String text;
-
- public SimpleLicense(String name, String uri, String link, String text) {
- if (uri == null)
- throw new SlcException(
- "Cannot manage a licence with a null URI ");
- this.uri = uri;
-
- this.name = name;
- this.link = link;
- this.text = text;
- }
-
- public String getUri() {
- return uri;
- }
-
- public String getText() {
- return text;
- }
-
- public String getName() {
- return name != null ? name : uri;
- }
-
- public String getLink() {
- return link;
- }
- }
-
- private void createJarLink(Composite parent) throws RepositoryException {
- Label label = tk.createLabel(parent, "Jar", SWT.RIGHT);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
-
- Composite body = tk.createComposite(parent);
- RowLayout rl = new RowLayout(SWT.HORIZONTAL);
- rl.spacing = 6;
- body.setLayout(rl);
- body.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
-
- Hyperlink jarLink = tk
- .createHyperlink(body, bundle.getName(), SWT.NONE);
- jarLink.addHyperlinkListener(new OpenFileLinkListener(bundle.getPath()));
-
- // Corresponding check sums
-
- String name = bundle.getName() + ".md5";
- if (bundle.getParent().hasNode(name)) {
- Node md5 = bundle.getParent().getNode(name);
- Hyperlink md5Link = tk.createHyperlink(body, "MD5", SWT.NONE);
- md5Link.addHyperlinkListener(new OpenFileLinkListener(md5.getPath()));
- }
-
- name = bundle.getName() + ".sha1";
- if (bundle.getParent().hasNode(name)) {
- Node sha1 = bundle.getParent().getNode(name);
- Hyperlink sha1Link = tk.createHyperlink(body, "SHA1", SWT.NONE);
- sha1Link.addHyperlinkListener(new OpenFileLinkListener(sha1
- .getPath()));
- }
- }
-
- private void createPomLink(Composite parent) throws RepositoryException {
- Label label = tk.createLabel(parent, "Pom", SWT.RIGHT);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
-
- String name = bundle.getName().substring(0,
- bundle.getName().length() - "jar".length())
- + "pom";
-
- if (bundle.getParent().hasNode(name)) {
- Node pom = bundle.getParent().getNode(name);
-
- Composite body = tk.createComposite(parent);
- RowLayout rl = new RowLayout(SWT.HORIZONTAL);
- rl.spacing = 6;
- body.setLayout(rl);
- body.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 3, 1));
-
- Hyperlink pomLink = tk.createHyperlink(body, "pom.xml", SWT.NONE);
- pomLink.addHyperlinkListener(new OpenFileLinkListener(pom.getPath()));
-
- // Corresponding check sums
- name = pom.getName() + ".md5";
- if (pom.getParent().hasNode(name)) {
- Node md5 = pom.getParent().getNode(name);
- Hyperlink md5Link = tk.createHyperlink(body, "MD5", SWT.NONE);
- md5Link.addHyperlinkListener(new OpenFileLinkListener(md5
- .getPath()));
- }
-
- name = pom.getName() + ".sha1";
- if (pom.getParent().hasNode(name)) {
- Node sha1 = pom.getParent().getNode(name);
- Hyperlink sha1Link = tk.createHyperlink(body, "SHA1", SWT.NONE);
- sha1Link.addHyperlinkListener(new OpenFileLinkListener(sha1
- .getPath()));
- }
- } else
- tk.createLabel(parent, "N/A", SWT.NONE);
- }
-
- private void createManifestLink(Composite parent)
- throws RepositoryException {
- tk.createLabel(parent, "Manifest", SWT.NONE);
- // Hyperlink link =
- // TODO fix this when file download has been implemented for the
- // manifest
- tk.createHyperlink(parent, "MANIFEST.MF", SWT.NONE);
- // link.addHyperlinkListener(new
- // OpenFileLinkListener(bundle.getPath()));
- }
-
- // private void createHyperlink(Composite parent, String label,
- // String jcrPropName) throws RepositoryException {
- // tk.createLabel(parent, label, SWT.NONE);
- // if (bundle.hasProperty(jcrPropName)) {
- // final Hyperlink link = tk.createHyperlink(parent, bundle
- // .getProperty(jcrPropName).getString(), SWT.NONE);
- // link.addHyperlinkListener(new AbstractHyperlinkListener() {
- // @Override
- // public void linkActivated(HyperlinkEvent e) {
- // try {
- // IWorkbenchBrowserSupport browserSupport = PlatformUI
- // .getWorkbench().getBrowserSupport();
- // IWebBrowser browser = browserSupport
- // .createBrowser(
- // IWorkbenchBrowserSupport.LOCATION_BAR
- // | IWorkbenchBrowserSupport.NAVIGATION_BAR,
- // "SLC Distribution browser",
- // "SLC Distribution browser",
- // "A tool tip");
- // browser.openURL(new URL(link.getText()));
- // } catch (Exception ex) {
- // throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- // }
- // }
- // });
- // } else
- // tk.createLabel(parent, "N/A", SWT.NONE);
- // }
-
- // helper to check if sources are available
- private void addSourceLink(Composite parent) {
- try {
- String srcPath = RepoUtils.relatedPdeSourcePath(
- RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH, bundle);
- if (!bundle.getSession().nodeExists(srcPath)) {
- createLT(parent, "Sources", "N/A");
- } else {
- final Node sourcesNode = bundle.getSession().getNode(srcPath);
-
- String srcName = null;
- if (sourcesNode.hasProperty(SlcNames.SLC_SYMBOLIC_NAME))
- srcName = sourcesNode.getProperty(
- SlcNames.SLC_SYMBOLIC_NAME).getString();
- else
- srcName = sourcesNode.getName();
- Label label = tk.createLabel(parent, "Sources", SWT.RIGHT);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
- false));
- final Hyperlink link = tk.createHyperlink(parent, srcName,
- SWT.NONE);
- link.addHyperlinkListener(new OpenFileLinkListener(sourcesNode
- .getPath()));
-
- // {
- // @Override
- // public void linkActivated(HyperlinkEvent e) {
- // try {
- // ModuleEditorInput editorInput = (ModuleEditorInput)
- // getEditorInput();
- // Map<String, String> params = new HashMap<String, String>();
- // params.put(OpenJcrFile.PARAM_REPO_NODE_PATH,
- // editorInput.getRepoNodePath());
- // params.put(OpenJcrFile.PARAM_REPO_URI,
- // editorInput.getUri());
- // params.put(OpenJcrFile.PARAM_WORKSPACE_NAME,
- // editorInput.getWorkspaceName());
- // params.put(OpenJcrFile.PARAM_FILE_PATH,
- // );
- // CommandUtils.callCommand(OpenJcrFile.ID, params);
- // } catch (Exception ex) {
- // throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- // }
- // }
- // });
-
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unable to configure sources link for "
- + bundle, e);
- }
- }
-
- private class OpenFileLinkListener extends HyperlinkAdapter {
- final private String path;
-
- public OpenFileLinkListener(String path) {
- this.path = path;
- }
-
- @Override
- public void linkActivated(HyperlinkEvent e) {
- log.warn("File download must be implemented. Cannot provide access to "
- + path);
-
- // try {
- // ModuleEditorInput editorInput = (ModuleEditorInput)
- // getEditorInput();
- // Map<String, String> params = new HashMap<String, String>();
- // params.put(OpenJcrFile.PARAM_REPO_NODE_PATH,
- // editorInput.getRepoNodePath());
- // params.put(OpenJcrFile.PARAM_REPO_URI, editorInput.getUri());
- // params.put(OpenJcrFile.PARAM_WORKSPACE_NAME,
- // editorInput.getWorkspaceName());
- // params.put(OpenJcrFile.PARAM_FILE_PATH, path);
- //
- // String cmdId = (new OpenJcrFileCmdId()).getCmdId();
- // if (log.isTraceEnabled())
- // log.debug("Retrieved openFile Cmd ID: " + cmdId);
- // CommandUtils.callCommand(cmdId, params);
- // } catch (Exception ex) {
- // throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- // }
- }
- }
-
- /** Creates a text area with corresponding maven snippet */
- private Text createMavenSnippet(Composite parent) {
- Text mavenSnippet = new Text(parent, SWT.MULTI | SWT.WRAP);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- gd.heightHint = 100;
- mavenSnippet.setLayoutData(gd);
- mavenSnippet.setText(generateXmlSnippet());
- return mavenSnippet;
- }
-
- private String generateXmlSnippet() {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("<dependency>\n");
- sb.append("\t<groupId>");
- sb.append(bundle.getProperty(SLC_GROUP_ID).getString());
- sb.append("</groupId>\n");
- sb.append("\t<artifactId>");
- sb.append(bundle.getProperty(SLC_ARTIFACT_ID).getString());
- sb.append("</artifactId>\n");
- sb.append("\t<version>");
- sb.append(bundle.getProperty(SLC_ARTIFACT_VERSION).getString());
- sb.append("</version>\n");
- sb.append("</dependency>");
- return sb.toString();
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while generating maven snippet");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.utils.DistUiHelpers;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/** List all properties of current bundle as a tree */
-public class BundleRawPage extends FormPage implements SlcNames, SlcTypes {
- // private final static Log log =
- // LogFactory.getLog(ArtifactDetailsPage.class);
-
- // Main business Objects
- private Node currBundle;
-
- // This page widgets
- private TreeViewer complexTree;
-
- public BundleRawPage(FormEditor editor, String title, Node currentNode) {
- super(editor, "id", title);
- this.currBundle = currentNode;
- }
-
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = 5;
- form.getBody().setLayout(layout);
- createViewer(form.getBody());
- }
-
- private void createViewer(Composite parent) {
-
- // Create the viewer
- int style = SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION;
- Tree tree = new Tree(parent, style);
- GridData gd = new GridData(GridData.FILL_BOTH);
- gd.grabExcessHorizontalSpace = true;
- gd.grabExcessVerticalSpace = true;
- tree.setLayoutData(gd);
- createColumn(tree, "Attribute", SWT.LEFT, 200);
- createColumn(tree, "Value", SWT.LEFT, 200);
- tree.setLinesVisible(true);
- tree.setHeaderVisible(true);
-
- complexTree = new TreeViewer(tree);
- complexTree.setContentProvider(new TreeContentProvider());
- complexTree.setLabelProvider(new TreeLabelProvider());
-
- // Initialize
- complexTree.setInput(currBundle);
- // result.expandAll();
- complexTree.expandToLevel(2);
-
- }
-
- private static TreeColumn createColumn(Tree parent, String name, int style,
- int width) {
- TreeColumn result = new TreeColumn(parent, style);
- result.setText(name);
- result.setWidth(width);
- result.setMoveable(true);
- result.setResizable(true);
- return result;
- }
-
- // View specific object
- private class ViewSpecificItems {
- private String key;
- private Object value;
- private boolean isFolder;
- private Node curNode;
-
- public ViewSpecificItems(String key, Object value, boolean isFolder) {
- this.key = key;
- this.value = value;
- this.isFolder = isFolder;
- }
-
- public String getKey() {
- return key;
- }
-
- public void setNode(Node node) {
- this.curNode = node;
- }
-
- public Node getNode() {
- return curNode;
- }
-
- public Object getValue() {
- return value;
- }
-
- public boolean isFolder() {
- return isFolder;
- }
-
- }
-
- // providers
- private class TreeLabelProvider extends ColumnLabelProvider implements
- SlcTypes, SlcNames {
- private static final long serialVersionUID = -6385445983392621937L;
-
- public void update(ViewerCell cell) {
- try {
-
- int colIndex = cell.getColumnIndex();
- Object element = cell.getElement();
- if (element instanceof Property) {
- Property prop = (Property) element;
- if (colIndex == 0)
- cell.setText(DistUiHelpers.getLabelJcrName(prop
- .getName()));
- else if (colIndex == 1)
- cell.setText(DistUiHelpers.formatValueAsString(prop
- .getValue()));
-
- } else if (element instanceof ViewSpecificItems) {
- if (colIndex == 0)
- cell.setText(((ViewSpecificItems) element).getKey());
- else if (colIndex == 1)
- cell.setText(DistUiHelpers
- .formatAsString(((ViewSpecificItems) element)
- .getValue()));
-
- } else if (element instanceof Node) {
- Node node = (Node) element;
- if (colIndex == 0) {
- if (node.isNodeType(NodeType.NT_FILE)) {
- cell.setImage(DistImages.IMG_FILE);
- cell.setText(node.getName());
- } else if (node.isNodeType(SLC_IMPORTED_PACKAGE))
- cell.setText("Import package");
- else if (node.isNodeType(SLC_EXPORTED_PACKAGE))
- cell.setText("Export package");
-
- } else if (colIndex == 1) {
- if (node.isNodeType(SLC_ARTIFACT)) {
- StringBuffer sb = new StringBuffer("");
- if (node.hasProperty(SLC_ARTIFACT_CLASSIFIER)) {
- sb.append(node.getProperty(
- SLC_ARTIFACT_CLASSIFIER).getString());
- sb.append(" ");
- }
- if (node.hasProperty(SLC_ARTIFACT_EXTENSION))
- sb.append(node.getProperty(
- SLC_ARTIFACT_EXTENSION).getString());
- cell.setText(sb.toString());
- } else if (node.isNodeType(SLC_IMPORTED_PACKAGE)
- || node.isNodeType(SLC_EXPORTED_PACKAGE))
- cell.setText(node.getProperty(SLC_NAME).getString());
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "unexpected error while getting artifact information",
- e);
- }
- }
- }
-
- private class TreeContentProvider implements ITreeContentProvider {
- private static final long serialVersionUID = -4315686158836938052L;
-
- public Object[] getElements(Object parent) {
- List<Object> elements = new ArrayList<Object>();
-
- try {
- Node node = (Node) parent;
- elements = new ArrayList<Object>();
-
- // Maven coordinates
-// elements.add(node.getProperty(SLC_GROUP_ID));
-// elements.add(node.getProperty(SLC_ARTIFACT_ID));
-// elements.add(node.getProperty(SLC_ARTIFACT_VERSION));
-
- // Meta information
- // boolean gotSource = false;
- // // TODO: implement this check
- // elements.add(new ViewSpecificItems("Sources available",
- // gotSource));
-
- // Jars
- NodeIterator ni = node.getNodes();
- while (ni.hasNext()) {
- Node child = ni.nextNode();
- if (child.isNodeType(SLC_ARTIFACT)) {
- // we skip sha1 files for the time being.
- elements.add(child);
- }
- }
-
- // Properties
- PropertyIterator pi = node.getProperties();
- while (pi.hasNext()) {
- Property curProp = pi.nextProperty();
- if (!curProp.getName().startsWith("jcr:")
- && !curProp.isMultiple())
- elements.add(curProp);
- }
-
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while listing node properties", e);
- }
- return elements.toArray();
- }
-
- public Object getParent(Object child) {
- return null;
- }
-
- public Object[] getChildren(Object parent) {
- Object[] result = null;
- try {
- if (parent instanceof Property) {
- Property prop = (Property) parent;
- if (prop.isMultiple()) {
- Value[] values = prop.getValues();
- return values;
- }
- } else if (parent instanceof Node) {
- Node node = (Node) parent;
- if (node.hasNodes()) {
- List<Object> elements = new ArrayList<Object>();
- PropertyIterator pi = node.getProperties();
- while (pi.hasNext()) {
- Property curProp = pi.nextProperty();
- if (!curProp.getName().startsWith("jcr:")
- && !curProp.isMultiple())
- elements.add(curProp);
- }
-
- NodeIterator ni = node.getNodes();
- while (ni.hasNext()) {
- Node curNode = ni.nextNode();
- if (curNode.isNodeType(SLC_IMPORTED_PACKAGE)
- || curNode.isNodeType(SLC_EXPORTED_PACKAGE)) {
- ViewSpecificItems vsi = new ViewSpecificItems(
- "Bundle dependencies", "", true);
- vsi.setNode(node);
- elements.add(vsi);
- break;
- }
- }
- return elements.toArray();
- }
- } else if (parent instanceof ViewSpecificItems
- && ((ViewSpecificItems) parent).isFolder()) {
- NodeIterator ni = ((ViewSpecificItems) parent).getNode()
- .getNodes();
- List<Node> elements = new ArrayList<Node>();
- while (ni.hasNext()) {
- Node curNode = ni.nextNode();
- if (curNode.isNodeType(SLC_IMPORTED_PACKAGE)
- || curNode.isNodeType(SLC_EXPORTED_PACKAGE)) {
- elements.add(curNode);
- }
- }
- return elements.toArray();
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected error getting multiple values property.", e);
- }
- return result;
- }
-
- public boolean hasChildren(Object parent) {
- try {
- if (parent instanceof Property
- && ((Property) parent).isMultiple()) {
- return true;
- } else if (parent instanceof Node && ((Node) parent).hasNodes()
- && ((Node) parent).isNodeType(SLC_BUNDLE_ARTIFACT)) {
- return true;
- } else if (parent instanceof ViewSpecificItems
- && ((ViewSpecificItems) parent).isFolder()) {
- return true;
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while checking if property is multiple",
- e);
- }
- return false;
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public void dispose() {
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-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.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.commands.OpenModuleEditor;
-import org.argeo.slc.repo.RepoConstants;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Expose Maven artifacts of a given workspace as a tree. Artifacts are grouped
- * by Maven group.
- */
-public class DistWkspBrowserPage extends FormPage implements DistConstants,
- RepoConstants {
- // private final static CmsLog log = CmsLog
- // .getLog(ArtifactsBrowserPage.class);
-
- final static String PAGE_ID = "artifactsBrowserPage";
-
- // Business object
- private Session session;
-
- // This page widgets
- private TreeViewer artifactTreeViewer;
-
- public DistWkspBrowserPage(FormEditor editor, String title, Session session) {
- super(editor, PAGE_ID, title);
- this.session = session;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- try {
- ScrolledForm form = managedForm.getForm();
- Composite parent = form.getBody();
- parent.setLayout(new FillLayout());
- createMavenBrowserPart(parent);
- getEditor().getSite().setSelectionProvider(artifactTreeViewer);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot create artifact browser page", e);
- }
- }
-
- /** Aether specific browser for the current workspace */
- private void createMavenBrowserPart(Composite parent)
- throws RepositoryException {
-
- int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.FULL_SELECTION | SWT.BORDER;
-
- Tree tree = new Tree(parent, style);
- createColumn(tree, "Maven browser", SWT.LEFT, 450);
- tree.setLinesVisible(true);
- tree.setHeaderVisible(true);
-
- artifactTreeViewer = new TreeViewer(tree);
-
- artifactTreeViewer.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 2648269889876058461L;
-
- @Override
- public String getText(Object element) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SlcTypes.SLC_GROUP_BASE))
- return JcrUtils.get((Node) element,
- SlcNames.SLC_GROUP_BASE_ID);
- else if (node.isNodeType(SlcTypes.SLC_ARTIFACT_BASE))
- return JcrUtils.get((Node) element,
- SlcNames.SLC_ARTIFACT_ID);
- else
- return node.getName();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot browse artifacts", e);
- }
- }
-
- @Override
- public Image getImage(Object element) {
- Node node = (Node) element;
- try {
-
- if (node.isNodeType(SlcTypes.SLC_GROUP_BASE))
- return DistImages.IMG_GROUP_BASE;
- else if (node.isNodeType(SlcTypes.SLC_ARTIFACT_BASE))
- return DistImages.IMG_ARTIFACT_BASE;
- else if (node
- .isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE))
- return DistImages.IMG_ARTIFACT_VERSION_BASE;
- else
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get images for artifacts", e);
- }
- }
- });
-
- artifactTreeViewer.setContentProvider(new ITreeContentProvider() {
- private static final long serialVersionUID = -2381555428857519326L;
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- }
-
- public Object[] getElements(Object inputElement) {
- try {
- List<Node> nodes = JcrUtils.nodeIteratorToList(listNodes(
- SlcTypes.SLC_GROUP_BASE, SlcNames.SLC_NAME));
- return nodes.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list children Nodes", e);
- }
- }
-
- public Object[] getChildren(Object parentElement) {
- // Only 3 levels for the time being
- try {
- Node pNode = (Node) parentElement;
- if (pNode.isNodeType(SlcTypes.SLC_GROUP_BASE)) {
- return getArtifactBase(pNode,
- SlcTypes.SLC_ARTIFACT_BASE);
- } else if (pNode.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
- return getArtifactBase(pNode,
- SlcTypes.SLC_ARTIFACT_VERSION_BASE);
- }
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list children Nodes", e);
- }
- }
-
- // Helper to get children because current version of Jackrabbit is
- // buggy in remote
- private Object[] getArtifactBase(Node parent, String nodeType)
- throws RepositoryException {
- List<Node> nodes = new ArrayList<Node>();
- NodeIterator ni = parent.getNodes();
- while (ni.hasNext()) {
- Node node = ni.nextNode();
- if (node.isNodeType(nodeType))
- nodes.add(node);
- }
- return nodes.toArray();
- }
-
- public Object getParent(Object element) {
- return null;
- }
-
- public boolean hasChildren(Object element) {
- try {
- Node pNode = (Node) element;
- if (pNode.isNodeType(SlcTypes.SLC_GROUP_BASE)
- || pNode.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
- // might return true even if there is no "valid" child
- return pNode.hasNodes();
- } else
- return false;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot check children Nodes", e);
- }
- }
- });
-
- artifactTreeViewer.addDoubleClickListener(new DoubleClickListener());
-
- artifactTreeViewer.setInput("Initialize");
- }
-
- private class DoubleClickListener implements IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- Object obj = ((IStructuredSelection) event.getSelection())
- .getFirstElement();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- try {
- if (node.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
- NodeIterator nit = node.getNodes();
- while (nit.hasNext()) {
- Node curr = nit.nextNode();
- if (curr.isNodeType(SlcTypes.SLC_ARTIFACT)) {
- node = curr;
- break;
- }
- }
- }
-
- if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
- DistWkspEditorInput dwip = (DistWkspEditorInput) getEditorInput();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenModuleEditor.PARAM_REPO_NODE_PATH,
- dwip.getRepoNodePath());
- params.put(OpenModuleEditor.PARAM_REPO_URI,
- dwip.getUri());
- params.put(OpenModuleEditor.PARAM_WORKSPACE_NAME,
- dwip.getWorkspaceName());
- String path = node.getPath();
- params.put(OpenModuleEditor.PARAM_MODULE_PATH, path);
- CommandUtils.callCommand(OpenModuleEditor.ID, params);
- }
- } catch (RepositoryException re) {
- throw new SlcException("Cannot get path for node " + node
- + " while setting parameters for "
- + "command OpenModuleEditor", re);
- }
-
- }
- }
- }
-
- private static TreeColumn createColumn(Tree parent, String name, int style,
- int width) {
- TreeColumn result = new TreeColumn(parent, style);
- result.setText(name);
- result.setWidth(width);
- result.setMoveable(true);
- result.setResizable(true);
- return result;
- }
-
- private NodeIterator listNodes(String nodeType, String orderBy)
- throws RepositoryException {
- QueryManager queryManager = session.getWorkspace().getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
-
- final String nodeSelector = "nodes";
- Selector source = factory.selector(nodeType, nodeSelector);
-
- Ordering order = factory.ascending(factory.propertyValue(nodeSelector,
- orderBy));
- Ordering[] orderings = { order };
-
- QueryObjectModel query = factory.createQuery(source, null, orderings,
- null);
-
- QueryResult result = query.execute();
-
- return result.getNodes();
- }
-
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/** An editor input pointing to a distribution workspace */
-public class DistWkspEditorInput implements IEditorInput, SlcNames {
-
- // Injected
- // private RepositoryFactory repositoryFactory;
- // private Keyring keyring;
- // private Node repoNode;
- private String repoNodePath;
- private String uri;
-
- // Local variables
- private String workspaceName;
-
- // public WorkspaceEditorInput(RepositoryFactory repositoryFactory,
- // Keyring keyring, Repository localRepository, Node repoNode,
- // String uri) {
- // // this.repositoryFactory = repositoryFactory;
- // // this.keyring = keyring;
- // this.localRepository = localRepository;
- // // this.repoNode= repoNode;
- // this.uri = uri;
- //
- // }
-
- /** uri and workspace name cannot be null */
- public DistWkspEditorInput(String repoNodePath, String uri,
- String workspaceName) {
- if (workspaceName == null)
- throw new SlcException("Workspace name cannot be null");
- if (uri == null)
- throw new SlcException("URI for repository cannot be null");
- this.repoNodePath = repoNodePath;
- this.workspaceName = workspaceName;
- this.uri = uri;
- }
-
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- // Dummy compulsory methods
- public String getToolTipText() {
- return "Editor for workspace " + workspaceName
- + " in repository of URI " + uri;
- }
-
- public String getName() {
- return workspaceName + "@" + uri;
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (!(obj instanceof DistWkspEditorInput))
- return false;
-
- DistWkspEditorInput other = (DistWkspEditorInput) obj;
-
- if (!workspaceName.equals(other.getWorkspaceName()))
- return false;
- if (!uri.equals(other.getUri()))
- return false;
-
- if (repoNodePath == null)
- return other.getRepoNodePath() == null;
- else
- return repoNodePath.equals(other.getRepoNodePath());
- }
-
- public String getUri() {
- return uri;
- }
-
- public String getWorkspaceName() {
- return workspaceName;
- }
-
- public String getRepoNodePath() {
- return repoNodePath;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.PropertyType;
-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.Constraint;
-import javax.jcr.query.qom.DynamicOperand;
-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 javax.jcr.query.qom.StaticOperand;
-
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.cms.ui.workbench.util.PrivilegedJob;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.commands.DeleteArtifacts;
-import org.argeo.slc.client.ui.dist.commands.OpenModuleEditor;
-import org.argeo.slc.client.ui.dist.utils.DistNodeViewerComparator;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-
-/** Show all bundles contained in a given workspace as filter-able table */
-public class DistWkspSearchPage extends FormPage implements SlcNames {
- // final private static CmsLog log = CmsLog
- // .getLog(DistributionOverviewPage.class);
-
- final static String PAGE_ID = "distributionOverviewPage";
-
- // Business Objects
- private Session session;
-
- // This page widgets
- private DistWorkspaceEditor formEditor;
- private FormToolkit tk;
-
- private DistNodeViewerComparator comparator;
- private TableViewer viewer;
-
- // private Composite header;
- private Text artifactTxt;
- private final static String FILTER_HELP_MSG = "Filter criterion, separated by a space";
-
- public DistWkspSearchPage(DistWorkspaceEditor formEditor, String title,
- Session session) {
- super(formEditor, PAGE_ID, title);
- this.formEditor = formEditor;
- this.session = session;
- }
-
- private void asynchronousRefresh() {
- RefreshJob job = new RefreshJob(artifactTxt.getText(), viewer,
- getSite().getShell().getDisplay());
- job.setUser(true);
- job.schedule();
- }
-
- private class RefreshJob extends PrivilegedJob {
- private TableViewer viewer;
- private String filter;
- private Display display;
-
- public RefreshJob(String filter, TableViewer viewer, Display display) {
- super("Get bundle list");
- this.filter = filter;
- this.viewer = viewer;
- this.display = display;
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- try {
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- monitor.beginTask("Getting bundle list", -1);
- final List<Node> result = JcrUtils
- .nodeIteratorToList(listBundleArtifacts(session, filter));
-
- display.asyncExec(new Runnable() {
- public void run() {
- viewer.setInput(result);
- }
- });
- } catch (Exception e) {
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID,
- "Cannot get bundle list", e);
- }
- return Status.OK_STATUS;
- }
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
-
- // Main Layout
- GridLayout layout = new GridLayout(1, false);
- Composite body = form.getBody();
- body.setLayout(layout);
-
- // Meta info about current workspace
- Composite header = tk.createComposite(body);
- header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- createHeaderPart(form, header);
-
- Composite modules = tk.createComposite(body);
- modules.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- populateModuleSection(modules);
- }
-
- private void createHeaderPart(ScrolledForm form, Composite parent) {
- GridLayout layout = new GridLayout(4, false);
- // layout.marginWidth = layout.marginHeight = layout.verticalSpacing =
- // 0;
- // layout.horizontalSpacing = 2;
- parent.setLayout(layout);
-
- String wkspName = ((DistWkspEditorInput) getEditorInput())
- .getWorkspaceName();
- wkspName = wkspName.replaceAll("-", " ");
- form.setText(wkspName);
-
- String repoAlias = "";
- Node repoNode = ((DistWorkspaceEditor) getEditor()).getRepoNode();
- if (repoNode != null)
- try {
- repoAlias = repoNode.isNodeType(NodeType.MIX_TITLE) ? repoNode
- .getProperty(Property.JCR_TITLE).getString() : repoNode
- .getName();
- } catch (RepositoryException e1) {
- throw new SlcException("Unable to get repository alias ", e1);
- }
- else
- repoAlias = " - ";
-
- createLT(parent, "Repository alias", repoAlias);
- createLT(parent, "URI",
- ((DistWkspEditorInput) getEditorInput()).getUri());
- }
-
- private void populateModuleSection(Composite parent) {
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = layout.horizontalSpacing = layout.horizontalSpacing = layout.marginHeight = 0;
- parent.setLayout(layout);
-
- Section section = tk.createSection(parent, Section.TITLE_BAR
- | Section.DESCRIPTION);
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- section.setText("Artifacts");
- section.setDescription("Search among all artifacts that are referenced in the current workspace");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Composite body = tk.createComposite(section);
- layout = new GridLayout(1, false);
- layout.marginWidth = layout.horizontalSpacing = layout.horizontalSpacing = layout.marginHeight = 0;
- body.setLayout(new GridLayout());
-
- // Filter
- Composite filter = tk.createComposite(body);
- filter.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- createFilterPart(filter);
-
- // Table
- Composite tableCmp = tk.createComposite(body);
- tableCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- createTableViewer(tableCmp);
-
- section.setClient(body);
- }
-
- /** Build repository request */
- private NodeIterator listBundleArtifacts(Session session, String filter)
- throws RepositoryException {
- QueryManager queryManager = session.getWorkspace().getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
-
- final String bundleArtifactsSelector = "bundleArtifacts";
- Selector source = factory.selector(SlcTypes.SLC_BUNDLE_ARTIFACT,
- bundleArtifactsSelector);
-
- // Create a dynamic operand for each property on which we want to filter
- DynamicOperand symbNameDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_SYMBOLIC_NAME);
- DynamicOperand versionDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_BUNDLE_VERSION);
- DynamicOperand nameDO = factory.propertyValue(source.getSelectorName(),
- DistConstants.SLC_BUNDLE_NAME);
-
- // Default Constraint: no source artifacts
- Constraint defaultC = factory.not(factory.comparison(
- symbNameDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE,
- factory.literal(session.getValueFactory().createValue(
- "%.source"))));
-
- // Build constraints based the textArea content
- if (filter != null && !"".equals(filter.trim())) {
- // Parse the String
- String[] strs = filter.trim().split(" ");
- for (String token : strs) {
- token = token.replace('*', '%');
- StaticOperand so = factory.literal(session.getValueFactory()
- .createValue("%" + token + "%"));
-
- Constraint currC = factory.comparison(symbNameDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so);
- currC = factory.or(currC, factory.comparison(versionDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so));
- currC = factory.or(currC, factory.comparison(nameDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so));
-
- defaultC = factory.and(defaultC, currC);
- }
- }
-
- Ordering order = factory.descending(factory.propertyValue(
- bundleArtifactsSelector, SlcNames.SLC_BUNDLE_VERSION));
- Ordering order2 = factory.ascending(factory.propertyValue(
- bundleArtifactsSelector, SlcNames.SLC_SYMBOLIC_NAME));
- Ordering[] orderings = { order, order2 };
-
- QueryObjectModel query = factory.createQuery(source, defaultC,
- orderings, null);
-
- QueryResult result = query.execute();
- return result.getNodes();
-
- }
-
- private Text createLT(Composite parent, String labelValue, String textValue) {
- Label label = new Label(parent, SWT.RIGHT);
- label.setText(labelValue);
- // label.setFont(EclipseUiUtils.getBoldFont(parent));
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
-
- // Add a trailing space to workaround a display glitch in RAP 1.3
- Text text = new Text(parent, SWT.LEFT); // | SWT.BORDER
- text.setText(textValue + " ");
- text.setEditable(false);
- return text;
- }
-
- private void createFilterPart(Composite parent) {
- GridLayout layout = new GridLayout();
- layout.marginWidth = layout.marginHeight = layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- parent.setLayout(layout);
-
- // Text Area to filter
- artifactTxt = tk.createText(parent, "", SWT.BORDER | SWT.SINGLE
- | SWT.SEARCH | SWT.CANCEL);
- artifactTxt.setMessage(FILTER_HELP_MSG);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, false, false);
- gd.grabExcessHorizontalSpace = true;
- artifactTxt.setLayoutData(gd);
- artifactTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -2422321852703208573L;
-
- public void modifyText(ModifyEvent event) {
- if ("".equals(artifactTxt.getText().trim()))
- asynchronousRefresh();
- else
- refreshFilteredList();
- }
- });
- }
-
- private void refreshFilteredList() {
- List<Node> nodes;
- try {
- nodes = JcrUtils.nodeIteratorToList(listBundleArtifacts(session,
- artifactTxt.getText()));
- viewer.setInput(nodes);
- } catch (RepositoryException e) {
- throw new SlcException("Unable to list bundles", e);
- }
- }
-
- private void createTableViewer(Composite parent) {
- parent.setLayout(new FillLayout());
- // helpers to enable sorting by column
- List<String> propertiesList = new ArrayList<String>();
- List<Integer> propertyTypesList = new ArrayList<Integer>();
-
- // Define the TableViewer
- viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
-
- // Name
- TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(300);
- col.getColumn().setText("Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -760226161605987538L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element,
- DistConstants.SLC_BUNDLE_NAME);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(0));
- propertiesList.add(DistConstants.SLC_BUNDLE_NAME);
- propertyTypesList.add(PropertyType.STRING);
-
- // Symbolic name
- col = new TableViewerColumn(viewer, SWT.V_SCROLL);
- col.getColumn().setWidth(300);
- col.getColumn().setText("Symbolic Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 4431447542158431355L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_SYMBOLIC_NAME);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(1));
- propertiesList.add(SLC_SYMBOLIC_NAME);
- propertyTypesList.add(PropertyType.STRING);
-
- // Version
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(130);
- col.getColumn().setText("Version");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -5616215547236158504L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_BUNDLE_VERSION);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(2));
- propertiesList.add(SLC_BUNDLE_VERSION);
- propertyTypesList.add(DistNodeViewerComparator.VERSION_TYPE);
-
- final Table table = viewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- viewer.setContentProvider(new DistributionsContentProvider());
- getSite().setSelectionProvider(viewer);
-
- comparator = new DistNodeViewerComparator(2,
- DistNodeViewerComparator.ASCENDING, propertiesList,
- propertyTypesList);
- viewer.setComparator(comparator);
-
- // Context Menu
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(viewer.getTable());
- menuManager.addMenuListener(new IMenuListener() {
- private static final long serialVersionUID = -3886983092940055195L;
-
- public void menuAboutToShow(IMenuManager manager) {
- contextMenuAboutToShow(manager);
- }
- });
- viewer.getTable().setMenu(menu);
- getSite().registerContextMenu(menuManager, viewer);
-
- // Double click
- viewer.addDoubleClickListener(new DoubleClickListener());
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- /** force refresh of the artifact list */
- public void refresh() {
- asynchronousRefresh();
- }
-
- /** Programmatically configure the context menu */
- protected void contextMenuAboutToShow(IMenuManager menuManager) {
- IWorkbenchWindow window = DistPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
- // Build conditions
- // Delete selected artifacts
- CommandUtils.refreshCommand(menuManager, window, DeleteArtifacts.ID,
- DeleteArtifacts.DEFAULT_LABEL, DeleteArtifacts.DEFAULT_ICON,
- true);
- }
-
- private SelectionAdapter getSelectionAdapter(final int index) {
- SelectionAdapter selectionAdapter = new SelectionAdapter() {
- private static final long serialVersionUID = 5515884441510882460L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Table table = viewer.getTable();
- comparator.setColumn(index);
- int dir = table.getSortDirection();
- if (table.getSortColumn() == table.getColumn(index)) {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- } else {
- dir = SWT.DOWN;
- }
- table.setSortDirection(dir);
- table.setSortColumn(table.getColumn(index));
- viewer.refresh();
- }
- };
- return selectionAdapter;
- }
-
- /* LOCAL CLASSES */
- private class DistributionsContentProvider implements
- IStructuredContentProvider {
- private static final long serialVersionUID = -635451814876234147L;
-
- // we keep a cache of the Nodes in the content provider to be able to
- // manage long request
- private List<Node> nodes;
-
- public void dispose() {
- }
-
- // We expect a list of nodes as a new input
- @SuppressWarnings("unchecked")
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- nodes = (List<Node>) newInput;
- }
-
- public Object[] getElements(Object arg0) {
- return nodes.toArray();
- }
- }
-
- private class DoubleClickListener implements IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- Object obj = ((IStructuredSelection) event.getSelection())
- .getFirstElement();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- try {
- if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
- DistWkspEditorInput dwip = (DistWkspEditorInput) formEditor
- .getEditorInput();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenModuleEditor.PARAM_REPO_NODE_PATH,
- dwip.getRepoNodePath());
- params.put(OpenModuleEditor.PARAM_REPO_URI,
- dwip.getUri());
- params.put(OpenModuleEditor.PARAM_WORKSPACE_NAME,
- dwip.getWorkspaceName());
- String path = node.getPath();
- params.put(OpenModuleEditor.PARAM_MODULE_PATH, path);
- CommandUtils.callCommand(OpenModuleEditor.ID, params);
- }
- } catch (RepositoryException re) {
- throw new SlcException("Cannot get path for node " + node
- + " while setting parameters for "
- + "command OpenModuleEditor", re);
- }
-
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.FormEditor;
-
-/** Browse, analyse and modify a workspace containing software distributions */
-public class DistWorkspaceEditor extends FormEditor implements SlcNames {
- private static final long serialVersionUID = 5373719580281643675L;
-
- // private final static Log log =
- // LogFactory.getLog(DistributionEditor.class);
- public final static String ID = DistPlugin.PLUGIN_ID + ".distWorkspaceEditor";
-
- /* DEPENDENCY INJECTION */
- private RepositoryFactory repositoryFactory;
- private Repository localRepository;
- private Keyring keyring;
-
- // Business objects
- private Node repoNode;
- // Session that provides the node in the home of the local repository
- private Session localSession = null;
- // The business Session on optionally remote repository
- private Session businessSession;
- private DistWkspEditorInput editorInput;
-
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- editorInput = (DistWkspEditorInput) input;
- try {
- localSession = localRepository.login();
- if (editorInput.getRepoNodePath() != null
- && localSession.nodeExists(editorInput.getRepoNodePath()))
- repoNode = localSession.getNode(editorInput.getRepoNodePath());
-
- businessSession = RepoUtils.getRemoteSession(
- repositoryFactory, keyring, repoNode, editorInput.getUri(),
- editorInput.getWorkspaceName());
- } catch (RepositoryException e) {
- throw new PartInitException("Cannot log to workspace "
- + editorInput.getName(), e);
- }
- setPartName(editorInput.getWorkspaceName());
- super.init(site, input);
- }
-
- @Override
- protected void addPages() {
- try {
- addPage(new DistWkspSearchPage(this, "Details ", businessSession));
- addPage(new DistWkspBrowserPage(this, "Maven ", businessSession));
- addPage(new WkspCategoryBaseListPage(this, "Groups ",
- businessSession));
- } catch (PartInitException e) {
- throw new SlcException("Cannot add distribution editor pages", e);
- }
- }
-
- @Override
- public void doSave(IProgressMonitor arg0) {
- }
-
- @Override
- public void dispose() {
- JcrUtils.logoutQuietly(businessSession);
- JcrUtils.logoutQuietly(localSession);
- super.dispose();
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- protected Node getRepoNode() {
- return repoNode;
- }
-
- protected Session getSession() {
- return businessSession;
- }
-
- /* DEPENDENCY INJECTION */
- public void setRepositoryFactory(RepositoryFactory repositoryFactory) {
- this.repositoryFactory = repositoryFactory;
- }
-
- public void setKeyring(Keyring keyring) {
- this.keyring = keyring;
- }
-
- public void setLocalRepository(Repository localRepository) {
- this.localRepository = localRepository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-
-/** Show the details for a given bundle. */
-public class ModularDistVersionDetailPage extends FormPage implements SlcNames {
-
- final static String PAGE_ID = "ModularDistVersionDetailPage";
-
- // Business Objects
- private Node modularDistVersion;
-
- // This page widgets
- private FormToolkit tk;
-
- public ModularDistVersionDetailPage(FormEditor formEditor, String title,
- Node modularDistVersion) {
- super(formEditor, PAGE_ID, title);
- this.modularDistVersion = modularDistVersion;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- // General settings for this page
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
- Composite body = form.getBody();
-
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = 5;
- layout.marginRight = 15;
- layout.verticalSpacing = 0;
- body.setLayout(layout);
- try {
- form.setText(modularDistVersion.hasProperty(SLC_NAME) ? modularDistVersion
- .getProperty(SLC_NAME).getString() : "");
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get slc:name for node "
- + modularDistVersion, re);
- }
-
- // Main layout
- Composite mavenSnipet = tk.createComposite(body);
- mavenSnipet.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- populateMavenSnippetPart(mavenSnipet);
- }
-
- private void populateMavenSnippetPart(Composite parent) {
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = layout.horizontalSpacing = layout.horizontalSpacing = layout.marginHeight = 0;
- parent.setLayout(layout);
-
- Section section = tk.createSection(parent, Section.TITLE_BAR
- | Section.DESCRIPTION);
- section.setText("Maven");
- section.setDescription("In order to rely on the versions defined by this distribution, "
- + "add the below tag to the dependency management of your parent pom.");
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Text snippetTxt = createMavenSnippet(section);
- section.setClient(snippetTxt);
- }
-
- // /////////////////////
- // HELPERS
- /** Creates a text area with corresponding maven snippet */
- private Text createMavenSnippet(Composite parent) {
- Text mavenSnippet = new Text(parent, SWT.MULTI | SWT.WRAP);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- gd.heightHint = 100;
- mavenSnippet.setLayoutData(gd);
- mavenSnippet.setText(generateXmlSnippet());
- mavenSnippet.setEditable(false);
- return mavenSnippet;
- }
-
- private String generateXmlSnippet() {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("<dependency>\n");
- sb.append("\t<groupId>");
- sb.append(modularDistVersion.getProperty(SLC_GROUP_ID).getString());
- sb.append("</groupId>\n");
- sb.append("\t<artifactId>");
- sb.append(modularDistVersion.getProperty(SLC_ARTIFACT_ID)
- .getString());
- sb.append("</artifactId>\n");
- sb.append("\t<version>");
- sb.append(modularDistVersion.getProperty(SLC_ARTIFACT_VERSION)
- .getString());
- sb.append("</version>\n");
- sb.append("\t<type>pom</type>\n");
- sb.append("\t<scope>import</scope>\n");
- sb.append("</dependency>");
- return sb.toString();
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while generating maven snippet");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-
-/**
- * Manage a modular distribution version contained in a specific workspace of a
- * repository
- */
-public class ModularDistVersionEditor extends ArtifactVersionEditor {
- private static final long serialVersionUID = -2223542780164288554L;
-
- // private final static Log log =
- // LogFactory.getLog(ModularDistVersionEditor.class);
- public final static String ID = DistPlugin.PLUGIN_ID + ".modularDistVersionEditor";
-
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- super.init(site, input);
- }
-
- @Override
- protected void addPages() {
- setPartName(getFormattedName());
- try {
- addPage(new ModularDistVersionOverviewPage(this, "Modules ",
- getArtifact()));
- addPage(new RunInOsgiPage(this, "Run as OSGi ", getArtifact()));
- addPage(new ModularDistVersionDetailPage(this, "Details",
- getArtifact()));
- } catch (PartInitException e) {
- throw new SlcException("Cannot add distribution editor pages", e);
- }
- }
-
- protected String getFormattedName() {
- try {
- String partName = null;
- if (getArtifact().hasProperty(SLC_NAME))
- partName = getArtifact().getProperty(SLC_NAME).getString();
- else
- partName = getArtifact().getName();
-
- if (partName.length() > 10) {
- partName = "..." + partName.substring(partName.length() - 10);
- }
- return partName;
- } catch (RepositoryException re) {
- throw new SlcException("unable to get slc:name property for node "
- + getArtifact(), re);
- }
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.qom.Constraint;
-import javax.jcr.query.qom.DynamicOperand;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
-import javax.jcr.query.qom.StaticOperand;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.commands.OpenModuleEditor;
-import org.argeo.slc.client.ui.dist.utils.DistNodeViewerComparator;
-import org.argeo.slc.client.ui.dist.utils.HyperlinkAdapter;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.aether.artifact.DefaultArtifact;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Hyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Show all modules contained in a given modular distribution as filter-able
- * table
- */
-public class ModularDistVersionOverviewPage extends FormPage implements
- SlcNames {
-
- private final static CmsLog log = CmsLog
- .getLog(ModularDistVersionOverviewPage.class);
-
- final static String PAGE_ID = "ModularDistVersionOverviewPage";
-
- // Business Objects
- private Node modularDistribution;
- // private Node modularDistributionBase;
-
- // This page widgets
- private DistNodeViewerComparator comparator;
- private TableViewer viewer;
- private FormToolkit tk;
- private Text filterTxt;
- private final static String FILTER_HELP_MSG = "Enter filter criterion separated by a space";
-
- public ModularDistVersionOverviewPage(FormEditor formEditor, String title,
- Node modularDistribution) {
- super(formEditor, PAGE_ID, title);
- this.modularDistribution = modularDistribution;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- // General settings for this page
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
- Composite body = form.getBody();
-
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = 5;
- layout.marginRight = 15;
- layout.verticalSpacing = 0;
- body.setLayout(layout);
- try {
- form.setText(modularDistribution.hasProperty(SlcNames.SLC_NAME) ? modularDistribution
- .getProperty(SlcNames.SLC_NAME).getString() : "");
- form.setMessage(
- modularDistribution
- .hasProperty(DistConstants.SLC_BUNDLE_DESCRIPTION) ? modularDistribution
- .getProperty(DistConstants.SLC_BUNDLE_DESCRIPTION)
- .getString() : "", IMessageProvider.NONE);
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get bundle name for node "
- + modularDistribution, re);
- }
-
- // Main layout
- Composite header = tk.createComposite(body);
- header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- populateHeaderPart(header);
-
- Composite moduleTablePart = tk.createComposite(body);
- moduleTablePart.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
- populateModuleTablePart(moduleTablePart);
- }
-
- private void populateHeaderPart(Composite parent) {
- GridLayout layout = new GridLayout(6, false);
- layout.horizontalSpacing = 10;
- parent.setLayout(layout);
- try {
- // 1st Line: Category, name version
- createLT(
- parent,
- "Category",
- modularDistribution.hasProperty(SlcNames.SLC_CATEGORY) ? modularDistribution
- .getProperty(SlcNames.SLC_CATEGORY).getString()
- : "");
- createLT(
- parent,
- "Name",
- modularDistribution.hasProperty(SlcNames.SLC_NAME) ? modularDistribution
- .getProperty(SlcNames.SLC_NAME).getString() : "");
- createLT(
- parent,
- "Version",
- modularDistribution.hasProperty(SlcNames.SLC_VERSION) ? modularDistribution
- .getProperty(SlcNames.SLC_VERSION).getString() : "");
-
- // 2nd Line: Vendor, licence, sources
- createLT(
- parent,
- "Vendor",
- modularDistribution
- .hasProperty(DistConstants.SLC_BUNDLE_VENDOR) ? modularDistribution
- .getProperty(DistConstants.SLC_BUNDLE_VENDOR)
- .getString() : "N/A");
-
- createHyperlink(parent, "Licence", DistConstants.SLC_BUNDLE_LICENCE);
- addSourceSourcesLink(parent);
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get bundle name for node "
- + modularDistribution, re);
- }
-
- }
-
- private Text createLT(Composite parent, String labelValue, String textValue) {
- Label label = tk.createLabel(parent, labelValue, SWT.RIGHT);
- // label.setFont(EclipseUiUtils.getBoldFont(parent));
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
-
- // Add a trailing space to workaround a display glitch in RAP 1.3
- Text text = new Text(parent, SWT.LEFT);
- text.setText(textValue + " ");
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- text.setEditable(false);
- return text;
- }
-
- private void createHyperlink(Composite parent, String label,
- String jcrPropName) throws RepositoryException {
- tk.createLabel(parent, label, SWT.NONE);
- if (modularDistribution.hasProperty(jcrPropName)) {
- final Hyperlink link = tk.createHyperlink(parent,
- modularDistribution.getProperty(jcrPropName).getString(),
- SWT.NONE);
- link.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- try {
- IWorkbenchBrowserSupport browserSupport = PlatformUI
- .getWorkbench().getBrowserSupport();
- IWebBrowser browser = browserSupport
- .createBrowser(
- IWorkbenchBrowserSupport.LOCATION_BAR
- | IWorkbenchBrowserSupport.NAVIGATION_BAR,
- "SLC Distribution browser",
- "SLC Distribution browser",
- "A tool tip");
- browser.openURL(new URL(link.getText()));
- } catch (Exception ex) {
- throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- }
- }
- });
- } else
- tk.createLabel(parent, "N/A", SWT.NONE);
- }
-
- // helper to check if sources are available
- private void addSourceSourcesLink(Composite parent) {
- try {
- String srcPath = RepoUtils.relatedPdeSourcePath(
- RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH,
- modularDistribution);
- if (!modularDistribution.getSession().nodeExists(srcPath)) {
- createLT(parent, "Sources", "N/A");
- } else {
- final Node sourcesNode = modularDistribution.getSession()
- .getNode(srcPath);
-
- String srcName = null;
- if (sourcesNode.hasProperty(SlcNames.SLC_SYMBOLIC_NAME))
- srcName = sourcesNode.getProperty(
- SlcNames.SLC_SYMBOLIC_NAME).getString();
- else
- srcName = sourcesNode.getName();
- Label label = tk.createLabel(parent, "Sources", SWT.RIGHT);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
- false));
- Hyperlink link = tk.createHyperlink(parent, srcName, SWT.NONE);
- link.addHyperlinkListener(new OpenFileLinkListener(sourcesNode
- .getPath()));
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unable to configure sources link for "
- + modularDistribution, e);
- }
- }
-
- private class OpenFileLinkListener extends HyperlinkAdapter {
- final private String path;
-
- public OpenFileLinkListener(String path) {
- this.path = path;
- }
-
- @Override
- public void linkActivated(HyperlinkEvent e) {
- log.warn("File download must be implemented. Cannot provide access to "
- + path);
-
- // try {
- // ModuleEditorInput editorInput = (ModuleEditorInput)
- // getEditorInput();
- // Map<String, String> params = new HashMap<String, String>();
- // params.put(OpenJcrFile.PARAM_REPO_NODE_PATH,
- // editorInput.getRepoNodePath());
- // params.put(OpenJcrFile.PARAM_REPO_URI, editorInput.getUri());
- // params.put(OpenJcrFile.PARAM_WORKSPACE_NAME,
- // editorInput.getWorkspaceName());
- // params.put(OpenJcrFile.PARAM_FILE_PATH, path);
- //
- // String cmdId = (new OpenJcrFileCmdId()).getCmdId();
- // CommandUtils.callCommand(cmdId, params);
- // } catch (Exception ex) {
- // throw new SlcException("error opening browser", ex); //$NON-NLS-1$
- // }
- }
- }
-
- private void populateModuleTablePart(Composite parent) {
- GridLayout layout = new GridLayout(1, false);
- layout.marginWidth = layout.horizontalSpacing = 0;
- layout.verticalSpacing = 5;
- layout.marginTop = 15;
- parent.setLayout(layout);
- // A sub title
- Label label = tk.createLabel(parent,
- "Modules included in the current distribution", SWT.NONE);
- label.setFont(EclipseUiUtils.getBoldFont(parent));
-
- // Add the filter section
- Composite filterPart = tk.createComposite(parent);
- filterPart.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- createFilterPart(filterPart);
-
- // Add the table
- Composite tablePart = tk.createComposite(parent);
- tablePart.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- createTableViewer(tablePart);
- // populate it on first pass.
- refresh();
- }
-
- private void createFilterPart(Composite parent) {
- GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = layout.marginHeight = layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- parent.setLayout(layout);
-
- // Text Area to filter
- filterTxt = tk.createText(parent, "", SWT.BORDER | SWT.SINGLE
- | SWT.SEARCH | SWT.CANCEL);
- filterTxt.setMessage(FILTER_HELP_MSG);
- filterTxt.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- filterTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -276152321986407726L;
-
- public void modifyText(ModifyEvent event) {
- refresh();
- }
- });
-
- Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
- resetBtn.setImage(DistImages.IMG_CLEAR);
- resetBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -3549303742841670919L;
-
- public void widgetSelected(SelectionEvent e) {
- filterTxt.setText("");
- filterTxt.setMessage(FILTER_HELP_MSG);
- }
- });
- }
-
- private void createTableViewer(Composite parent) {
- parent.setLayout(new FillLayout());
- // helpers to enable sorting by column
- List<String> propertiesList = new ArrayList<String>();
- List<Integer> propertyTypesList = new ArrayList<Integer>();
-
- // Define the TableViewer
- viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
-
- // Name
- TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(220);
- col.getColumn().setText("Category");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 5875398301711336875L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SlcNames.SLC_CATEGORY);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(0));
- propertiesList.add(SlcNames.SLC_CATEGORY);
- propertyTypesList.add(PropertyType.STRING);
-
- // Symbolic name
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(220);
- col.getColumn().setText("Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 3880240676256465072L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_NAME);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(1));
- propertiesList.add(SLC_NAME);
- propertyTypesList.add(PropertyType.STRING);
-
- // Version
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(160);
- col.getColumn().setText("Version");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -4706438113850571784L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_VERSION);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(2));
- propertiesList.add(SLC_VERSION);
- propertyTypesList.add(DistNodeViewerComparator.VERSION_TYPE);
-
- // Exists in workspace
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(160);
- col.getColumn().setText("Exists in workspace");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 8190063212920414300L;
-
- @Override
- public String getText(Object element) {
- return getRealizedModule((Node) element) != null ? "Yes" : "No";
- // return JcrUtils.get((Node) element, SLC_VERSION);
- }
- });
- // col.getColumn().addSelectionListener(getSelectionAdapter(2));
- // propertiesList.add(SLC_VERSION);
- // propertyTypesList.add(PropertyType.STRING);
-
- final Table table = viewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- viewer.setContentProvider(new DistributionsContentProvider());
- getSite().setSelectionProvider(viewer);
-
- comparator = new DistNodeViewerComparator(2,
- DistNodeViewerComparator.ASCENDING, propertiesList,
- propertyTypesList);
- viewer.setComparator(comparator);
-
- // // Context Menu
- // MenuManager menuManager = new MenuManager();
- // Menu menu = menuManager.createContextMenu(viewer.getTable());
- // menuManager.addMenuListener(new IMenuListener() {
- // public void menuAboutToShow(IMenuManager manager) {
- // contextMenuAboutToShow(manager);
- // }
- // });
- // viewer.getTable().setMenu(menu);
- // getSite().registerContextMenu(menuManager, viewer);
-
- // Double click
- viewer.addDoubleClickListener(new DoubleClickListener());
- }
-
- private Node getRealizedModule(Node moduleCoordinates) {
- try {
- String category = JcrUtils.get(moduleCoordinates, SLC_CATEGORY);
- String name = JcrUtils.get(moduleCoordinates, SLC_NAME);
- String version = JcrUtils.get(moduleCoordinates, SLC_VERSION);
- Artifact artifact = new DefaultArtifact(category + ":" + name + ":"
- + version);
- String parentPath = MavenConventionsUtils.artifactParentPath(
- RepoConstants.DEFAULT_ARTIFACTS_BASE_PATH, artifact);
-
- Session session = modularDistribution.getSession();
- if (session.nodeExists(parentPath)) {
- Node parent = session.getNode(parentPath);
- NodeIterator nit = parent.getNodes();
- while (nit.hasNext()) {
- Node currN = nit.nextNode();
- if (currN.isNodeType(SlcTypes.SLC_ARTIFACT))
- return currN;
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "unable to retrieve realized module with coordinates "
- + moduleCoordinates, re);
- }
- return null;
- }
-
- private void refresh() {
- final List<Node> result = JcrUtils
- .nodeIteratorToList(listBundleArtifacts());
- viewer.setInput(result);
- }
-
- /** Build repository request */
- private NodeIterator listBundleArtifacts() {
- try {
- Session session = modularDistribution.getSession();
- QueryManager queryManager = session.getWorkspace()
- .getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
-
- Selector source = factory.selector(SlcTypes.SLC_MODULE_COORDINATES,
- SlcTypes.SLC_MODULE_COORDINATES);
-
- // Create a dynamic operand for each property on which we want to
- // filter
- DynamicOperand catDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_CATEGORY);
- DynamicOperand nameDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_NAME);
- DynamicOperand versionDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_VERSION);
-
- String path = modularDistribution.getPath() + "/"
- + SlcNames.SLC_MODULES;
-
- // Default Constraint: correct children
- Constraint defaultC = factory.descendantNode(
- source.getSelectorName(), path);
-
- String filter = filterTxt.getText();
-
- // Build constraints based the textArea content
- if (filter != null && !"".equals(filter.trim())) {
- // Parse the String
- String[] strs = filter.trim().split(" ");
- for (String token : strs) {
- token = token.replace('*', '%');
- StaticOperand so = factory.literal(session
- .getValueFactory().createValue("%" + token + "%"));
-
- Constraint currC = factory.comparison(catDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so);
- currC = factory.or(currC, factory.comparison(versionDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so));
- currC = factory.or(currC, factory.comparison(nameDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so));
-
- defaultC = factory.and(defaultC, currC);
- }
- }
-
- QueryObjectModel query = factory.createQuery(source, defaultC,
- null, null);
- QueryResult result = query.execute();
- return result.getNodes();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to refresh module list for node "
- + modularDistribution, re);
- }
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- // /** Programmatically configure the context menu */
- // protected void contextMenuAboutToShow(IMenuManager menuManager) {
- // IWorkbenchWindow window = DistPlugin.getDefault().getWorkbench()
- // .getActiveWorkbenchWindow();
- // // Build conditions
- // // Delete selected artifacts
- // // CommandUtils.refreshCommand(menuManager, window, DeleteArtifacts.ID,
- // // DeleteArtifacts.DEFAULT_LABEL, DeleteArtifacts.DEFAULT_ICON,
- // // true);
- // }
-
- private SelectionAdapter getSelectionAdapter(final int index) {
- SelectionAdapter selectionAdapter = new SelectionAdapter() {
- private static final long serialVersionUID = 1260801795934660840L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Table table = viewer.getTable();
- comparator.setColumn(index);
- int dir = table.getSortDirection();
- if (table.getSortColumn() == table.getColumn(index)) {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- } else {
- dir = SWT.DOWN;
- }
- table.setSortDirection(dir);
- table.setSortColumn(table.getColumn(index));
- viewer.refresh();
- }
- };
- return selectionAdapter;
- }
-
- /* LOCAL CLASSES */
- private class DistributionsContentProvider implements
- IStructuredContentProvider {
- private static final long serialVersionUID = 8385338190908823791L;
- // we keep a cache of the Nodes in the content provider to be able to
- // manage long request
- private List<Node> nodes;
-
- public void dispose() {
- }
-
- // We expect a list of nodes as a new input
- @SuppressWarnings("unchecked")
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- nodes = (List<Node>) newInput;
- }
-
- public Object[] getElements(Object arg0) {
- return nodes.toArray();
- }
- }
-
- private class DoubleClickListener implements IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- Object obj = ((IStructuredSelection) event.getSelection())
- .getFirstElement();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- try {
- if (node.isNodeType(SlcTypes.SLC_MODULE_COORDINATES)) {
- Node realizedModule = getRealizedModule(node);
- if (realizedModule != null) {
- ModuleEditorInput dwip = (ModuleEditorInput) getEditorInput();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenModuleEditor.PARAM_REPO_NODE_PATH,
- dwip.getRepoNodePath());
- params.put(OpenModuleEditor.PARAM_REPO_URI,
- dwip.getUri());
- params.put(OpenModuleEditor.PARAM_WORKSPACE_NAME,
- dwip.getWorkspaceName());
- String path = realizedModule.getPath();
- params.put(OpenModuleEditor.PARAM_MODULE_PATH, path);
- CommandUtils.callCommand(OpenModuleEditor.ID,
- params);
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException("Cannot get path for node " + node
- + " while setting parameters for "
- + "command OpenModuleEditor", re);
- }
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/** Editor input for a JCR node object in a multi-repository environment */
-public class ModuleEditorInput implements IEditorInput, SlcNames {
-
- // Define relevant workspace on a given repository
- private String repoNodePath;
- private String uri;
- private String workspaceName;
- private String modulePath;
-
- public ModuleEditorInput(String repoNodePath, String uri,
- String workspaceName, String artifactPath) {
- if (workspaceName == null)
- throw new SlcException("Workspace name cannot be null");
- if (uri == null && repoNodePath == null)
- throw new SlcException("Define at least one of the 2 "
- + "parameters URI or Repo Node Path");
- if (artifactPath == null)
- throw new SlcException("Module path cannot be null");
- this.repoNodePath = repoNodePath;
- this.uri = uri;
- this.workspaceName = workspaceName;
- this.modulePath = artifactPath;
- }
-
- public String getModulePath() {
- return modulePath;
- }
-
- public String getWorkspaceName() {
- return workspaceName;
- }
-
- public String getRepoNodePath() {
- return repoNodePath;
- }
-
- public String getUri() {
- return uri;
- }
-
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return true;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- // Dummy compulsory methods
- public String getToolTipText() {
- return getModulePath();
- }
-
- public String getName() {
- return JcrUtils.lastPathElement(modulePath);
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- /**
- * equals method based on coordinates
- */
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
-
- ModuleEditorInput other = (ModuleEditorInput) obj;
-
- if (!modulePath.equals(other.getModulePath()))
- return false;
- if (!workspaceName.equals(other.getWorkspaceName()))
- return false;
-
- if (uri == null && other.getUri() != null
- || !uri.equals(other.getUri()))
- return false;
-
- if (repoNodePath == null && other.getRepoNodePath() != null
- || !repoNodePath.equals(other.getRepoNodePath()))
- return false;
-
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Enable launch of the current distribution in a separate osgi run time.
- * Display also a console to interract with the launched runtime
- */
-public class RunInOsgiPage extends FormPage implements SlcNames {
-
- final static String PAGE_ID = "RunInOsgiPage";
-
- // Business Objects
- private Node modularDistribution;
-
- // This page widgets
- private Button launchBtn;
- private Text consoleTxt;
-
- private FormToolkit tk;
-
- public RunInOsgiPage(FormEditor formEditor, String title,
- Node modularDistribution) {
- super(formEditor, PAGE_ID, title);
- this.modularDistribution = modularDistribution;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
- // Main Layout
- Composite body = form.getBody();
- GridLayout layout = new GridLayout();
- layout.marginTop = layout.marginWidth = 0;
- body.setLayout(layout);
-
- // The header
- Composite header = tk.createComposite(body);
- header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- createHeaderPart(header);
-
- // The console
- Composite console = tk.createComposite(body);
- console.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- createConsolePart(console);
- body.layout();
- }
-
- private void createHeaderPart(Composite parent) {
- GridLayout layout = new GridLayout();
- parent.setLayout(layout);
-
- // Text Area to filter
- launchBtn = tk.createButton(parent, " Launch ", SWT.PUSH);
- launchBtn.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
-
- launchBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -1633658484882130602L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- throw new SlcException("Implement this");
- }
- });
- }
-
- private void createConsolePart(Composite parent) {
- parent.setLayout(new GridLayout());
- consoleTxt = tk.createText(parent, "OSGi > ", SWT.MULTI | SWT.WRAP
- | SWT.BORDER);
- consoleTxt.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- }
-
- @Override
- public void setFocus() {
- launchBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.observation.Event;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.qom.Constraint;
-import javax.jcr.query.qom.DynamicOperand;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
-import javax.jcr.query.qom.StaticOperand;
-
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.commands.OpenGenerateBinariesWizard;
-import org.argeo.slc.client.ui.dist.commands.OpenModuleEditor;
-import org.argeo.slc.client.ui.dist.utils.DistNodeViewerComparator;
-import org.argeo.slc.repo.RepoConstants;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Show all category base (currently only Aether group base) contained in a
- * given workspace as filter-able table. Enable to definition of which of them
- * should be managed as modular distribution
- */
-public class WkspCategoryBaseListPage extends FormPage implements SlcNames {
-
- final static String PAGE_ID = "WkspCategoryBaseListPage";
-
- // Business Objects
- private Session session;
-
- // This page widgets
- private DistNodeViewerComparator comparator;
- private TableViewer viewer;
- private FormToolkit tk;
- private Text filterTxt;
- private final static String FILTER_HELP_MSG = "Enter filter criterion separated by a space";
-
- // Observes changes
- // private final static String[] observedTypes = { SlcTypes.SLC_GROUP_BASE
- // };
- // private CategoryObserver categoriesObserver;
-
- public WkspCategoryBaseListPage(FormEditor formEditor, String title,
- Session session) {
- super(formEditor, PAGE_ID, title);
- this.session = session;
- }
-
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- ScrolledForm form = managedForm.getForm();
- tk = managedForm.getToolkit();
-
- form.setText("Define Relevant Categories");
- form.setMessage("Choose in the below list "
- + "the categories that can be used as base for "
- + "modular distributions maintained via the current workspace",
- IMessageProvider.NONE);
-
- // Main Layout
- GridLayout layout = new GridLayout(1, false);
- Composite body = form.getBody();
- body.setLayout(layout);
-
- // filter section
- Composite header = tk.createComposite(body);
- header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- createFilterPart(header);
-
- // the table
- Composite tableCmp = tk.createComposite(body);
- tableCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- createTableViewer(tableCmp);
-
- // categoriesObserver = new CategoryObserver(viewer.getTable()
- // .getDisplay());
- // try {
- // ObservationManager observationManager = session.getWorkspace()
- // .getObservationManager();
- // // FIXME Will not be notified if empty result is deleted
- // observationManager.addEventListener(categoriesObserver,
- // Event.PROPERTY_CHANGED, "/", true, null, observedTypes,
- // false);
- // } catch (RepositoryException e) {
- // throw new SlcException("Cannot register listeners", e);
- // }
-
- refresh();
- }
-
- private void refresh() {
- final List<Node> result = JcrUtils.nodeIteratorToList(listGroupBase());
- viewer.setInput(result);
- }
-
- /** Build repository request */
- private NodeIterator listGroupBase() {
- try {
- QueryManager queryManager = session.getWorkspace()
- .getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
-
- Selector source = factory.selector(SlcTypes.SLC_GROUP_BASE,
- SlcTypes.SLC_MODULE_COORDINATES);
-
- // Create a dynamic operand for each property on which we want to
- // filter
- DynamicOperand catDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_CATEGORY);
- DynamicOperand nameDO = factory.propertyValue(
- source.getSelectorName(), SlcNames.SLC_NAME);
-
- String filter = filterTxt.getText();
-
- Constraint defaultC = null;
- // Build constraints based the textArea content
- if (filter != null && !"".equals(filter.trim())) {
- // Parse the String
- String[] strs = filter.trim().split(" ");
- for (String token : strs) {
- token = token.replace('*', '%');
- StaticOperand so = factory.literal(session
- .getValueFactory().createValue("%" + token + "%"));
-
- Constraint currC = factory.comparison(catDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so);
- currC = factory.or(currC, factory.comparison(nameDO,
- QueryObjectModelFactory.JCR_OPERATOR_LIKE, so));
-
- if (defaultC == null)
- defaultC = currC;
- else
- defaultC = factory.and(defaultC, currC);
- }
- }
-
- QueryObjectModel query = factory.createQuery(source, defaultC,
- null, null);
- QueryResult result = query.execute();
- return result.getNodes();
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unable to refresh group list for workspace "
- + getEditorInput().getName(), re);
- }
- }
-
- private void createFilterPart(Composite parent) {
- GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = layout.marginHeight = layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- parent.setLayout(layout);
-
- // Text Area to filter
- filterTxt = tk.createText(parent, "", SWT.BORDER | SWT.SINGLE
- | SWT.SEARCH | SWT.CANCEL);
- filterTxt.setMessage(FILTER_HELP_MSG);
- filterTxt.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- filterTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = 8727389523069041623L;
-
- public void modifyText(ModifyEvent event) {
- refresh();
- }
- });
-
- Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
- resetBtn.setImage(DistImages.IMG_REPO_READONLY);
- resetBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -6523538838444581321L;
-
- public void widgetSelected(SelectionEvent e) {
- resetFilter();
- }
- });
- }
-
- private void resetFilter() {
- filterTxt.setText("");
- filterTxt.setMessage(FILTER_HELP_MSG);
- }
-
- private void createTableViewer(Composite parent) {
- parent.setLayout(new FillLayout());
- // helpers to enable sorting by column
- List<String> propertiesList = new ArrayList<String>();
- List<Integer> propertyTypesList = new ArrayList<Integer>();
-
- // Define the TableViewer
- viewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
- | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
-
- TableViewerColumn col;
- // Name
- // TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
- // col.getColumn().setWidth(220);
- // col.getColumn().setText("Category");
- // col.setLabelProvider(new ColumnLabelProvider() {
- // @Override
- // public String getText(Object element) {
- // return JcrUtils.get((Node) element, SlcNames.SLC_CATEGORY);
- // }
- // });
- // col.getColumn().addSelectionListener(getSelectionAdapter(0));
- // propertiesList.add(SlcNames.SLC_CATEGORY);
- // propertyTypesList.add(PropertyType.STRING);
-
- // Group base name
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(220);
- col.getColumn().setText("Group Name");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 6186787928630825293L;
-
- @Override
- public String getText(Object element) {
- return JcrUtils.get((Node) element, SLC_GROUP_BASE_ID);
- }
- });
- col.getColumn().addSelectionListener(getSelectionAdapter(0));
- propertiesList.add(SLC_GROUP_BASE_ID);
- propertyTypesList.add(PropertyType.STRING);
-
- // Version
- col = new TableViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(80);
- col.getColumn().setText("Has binaries");
- col.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -2017377132642062464L;
-
- @Override
- public String getText(Object element) {
- try {
- Node currNode = (Node) element;
-
- return currNode.hasNode(RepoConstants.BINARIES_ARTIFACT_ID) ? "Yes"
- : "No";
- } catch (RepositoryException e) {
- throw new SlcException("unable to check type of node "
- + element, e);
- }
- }
- });
- // col.getColumn().addSelectionListener(getSelectionAdapter(2));
- // propertiesList.add(SLC_VERSION);
- // propertyTypesList.add(PropertyType.STRING);
-
- final Table table = viewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- viewer.setContentProvider(new DistributionsContentProvider());
- getSite().setSelectionProvider(viewer);
-
- comparator = new DistNodeViewerComparator(0,
- DistNodeViewerComparator.ASCENDING, propertiesList,
- propertyTypesList);
- viewer.setComparator(comparator);
-
- // Context Menu
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(viewer.getTable());
- menuManager.addMenuListener(new IMenuListener() {
- private static final long serialVersionUID = 739004528695501335L;
-
- public void menuAboutToShow(IMenuManager manager) {
- contextMenuAboutToShow(manager);
- }
- });
- viewer.getTable().setMenu(menu);
- getSite().registerContextMenu(menuManager, viewer);
-
- // Double click
- viewer.addDoubleClickListener(new DoubleClickListener());
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- /** Programmatically configure the context menu */
- protected void contextMenuAboutToShow(IMenuManager menuManager) {
- IWorkbenchWindow window = DistPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
- // Build conditions
- // Mark as category base
- Object firstElement = ((IStructuredSelection) viewer.getSelection())
- .getFirstElement();
- Node currSelected = (Node) firstElement;
-
- DistWkspEditorInput input = (DistWkspEditorInput) getEditorInput();
-
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenGenerateBinariesWizard.PARAM_REPO_NODE_PATH,
- input.getRepoNodePath());
- try {
- params.put(OpenGenerateBinariesWizard.PARAM_MODULE_PATH,
- currSelected.getPath());
- } catch (RepositoryException e) {
- throw new SlcException("Unable to get path for " + currSelected, e);
- }
- params.put(OpenGenerateBinariesWizard.PARAM_WORKSPACE_NAME,
- input.getWorkspaceName());
-
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- OpenGenerateBinariesWizard.ID,
- OpenGenerateBinariesWizard.DEFAULT_LABEL,
- OpenGenerateBinariesWizard.DEFAULT_ICON, true, params);
-
- // boolean isRelevant = false;
- // try {
- // isRelevant = currSelected.isNodeType(SlcTypes.SLC_CATEGORY);
- // boolean canEdit = currSelected.canAddMixin(SlcTypes.SLC_CATEGORY);
- //
- // } catch (RepositoryException e) {
- // throw new SlcException("unable to check type of node "
- // + firstElement, e);
- // }
- // // Add
- // if (isRelevant) {// Remove
- // CommandUtils.refreshCommand(menuManager, window,
- // MarkAsRelevantCategory.ID,
- // MarkAsRelevantCategory.DEFAULT_REMOVE_LABEL,
- // MarkAsRelevantCategory.DEFAULT_REMOVE_ICON, true);
- // } else {
- // CommandUtils.refreshCommand(menuManager, window,
- // MarkAsRelevantCategory.ID,
- // MarkAsRelevantCategory.DEFAULT_LABEL,
- // MarkAsRelevantCategory.DEFAULT_ICON, true);
- // }
- }
-
- private SelectionAdapter getSelectionAdapter(final int index) {
- SelectionAdapter selectionAdapter = new SelectionAdapter() {
- private static final long serialVersionUID = -1723894288128081757L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Table table = viewer.getTable();
- comparator.setColumn(index);
- int dir = table.getSortDirection();
- if (table.getSortColumn() == table.getColumn(index)) {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- } else {
- dir = SWT.DOWN;
- }
- table.setSortDirection(dir);
- table.setSortColumn(table.getColumn(index));
- viewer.refresh();
- }
- };
- return selectionAdapter;
- }
-
- /* LOCAL CLASSES */
- private class DistributionsContentProvider implements
- IStructuredContentProvider {
- private static final long serialVersionUID = -5939763615620837492L;
-
- // we keep a cache of the Nodes in the content provider to be able to
- // manage long request
- private List<Node> nodes;
-
- public void dispose() {
- }
-
- // We expect a list of nodes as a new input
- @SuppressWarnings("unchecked")
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- nodes = (List<Node>) newInput;
- }
-
- public Object[] getElements(Object arg0) {
- return nodes.toArray();
- }
- }
-
- private class DoubleClickListener implements IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- Object obj = ((IStructuredSelection) event.getSelection())
- .getFirstElement();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- try {
- if (node.isNodeType(SlcTypes.SLC_ARTIFACT)) {
- DistWkspEditorInput dwip = (DistWkspEditorInput) getEditorInput();
- Map<String, String> params = new HashMap<String, String>();
- params.put(OpenModuleEditor.PARAM_REPO_NODE_PATH,
- dwip.getRepoNodePath());
- params.put(OpenModuleEditor.PARAM_REPO_URI,
- dwip.getUri());
- params.put(OpenModuleEditor.PARAM_WORKSPACE_NAME,
- dwip.getWorkspaceName());
- String path = node.getPath();
- params.put(OpenModuleEditor.PARAM_MODULE_PATH, path);
- CommandUtils.callCommand(OpenModuleEditor.ID, params);
- }
- } catch (RepositoryException re) {
- throw new SlcException("Cannot get path for node " + node
- + " while setting parameters for "
- + "command OpenModuleEditor", re);
- }
-
- }
- }
- }
-
- class CategoryObserver extends AsyncUiEventListener {
-
- public CategoryObserver(Display display) {
- super(display);
- }
-
- @Override
- protected Boolean willProcessInUiThread(List<Event> events)
- throws RepositoryException {
- for (Event event : events) {
- String path = event.getPath();
- if (JcrUtils.lastPathElement(path).equals(
- DistConstants.JCR_MIXIN_TYPES))
- return true;
- }
- return false;
- }
-
- protected void onEventInUiThread(List<Event> events)
- throws RepositoryException {
- if (getLog().isTraceEnabled())
- getLog().trace("Refresh table");
- viewer.refresh();
- }
- }
-
- @Override
- public void setActive(boolean active) {
- super.setActive(active);
- if (active) {
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.argeo.eclipse.ui.TreeParent;
-
-/** Common super class for all tree elements of the Distributions View */
-public abstract class DistParentElem extends TreeParent {
- protected final static Character VERSION_SEP = '-';
-
- protected static final List<String> ARGEO_SYSTEM_WKSP;
- static {
- List<String> tmpList = new ArrayList<String>();
- tmpList.add("main");
- tmpList.add("proxy");
- tmpList.add("security");
- tmpList.add("localrepo");
- ARGEO_SYSTEM_WKSP = Collections.unmodifiableList(tmpList);
- }
-
- private boolean inHome = false;
- private boolean isReadOnly = false;
-
- public DistParentElem(String name, boolean inHome, boolean isReadOnly) {
- super(name);
- this.inHome = inHome;
- this.isReadOnly = isReadOnly;
- }
-
- public DistParentElem(String name) {
- super(name);
- }
-
- // public abstract String getLabel();
- //
- // public abstract Object[] getChildren();
- //
- // public boolean hasChildren() {
- // return true;
- // }
- //
- // public void dispose() {
- // }
-
- public void setInHome(boolean inHome) {
- this.inHome = inHome;
- }
-
- public void setReadOnly(boolean isReadOnly) {
- this.isReadOnly = isReadOnly;
- }
-
- public boolean inHome() {
- return inHome;
- }
-
- public boolean isReadOnly() {
- return isReadOnly;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-/**
- * Abstract a node of type slc:groupBase that gathers a set of artifacts that
- * have the same group ID
- */
-public class GroupBaseElem extends DistParentElem {
- // private WorkspaceElem wkspElem;
- private String groupId;
-
- public GroupBaseElem(WorkspaceElem wkspElem, String groupId) {
- super(groupId, wkspElem.inHome(), wkspElem.isReadOnly());
-
- setParent(wkspElem);
- // this.wkspElem = wkspElem;
- this.groupId = groupId;
- }
-
- public Object[] getChildren() {
- return null;
- }
-
- public String getLabel() {
- return groupId;
- }
-
- // public String toString() {
- // return getLabel();
- // }
-
- // public void dispose() {
- // }
-
- public WorkspaceElem getWorkspaceElem() {
- return (WorkspaceElem) getParent();
- }
-
- public String getGroupId() {
- return getName();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.qom.Constraint;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-
-/**
- * Abstract the base of a given modular distribution set i.e. the parent of all
- * versions of a given modular distribution
- */
-public class ModularDistVersionBaseElem extends DistParentElem {
-
- // final static public String AETHER_CATEGORY_BASE = "categoryBase";
- final static public String AETHER_BINARIES_TYPE = "binaries";
- final static public String AETHER_DEP_TYPE = "dep";
- private String type;
- private Node modularDistVersionBase;
-
- public ModularDistVersionBaseElem(WorkspaceElem wkspElem, String name,
- Node modularDistVersionBase, String type) {
- super(name, wkspElem.inHome(), wkspElem.isReadOnly());
- setParent(wkspElem);
- this.modularDistVersionBase = modularDistVersionBase;
- this.type = type;
- }
-
- public Node getModularDistBase() {
- // // TODO clean this
- // if (type.equals(AETHER_CATEGORY_BASE))
- // return modularDistVersionBase;
- // else
- try {
- return modularDistVersionBase.getParent();
- } catch (RepositoryException e) {
- throw new SlcException("unable to get parent node for "
- + modularDistVersionBase, e);
- }
- }
-
- public WorkspaceElem getWkspElem() {
- return (WorkspaceElem) getParent();
- }
-
- /**
- * Override normal behaviour to initialise children only when first
- * requested
- */
- @Override
- public synchronized boolean hasChildren() {
- if (isLoaded()) {
- return super.hasChildren();
- } else {
- return true;
- }
- };
-
- /**
- * Override normal behaviour to initialise children only when first
- * requested
- */
- @Override
- public synchronized Object[] getChildren() {
- if (isLoaded()) {
- return super.getChildren();
- } else {
- try {
- NodeIterator ni = getDistVersions();
- while (ni != null && ni.hasNext()) {
- Node curNode = ni.nextNode();
- if (curNode.hasProperty(SlcNames.SLC_ARTIFACT_VERSION))
- addChild(new ModularDistVersionElem(this, curNode
- .getProperty(SlcNames.SLC_ARTIFACT_VERSION)
- .getString(), curNode));
- }
- return super.getChildren();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to retrieve children for "
- + modularDistVersionBase, re);
- }
- }
- }
-
- private NodeIterator getDistVersions() {
- try {
- // if (AETHER_CATEGORY_BASE.equals(type))
- // return null;
-
- QueryManager queryManager = modularDistVersionBase.getSession()
- .getWorkspace().getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
- Selector source = factory.selector(
- SlcTypes.SLC_MODULAR_DISTRIBUTION,
- SlcTypes.SLC_MODULAR_DISTRIBUTION);
- Constraint constraint = factory.descendantNode(
- source.getSelectorName(), modularDistVersionBase.getPath());
- // Ordering order = factory.descending(factory.propertyValue(
- // source.getSelectorName(), SlcNames.SLC_ARTIFACT_VERSION));
- // Ordering[] orderings = { order };
- QueryObjectModel query = factory.createQuery(source, constraint,
- null, null);
- QueryResult queryResult = query.execute();
- return queryResult.getNodes();
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unable to version for modular distribution: " + getName(),
- e);
- }
- }
-
- public String getType() {
- return type;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import javax.jcr.Node;
-
-/**
- * Abstract a node of type slc:modularDistribution that has a child node that
- * lists the modules contained in the current distribution
- */
-public class ModularDistVersionElem extends DistParentElem {
- private final Node modularDistVersionNode;
-
- public ModularDistVersionElem(ModularDistVersionBaseElem modularDistGroupElem,
- String version, Node modularDistVersionNode) {
- super(version, modularDistGroupElem.inHome(), modularDistGroupElem
- .isReadOnly());
- setParent(modularDistGroupElem);
- this.modularDistVersionNode = modularDistVersionNode;
- }
-
- public Object[] getChildren() {
- return null;
- }
-
- public String getLabel() {
- return getName();
- }
-
- public WorkspaceElem getWorkspaceElem() {
- return (WorkspaceElem) getParent().getParent();
- }
-
- public Node getModularDistVersionNode() {
- return modularDistVersionNode;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import java.security.AccessControlException;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.security.Keyring;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-
-/**
- * Abstract a repository. It might be persisted by a node in the current user
- * home Node or just an URI and a label if user is anonymous
- */
-public class RepoElem extends DistParentElem {
- // private final static CmsLog log = CmsLog.getLog(RepoElem.class);
-
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
- private Credentials credentials;
- private Session defaultSession = null;
-
- // Defines current repo
- private Node repoNode = null;
- private String label;
- private String uri;
-
- private Repository repository;
-
- /**
- * Creates a RepoElement for anonymous user. The {@code RepositoryFactory}
- * is used to enable lazy initialisation
- */
- public RepoElem(RepositoryFactory repoFactory, String uri, String label) {
- super(label);
- this.repositoryFactory = repoFactory;
- this.uri = uri;
- this.label = label;
- }
-
- /**
- * Creates a RepoElement for an authenticated user. The
- * {@code RepositoryFactory} and {@code Keyring} are used to enable lazy
- * initialisation
- *
- */
- public RepoElem(RepositoryFactory repoFactory, Keyring keyring, Node repoNode, String alias) {
- super(alias);
- this.label = alias;
- // label = repoNode.isNodeType(NodeType.MIX_TITLE) ? repoNode
- // .getProperty(Property.JCR_TITLE).getString() : repoNode
- // .getName();
- this.repoNode = repoNode;
- this.repositoryFactory = repoFactory;
- this.keyring = keyring;
- try {
- // Initialize this repo information
- setInHome(RepoConstants.DEFAULT_JAVA_REPOSITORY_ALIAS.equals(repoNode.getName()));
- if (inHome())
- // Directly log and retrieve children for local repository
- login();
- else
- setReadOnly(!repoNode.hasNode(ArgeoNames.ARGEO_PASSWORD));
- uri = JcrUtils.get(repoNode, ArgeoNames.ARGEO_URI);
- } catch (RepositoryException e) {
- throw new SlcException("Unable to " + "initialize repo element", e);
- }
- }
-
- /** Effective login. Does nothing if the session is already there. */
- public void login() {
- if (isConnected())
- return;
-
- if (repository == null)
- if (repoNode == null)
- // Anonymous
- repository = CmsJcrUtils.getRepositoryByUri(repositoryFactory, uri);
- else {
- repository = RepoUtils.getRepository(repositoryFactory, keyring, repoNode);
- credentials = RepoUtils.getRepositoryCredentials(keyring, repoNode);
- }
-
- try {
- // FIXME make it more generic
- String defaultWorkspace = CmsConstants.SYS_WORKSPACE;
- defaultSession = repository.login(credentials, defaultWorkspace);
- refreshChildren();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot login repository " + label + " with credential " + credentials, e);
- }
- }
-
- protected void refreshChildren() {
- try {
- // TODO also remove deleted children (only adds for the time being
- String[] workspaceNames = defaultSession.getWorkspace().getAccessibleWorkspaceNames();
- buildWksp: for (String workspaceName : workspaceNames) {
- if (!isWorkspaceVisible(workspaceName))
- continue buildWksp;
-
- String prefix = getPrefix(workspaceName);
- if (getChildByName(prefix) == null) {
- WkspGroupElem wkspGpElem = new WkspGroupElem(RepoElem.this, prefix);
- addChild(wkspGpElem);
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list workspaces for " + repoNode, e);
- }
- }
-
- @Override
- public synchronized void dispose() {
- JcrUtils.logoutQuietly(defaultSession);
- super.dispose();
- }
-
- private String getPrefix(String workspaceName) {
- // Here is the tricks - we rely on a "hard coded" convention
- // Workspace name should be like: name-major.minor
- if (workspaceName.lastIndexOf(VERSION_SEP) > 0)
- return workspaceName.substring(0, workspaceName.lastIndexOf(VERSION_SEP));
- else
- return workspaceName;
- }
-
- /* Exposes this to the children workspace group */
- protected boolean isWorkspaceVisible(String wkspName) {
- Boolean result = true;
- if (ARGEO_SYSTEM_WKSP.contains(wkspName))
- return false;
- // Add a supplementary check to hide workspace that are not
- // public to anonymous user
- if (repoNode == null) {
- Session tmpSession = null;
- try {
- tmpSession = repository.login(wkspName);
- try {
- tmpSession.checkPermission("/", "read");
- } catch (AccessControlException e) {
- result = false;
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list workspaces for anonymous user", e);
- } finally {
- JcrUtils.logoutQuietly(tmpSession);
- }
- }
- return result;
- }
-
- /**
- * Actual call to the
- * {@link Repository#login(javax.jcr.Credentials, String)} method. To be
- * overridden.
- *
- * Creates a new session with correct credentials using the information
- * contained in the corresponding repo node. It provides all UI children
- * elements an unique entry point to retrieve a new Session. Caller must
- * close the session when it is not in use anymore.
- *
- */
- protected Session repositoryLogin(String workspaceName) {
- try {
- if (workspaceName == null)
- workspaceName = CmsConstants.SYS_WORKSPACE;// FIXME make it more generic
- return repository.login(credentials, workspaceName);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot login repository " + label + " with credential " + credentials, e);
- }
- }
-
- public Boolean isConnected() {
- if (defaultSession != null && defaultSession.isLive())
- return true;
- else
- return false;
- }
-
- /** Exposes URI to the current repository */
- public String getUri() {
- return uri;
- }
-
- public String getRepoNodePath() {
- if (repoNode == null)
- return null;
- else
- try {
- return repoNode.getPath();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get node path for repository " + label, e);
- }
- }
-
- /**
- * Exposes the local repoNode that completely define a connection to a
- * repository (including a set of credentials). Might return null in case of
- * an anonymous user
- */
- protected Node getRepoNode() {
- return repoNode;
- }
-
- protected Repository getRepository() {
- return repository;
- }
-
- protected Credentials getCredentials() {
- return credentials;
- }
-
- // META INFO
- public String getDescription() {
- String desc = label;
- if (repoNode != null)
- desc = label + " (" + uri + ")";
- return desc;
- }
-
- public String getLabel() {
- return label;
- }
-
- public String toString() {
- return repoNode != null ? repoNode.toString() : label;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-
-/**
- * Abstract set of similar workspaces, that is a bunch of workspaces with same
- * prefix.
- */
-public class WkspGroupElem extends DistParentElem {
-
- private Session defaultSession;
-
- public WkspGroupElem(RepoElem repoElem, String prefix) {
- super(prefix, repoElem.inHome(), repoElem.isReadOnly());
- setParent(repoElem);
- // Directly adds children upon creation
- try {
- defaultSession = repoElem.repositoryLogin(null);
- String[] wkpNames = defaultSession.getWorkspace()
- .getAccessibleWorkspaceNames();
- for (String wkpName : wkpNames) {
- if (prefix.equals(getPrefix(wkpName))
- // if (wkpName.startsWith(prefix)
- && repoElem.isWorkspaceVisible(wkpName))
- addChild(new WorkspaceElem(WkspGroupElem.this, repoElem,
- wkpName));
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot retrieve workspace names", e);
- }
- }
-
- // FIXME - we rely on a "hard coded" convention : Workspace name must have
- // this format: name-major.minor
- // We might expose this method as static public, to be used among others by
- // the RepoElem parent objects when building its children
- private String getPrefix(String workspaceName) {
- if (workspaceName.lastIndexOf(VERSION_SEP) > 0)
- return workspaceName.substring(0,
- workspaceName.lastIndexOf(VERSION_SEP));
- else
- return workspaceName;
- }
-
- public void dispose() {
- JcrUtils.logoutQuietly(defaultSession);
- super.dispose();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.model;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.query.InvalidQueryException;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.qom.QueryObjectModel;
-import javax.jcr.query.qom.QueryObjectModelFactory;
-import javax.jcr.query.qom.Selector;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-
-/** Abstract a workspace that contains a software distribution */
-public class WorkspaceElem extends DistParentElem {
- private final RepoElem repoElem;
- private String workspaceName;
- private Session currSession;
-
- public WorkspaceElem(WkspGroupElem parent, RepoElem repoElem,
- String workspaceName) {
- super(workspaceName, repoElem.inHome(), repoElem.isReadOnly());
- this.repoElem = repoElem;
- this.workspaceName = workspaceName;
- setParent(parent);
- }
-
- public String getWorkspaceName() {
- return workspaceName;
- }
-
- public RepoElem getRepoElem() {
- return repoElem;
- }
-
- public Boolean isConnected() {
- if (currSession != null && currSession.isLive())
- return true;
- else
- return false;
- }
-
- public void login() {
- currSession = repoElem.repositoryLogin(getName());
- }
-
- /** Utility to create a new Session with correct credential in this context */
- public Session getNewSession() {
- return repoElem.repositoryLogin(getName());
- }
-
- public boolean hasChildren() {
- try {
- if (isConnected())
- return currSession.getRootNode().hasNodes();
- else
- return true;
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while checking children node existence",
- re);
- }
- }
-
- /** Override normal behaviour to initialize display of the workspace */
- @Override
- public synchronized Object[] getChildren() {
- if (isLoaded()) {
- return super.getChildren();
- } else {
- // initialize current object
- try {
- // Lazy connect the first time we retrieve children
- if (currSession == null)
- login();
-
- // Retrieve already existing distribution
-
- // Use QOM rather than SQL2 - it seems more robust for remoting
- // with JCR 2.2 (might also be some model refresh issue with the
- // remoting)
- QueryManager queryManager = currSession.getWorkspace()
- .getQueryManager();
- QueryObjectModelFactory factory = queryManager.getQOMFactory();
- Selector selector = factory.selector(
- SlcTypes.SLC_MODULAR_DISTRIBUTION,
- SlcTypes.SLC_MODULAR_DISTRIBUTION);
- // Curiously this works...
- // Selector selector = factory.selector(
- // SlcTypes.SLC_JAR_FILE,
- // SlcTypes.SLC_JAR_FILE);
-
- QueryObjectModel query = factory.createQuery(selector, null,
- null, null);
-
- // Query groupQuery = currSession
- // .getWorkspace()
- // .getQueryManager()
- // .createQuery(
- // "select * from ["
- // + SlcTypes.SLC_MODULAR_DISTRIBUTION
- // + "]", Query.JCR_SQL2);
- NodeIterator distributions = null;
- try {
- distributions = query.execute().getNodes();
- } catch (InvalidQueryException iqe) {
- // For legacy only does not throw an exception while
- // browsing
- // legacy repositories that does not know
- // SLC_MODULAR_DISTRIBUTION type
- }
- distribs: while (distributions != null
- && distributions.hasNext()) {
- Node currDist = distributions.nextNode();
- Node distBase = currDist.getParent().getParent();
- if (!distBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE))
- continue distribs;
- String groupId = distBase
- .getProperty(SlcNames.SLC_GROUP_ID).getString();
- String artifactId = distBase.getProperty(
- SlcNames.SLC_ARTIFACT_ID).getString();
-
- String name;
- String type;
- if (ModularDistVersionBaseElem.AETHER_BINARIES_TYPE
- .equals(artifactId)) {
- name = groupId;
- type = ModularDistVersionBaseElem.AETHER_BINARIES_TYPE;
- } else {
- name = artifactId;
- type = ModularDistVersionBaseElem.AETHER_DEP_TYPE;
- }
- if (getChildByName(name) == null)
- addChild(new ModularDistVersionBaseElem(
- WorkspaceElem.this, name, distBase, type));
- }
- return super.getChildren();
- } catch (RepositoryException e) {
- throw new SlcException(
- "Cannot initialize WorkspaceNode UI object."
- + getName(), e);
- }
- }
- }
-
- @Override
- public synchronized void dispose() {
- JcrUtils.logoutQuietly(currSession);
- super.dispose();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.query.Row;
-
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.TableColumn;
-
-/**
- * Centralizes and factorizes useful methods to create and manage tables that
- * display artifacts for both editors and views.
- */
-public class ArtifactsTableConfigurer implements SlcNames, SlcTypes,
- DistConstants {
- // private final static CmsLog log = CmsLog
- // .getLog(ArtifactsTableConfigurer.class);
- // Used in the comparator to be able to retrieve the value from a row
- // knowing the corresponding column index.
- private Map<Integer, String> indexToName = new HashMap<Integer, String>();
-
- private CurrentTableComparator comparator;
- private TableViewer viewer;
-
- protected DateFormat timeFormatter = new SimpleDateFormat(DATE_TIME_FORMAT);
-
- /**
- * Create and initialize the table configurer.
- */
- public ArtifactsTableConfigurer(TableViewer viewer,
- int defaultSortColumnIndex, int direction) {
- this.viewer = viewer;
- comparator = new CurrentTableComparator(defaultSortColumnIndex,
- direction);
- }
-
- public GenericTableComparator getComparator() {
- return comparator;
- }
-
- /**
- * Configure column width and header label depending on the value that will
- * be displayed in the current column.
- *
- * @param jcrColumnName
- * @param column
- * @param columnIndex
- */
- public void configureColumn(String jcrColumnName, TableViewerColumn column,
- int columnIndex) {
-
- if (columnIndex != -1
- && getSelectionAdapter(column.getColumn(), columnIndex) != null) {
- column.getColumn().addSelectionListener(
- getSelectionAdapter(column.getColumn(), columnIndex));
- indexToName.put(new Integer(columnIndex), jcrColumnName);
- }
- Object[] objs = DistUiHelpers
- .getLabelAndDefaultValueWidth(jcrColumnName);
- column.getColumn().setWidth((Integer) objs[1]);
- column.getColumn().setText((String) objs[0]);
- }
-
- /**
- * Might be used by client classes to sort the table with based on selected
- * columns.
- *
- * @param column
- * @param index
- * @return
- */
- public SelectionAdapter getSelectionAdapter(final TableColumn column,
- final int index) {
-
- // A comparator must be define
- if (comparator == null)
- return null;
-
- SelectionAdapter selectionAdapter = new SelectionAdapter() {
- private static final long serialVersionUID = 5239138629878556374L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
-
- try {
-
- comparator.setColumn(index);
- int dir = viewer.getTable().getSortDirection();
- if (viewer.getTable().getSortColumn() == column) {
- dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
- } else {
-
- dir = SWT.DOWN;
- }
- viewer.getTable().setSortDirection(dir);
- viewer.getTable().setSortColumn(column);
- viewer.refresh();
- } catch (Exception exc) {
- exc.printStackTrace();
- }
- }
- };
- return selectionAdapter;
- }
-
- /**
- * provides a label provider that returns the content of a specific cell.
- * Specific treatment is done for some columns when the query returns a code
- * that must be translated to the corresponding value at display time.
- */
- public ColumnLabelProvider getLabelProvider(final String columnName) {
- boolean test = false;
-
- if (test) {
- return new ColumnLabelProvider() {
- private static final long serialVersionUID = 7996387354459551737L;
-
- public String getText(Object element) {
- return null;
- }
-
- public Image getImage(Object element) {
- return null;
- }
- };
- } else
- return new ColumnLabelProvider() {
- private static final long serialVersionUID = 6746632988975282759L;
-
- public String getText(Object element) {
- Row row = (Row) element;
- try {
- return row.getValue(columnName).getString();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot display row " + row, e);
- }
- }
-
- public Image getImage(Object element) {
- return null;
- }
- };
- }
-
- /** Implements comparator for various types of Artifact Table row */
- private class CurrentTableComparator extends GenericTableComparator {
- private static final long serialVersionUID = -4737460932326339442L;
-
- public CurrentTableComparator(int colIndex, int direction) {
- super(colIndex, direction);
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- int rc = 0;
-
- if (e1 instanceof Row) {
- try {
-
- Value v1 = ((Row) e1).getValue(indexToName
- .get(propertyIndex));
- Value v2 = ((Row) e2).getValue(indexToName
- .get(propertyIndex));
-
- if (v1.getType() == PropertyType.STRING)
- rc = v1.getString().compareTo(v2.getString());
- else if (v1.getType() == PropertyType.DATE)
- rc = v1.getDate().compareTo(v2.getDate());
- else
- throw new SlcException("comparator for object type "
- + v1.getType() + " is not yet implemented");
- } catch (Exception e) {
- throw new SlcException("rows cannot be compared ", e);
- }
- } else
- throw new SlcException("Unsupported row type");
- // If descending order, flip the direction
- if (direction == DESCENDING) {
- rc = -rc;
- }
- return rc;
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.Parameterization;
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.menus.CommandContributionItem;
-import org.eclipse.ui.menus.CommandContributionItemParameter;
-import org.eclipse.ui.services.IServiceLocator;
-
-/**
- * Centralizes useful methods to manage command updates
- */
-public class CommandHelpers {
-
- /**
- * Refresh the given command.
- */
- public static void refreshCommand(IMenuManager menuManager,
- IServiceLocator locator, String cmdId, String label, String iconPath,
- boolean showCommand) {
- IContributionItem ici = menuManager.find(cmdId);
- if (ici != null)
- menuManager.remove(ici);
-
- if (showCommand) {
- // Set Params
- CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter(
- locator, null, cmdId, SWT.PUSH);
- contributionItemParameter.label = label;
- contributionItemParameter.icon = DistPlugin.getImageDescriptor(iconPath);
- CommandContributionItem cci = new CommandContributionItem(
- contributionItemParameter);
- cci.setId(cmdId);
- menuManager.add(cci);
- }
- }
-
- /**
- * Refresh the given command and optionally corresponding parameters.
- *
- * @param menuManager
- * @param locator
- * @param cmdId
- * @param label
- * @param showCommand
- * Command must be explicitly removed from the context menu at
- * each refresh setting this to false.
- * @param params
- * maps a paramId with a String value
- */
- public static void refreshParameterizedCommand(IMenuManager menuManager,
- IServiceLocator locator, String cmdId, String label, String iconPath,
- boolean showCommand, Map<String, String> params) {
- IContributionItem ici = menuManager.find(cmdId);
- if (ici != null)
- menuManager.remove(ici);
-
- if (showCommand) {
- // Set Params
- CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter(
- locator, null, cmdId, SWT.PUSH);
- contributionItemParameter.label = label;
- contributionItemParameter.icon = DistPlugin.getImageDescriptor(iconPath);
-
- if (params != null)
- contributionItemParameter.parameters = params;
-
- CommandContributionItem cci = new CommandContributionItem(
- contributionItemParameter);
- cci.setId(cmdId);
- menuManager.add(cci);
- }
- }
-
- /** Helper to call a command without parameter easily */
- public static void callCommand(String commandID) {
- callCommand(commandID, null);
- }
-
- /** Helper to call a command with a single parameter easily */
- public static void callCommand(String commandID, String parameterID,
- String parameterValue) {
- Map<String, String> params = new HashMap<String, String>();
- params.put(parameterID, parameterValue);
- callCommand(commandID, params);
- }
-
- /**
- * Helper to call a command with a map of parameters easily
- *
- * @param paramMap
- * a map that links various commands ids with corresponding
- * String values.
- */
- public static void callCommand(String commandID,
- Map<String, String> paramMap) {
- try {
- IWorkbench iw = DistPlugin.getDefault().getWorkbench();
- IHandlerService handlerService = (IHandlerService) iw
- .getService(IHandlerService.class);
- ICommandService cmdService = (ICommandService) iw
- .getActiveWorkbenchWindow().getService(
- ICommandService.class);
- Command cmd = cmdService.getCommand(commandID);
-
- ArrayList<Parameterization> parameters = null;
- ParameterizedCommand pc;
-
- if (paramMap != null) {
- // Set parameters of the command to launch :
- parameters = new ArrayList<Parameterization>();
- Parameterization parameterization;
- for (String id : paramMap.keySet()) {
- parameterization = new Parameterization(
- cmd.getParameter(id), paramMap.get(id));
- parameters.add(parameterization);
- }
- pc = new ParameterizedCommand(cmd,
- parameters.toArray(new Parameterization[parameters.size()]));
- } else
- pc = new ParameterizedCommand(cmd, null);
-
- // build the parameterized command
- // execute the command
- handlerService.executeCommand(pc, null);
- } catch (Exception e) {
- throw new SlcException(
- "Unexepected exception while opening node editor", e);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import java.math.BigDecimal;
-import java.util.Calendar;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.ValueFormatException;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.argeo.slc.SlcException;
-import org.eclipse.jface.viewers.Viewer;
-
-/** Add ability to order by name version and version */
-public class DistNodeViewerComparator extends GenericTableComparator {
- private static final long serialVersionUID = -5966120108210992211L;
-
- private final static CmsLog log = CmsLog
- .getLog(DistNodeViewerComparator.class);
-
- // Jcr property type goes to 12
- public final static int NAME_VERSION_TYPE = 100;
- public final static int VERSION_TYPE = 101;
-
- protected List<String> propertiesList;
- protected List<Integer> propertyTypesList;
- protected Integer propertyType;
- protected String property;
-
- private NameVersionComparator nvc = new NameVersionComparator();
- private VersionComparator vc = new VersionComparator();
-
- public DistNodeViewerComparator(int defaultColIndex, int defaultDirection,
- List<String> propertiesList, List<Integer> propertyTypesList) {
- super(defaultColIndex, defaultDirection);
- this.propertiesList = propertiesList;
- this.propertyTypesList = propertyTypesList;
- this.propertyIndex = defaultColIndex;
- this.propertyType = propertyTypesList.get(defaultColIndex);
- this.property = propertiesList.get(defaultColIndex);
- setColumn(defaultColIndex);
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- int rc = 0;
- long lc = 0;
-
- try {
- Node n1 = (Node) e1;
- Node n2 = (Node) e2;
-
- Value v1 = null;
- Value v2 = null;
- if (n1.hasProperty(property))
- v1 = n1.getProperty(property).getValue();
- if (n2.hasProperty(property))
- v2 = n2.getProperty(property).getValue();
-
- if (v2 == null && v1 == null)
- return 0;
- else if (v2 == null)
- return -1;
- else if (v1 == null)
- return 1;
-
- switch (propertyType) {
- case NAME_VERSION_TYPE:
- rc = nvc.compare(viewer, v1.getString(), v2.getString());
- break;
- case VERSION_TYPE:
- rc = vc.compare(viewer, v1.getString(), v2.getString());
- break;
- case PropertyType.STRING:
- rc = v1.getString().compareTo(v2.getString());
- break;
- case PropertyType.BOOLEAN:
- boolean b1 = v1.getBoolean();
- boolean b2 = v2.getBoolean();
- if (b1 == b2)
- rc = 0;
- else
- // we assume true is greater than false
- rc = b1 ? 1 : -1;
- break;
- case PropertyType.DATE:
- Calendar c1 = v1.getDate();
- Calendar c2 = v2.getDate();
- if (c1 == null || c2 == null)
- log.trace("undefined date");
- lc = c1.getTimeInMillis() - c2.getTimeInMillis();
- if (lc < Integer.MIN_VALUE)
- // rc = Integer.MIN_VALUE;
- rc = -1;
- else if (lc > Integer.MAX_VALUE)
- // rc = Integer.MAX_VALUE;
- rc = 1;
- else
- rc = (int) lc;
- break;
- case PropertyType.LONG:
- long l1;
- long l2;
- // FIXME sometimes an empty string is set instead of the id
- try {
- l1 = v1.getLong();
- } catch (ValueFormatException ve) {
- l1 = 0;
- }
- try {
- l2 = v2.getLong();
- } catch (ValueFormatException ve) {
- l2 = 0;
- }
-
- lc = l1 - l2;
- if (lc < Integer.MIN_VALUE)
- // rc = Integer.MIN_VALUE;
- rc = -1;
- else if (lc > Integer.MAX_VALUE)
- // rc = Integer.MAX_VALUE;
- rc = 1;
- else
- rc = (int) lc;
- break;
- case PropertyType.DECIMAL:
- BigDecimal bd1 = v1.getDecimal();
- BigDecimal bd2 = v2.getDecimal();
- rc = bd1.compareTo(bd2);
- break;
- default:
- throw new SlcException(
- "Unimplemented comparaison for PropertyType "
- + propertyType);
- }
-
- // If descending order, flip the direction
- if (direction == DESCENDING) {
- rc = -rc;
- }
-
- } catch (RepositoryException re) {
- throw new SlcException("Unexpected error "
- + "while comparing nodes", re);
- }
- return rc;
- }
-
- @Override
- public void setColumn(int column) {
- if (column == this.propertyIndex) {
- // Same column as last sort; toggle the direction
- direction = 1 - direction;
- } else {
- // New column; do a descending sort
- this.propertyIndex = column;
- this.propertyType = propertyTypesList.get(column);
- this.property = propertiesList.get(column);
- direction = ASCENDING;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-
-public class DistUiHelpers implements DistConstants, SlcTypes, SlcNames {
- private final static CmsLog log = CmsLog.getLog(DistUiHelpers.class);
- private final static DateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT);
-
- /**
- * Returns a user-friendly label for a given jcr property name. If the
- * corresponding mapping is not found, the input String is returned. If
- * input String is null "(No name)" is returned
- */
- public static String getLabelJcrName(String jcrName) {
- return (String) getLabelAndDefaultValueWidth(jcrName)[0];
- }
-
- /**
- * Returns a label ( (String) object[0] )and default value width ( (int)
- * object[1] ) for a given property name
- */
- public static Object[] getLabelAndDefaultValueWidth(String propertyName) {
- // to avoid npe :
- if (propertyName == null)
- return new Object[] { "(No name)", 60 };
-
- // ArtifactId
- if (propertyName.equals(SLC_ARTIFACT + "." + SLC_ARTIFACT_ID)
- || propertyName.equals(SLC_ARTIFACT_BASE + "."
- + SLC_ARTIFACT_ID)
- || propertyName.equals(SLC_ARTIFACT_VERSION_BASE + "."
- + SLC_ARTIFACT_ID)
- || propertyName.equals(SLC_ARTIFACT_ID)) {
- return new Object[] { "Artifact ID", 200 };
- } // GroupId
- else if (propertyName.equals(SLC_ARTIFACT + "." + SLC_GROUP_ID)
- || propertyName.equals(SLC_ARTIFACT_BASE + "." + SLC_GROUP_ID)
- || propertyName.equals(SLC_ARTIFACT_VERSION_BASE + "."
- + SLC_GROUP_ID) || propertyName.equals(SLC_GROUP_ID)) {
- return new Object[] { "Group ID", 120 };
- } // Version
- else if (propertyName.equals(SLC_ARTIFACT + "." + SLC_ARTIFACT_VERSION)
- || propertyName.equals(SLC_ARTIFACT_VERSION_BASE + "."
- + SLC_ARTIFACT_VERSION)
- || propertyName.equals(SLC_ARTIFACT_VERSION)) {
- return new Object[] { "Version", 60 };
- } else if (propertyName.equals(SLC_ARTIFACT + "."
- + SLC_ARTIFACT_CLASSIFIER)
- || propertyName.equals(SLC_ARTIFACT_CLASSIFIER)) {
- return new Object[] { "Classifier", 60 };
- } else if (propertyName.equals(SLC_ARTIFACT + "."
- + SLC_ARTIFACT_EXTENSION)
- || propertyName.equals(SLC_ARTIFACT_EXTENSION)) {
- return new Object[] { "Type", 40 };
- } else if (propertyName.equals(SLC_BUNDLE_ARTIFACT + "."
- + SLC_SYMBOLIC_NAME)
- || propertyName.equals(SLC_SYMBOLIC_NAME)) {
- return new Object[] { "Symbolic name", 180 };
- } else if (propertyName.equals(SLC_BUNDLE_ARTIFACT + "."
- + SLC_BUNDLE_VERSION)
- || propertyName.equals(SLC_BUNDLE_VERSION)) {
- return new Object[] { "Bundle version", 120 };
- } else if (propertyName
- .equals(SLC_BUNDLE_ARTIFACT + "." + SLC_MANIFEST)
- || propertyName.equals(SLC_MANIFEST)) {
- return new Object[] { "Manifest", 60 };
- } // TODO remove hard coded strings
- else if (propertyName.equals("slc:Bundle-ManifestVersion")) {
- return new Object[] { "Bundle Manifest Version", 60 };
- } else if (propertyName.equals("slc:Manifest-Version")) {
- return new Object[] { "Manifest Version", 60 };
- } else if (propertyName.equals("slc:Bundle-Vendor")) {
- return new Object[] { "Bundle Vendor", 60 };
- } else if (propertyName.equals("slc:Bundle-SymbolicName")) {
- return new Object[] { "Bundle symbolic name", 60 };
- } else if (propertyName.equals("slc:Bundle-Name")) {
- return new Object[] { "Bundle name", 60 };
- } else if (propertyName.equals("slc:Bundle-DocURL")) {
- return new Object[] { "Doc URL", 120 };
- } else if (propertyName.equals("slc:Bundle-Licence")) {
- return new Object[] { "Bundle licence", 120 };
- } else if (propertyName.equals(SLC_ARTIFACT_VERSION_BASE + "."
- + JCR_IDENTIFIER)) {
- return new Object[] { "UUID", 0 };
- } else {
- if (log.isTraceEnabled())
- log.trace("No Column label provider defined for property: ["
- + propertyName + "]");
- return new Object[] { propertyName, 60 };
- }
- }
-
- public static String formatValueAsString(Value value) {
- try {
- String strValue;
-
- if (value.getType() == PropertyType.BINARY)
- strValue = "<binary>";
- else if (value.getType() == PropertyType.DATE)
- strValue = df.format(value.getDate().getTime());
- else
- strValue = value.getString();
- return strValue;
- } catch (RepositoryException e) {
- throw new SlcException("unexpected error while formatting value",
- e);
- }
- }
-
- public static String formatAsString(Object value) {
- String strValue;
- if (value instanceof Calendar)
- strValue = df.format(((Calendar) value).getTime());
- else
- strValue = value.toString();
- return strValue;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.events.IHyperlinkListener;
-
-/** Convenience class to reduce the number of methods to implement */
-public abstract class HyperlinkAdapter implements IHyperlinkListener {
-
- public void linkEntered(HyperlinkEvent e) {
- }
-
- public void linkExited(HyperlinkEvent e) {
- }
-
- /** Must be overriden **/
- public abstract void linkActivated(HyperlinkEvent e);
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-
-/**
- * Enable comparison of two names version string with form org.argeo.slc-1.2.x.
- * with following rules and assumptions:
- * <ul>
- * <li>
- * Names are ordered using Lexicographical order</li>
- * <li>
- * Version are parsed and compared segment by segment; doing best effort to
- * convert major, minor and micro to integer and compare them as such (to have
- * 0.1 < 0.9 < 0.10 not 0.1 < 0.10 < 0.9).</li>
- * <li>Version should not contain any dash (-), version segments should be
- * separated by dots (.)</li>
- * </ul>
- */
-
-public class NameVersionComparator extends ViewerComparator {
- private static final long serialVersionUID = 8290130681918221197L;
-
- private VersionComparator vc = new VersionComparator();
-
- @Override
- public int category(Object element) {
- if (element instanceof String) {
- int lastInd = ((String) element).lastIndexOf('-');
- if (lastInd > 0)
- return 10;
- }
- // unvalid names always last
- return 5;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- int cat1 = category(e1);
- int cat2 = category(e2);
-
- if (cat1 != cat2) {
- return cat1 - cat2;
- }
-
- int result = 0;
-
- String s1, s2;
-
- if (e1 instanceof TreeParent) {
- s1 = ((TreeParent) e1).getName();
- s2 = ((TreeParent) e2).getName();
- } else {
- s1 = e1.toString();
- s2 = e2.toString();
- }
-
- int i1 = s1.lastIndexOf('-');
- int i2 = s2.lastIndexOf('-');
-
- // Specific cases, unvalid Strings
- if (i1 < 0)
- if (i2 < 0)
- return s1.compareTo(s2);
- else
- return 1;
- else if (i2 < 0)
- return -1;
-
- String aName = s1.substring(0, s1.lastIndexOf('-'));
- String aVersion = s1.substring(s1.lastIndexOf('-'));
-
- String bName = s2.substring(0, s2.lastIndexOf('-'));
- String bVersion = s2.substring(s2.lastIndexOf('-'));
-
- result = aName.compareTo(bName);
- if (result != 0)
- return result;
- else
- return vc.compare(viewer, aVersion, bVersion);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-
-/**
- * Enable comparison of two version string with form "1.2.5.qualifier" with
- * following rules and assumptions:
- * <ul>
- * <li>
- * Version are parsed and compared segment by segment; doing best effort to
- * convert major, minor and micro to integer and compare them as such (to have
- * 0.1 < 0.9 < 0.10 not 0.1 < 0.10 < 0.9).</li>
- * <li>Version should not contain any dash (-), version segments should be
- * separated by dots (.)</li>
- * </ul>
- */
-
-public class VersionComparator extends ViewerComparator {
- private static final long serialVersionUID = 3760077835650538982L;
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- String s1 = (String) e1;
- String s2 = (String) e2;
- return compareVersion(s1, s2);
- }
-
- /**
- * Enable comparison of two versions of the form
- * "major.minor.micro.qualifier". We assume the separator is always a "."
- * and make best effort to convert major, minor and micro to int.
- */
- private int compareVersion(String v1, String v2) {
- String[] t1 = v1.split("\\.");
- String[] t2 = v2.split("\\.");
-
- for (int i = 0; i < t1.length && i < t2.length; i++) {
- int result = compareToken(t1[i], t2[i]);
- if (result != 0)
- return result;
- }
- if (t1.length > t2.length)
- return 1;
- else if (t1.length < t2.length)
- return -1;
- else
- return 0;
- }
-
- private int compareToken(String t1, String t2) {
- if (t1 == null && t2 == null)
- return 0;
- else if (t1 == null)
- return -1;
- else if (t2 == null)
- return 1;
-
- Integer i1 = null, i2 = null;
- try {
- i1 = new Integer(t1);
- i2 = new Integer(t2);
- } catch (NumberFormatException nfe) {
- // the format is not valid we silently compare as String
- return t1.compareTo(t2);
- }
- return i1.compareTo(i2);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.utils;
-
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TreeColumn;
-
-/** Useful methods to manage table to display nodes list. */
-public class ViewerUtils {
-
- /**
- * Creates a basic column for the given table. For the time being, we do not
- * support moveable columns.
- */
- public static TableColumn createColumn(Table parent, String name,
- int style, int width) {
- TableColumn result = new TableColumn(parent, style);
- result.setText(name);
- result.setWidth(width);
- result.setResizable(true);
- return result;
- }
-
- /**
- * Creates a TableViewerColumn for the given viewer. For the time being, we
- * do not support moveable columns.
- */
- public static TableViewerColumn createTableViewerColumn(TableViewer parent,
- String name, int style, int width) {
- TableViewerColumn tvc = new TableViewerColumn(parent, style);
- final TableColumn column = tvc.getColumn();
- column.setText(name);
- column.setWidth(width);
- column.setResizable(true);
- return tvc;
- }
-
- /**
- * Creates a TreeViewerColumn for the given viewer. For the time being, we
- * do not support moveable columns.
- */
- public static TreeViewerColumn createTreeViewerColumn(TreeViewer parent,
- String name, int style, int width) {
- TreeViewerColumn tvc = new TreeViewerColumn(parent, style);
- final TreeColumn column = tvc.getColumn();
- column.setText(name);
- column.setWidth(width);
- column.setResizable(true);
- return tvc;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryResult;
-import javax.jcr.query.Row;
-import javax.jcr.query.RowIterator;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.utils.ArtifactsTableConfigurer;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.part.ViewPart;
-
-/** Factorizes useful methods to build a query view in a sashForm */
-public abstract class AbstractQueryArtifactsView extends ViewPart implements
- SlcTypes {
- private static final CmsLog log = CmsLog
- .getLog(AbstractQueryArtifactsView.class);
-
- // shortcuts
- final protected static String SAVB = "[" + SLC_ARTIFACT_VERSION_BASE + "]";
- final protected static String SBA = "[" + SLC_BUNDLE_ARTIFACT + "]";
- final protected static String SIP = "[" + SLC_IMPORTED_PACKAGE + "]";
- final protected static String SEP = "[" + SLC_EXPORTED_PACKAGE + "]";
-
- /* DEPENDENCY INJECTION */
- private Session session;
- private List<String> columnProperties;
-
- // This page widgets
- private TableViewer viewer;
- private List<TableViewerColumn> tableViewerColumns = new ArrayList<TableViewerColumn>();
- private ArtifactsTableConfigurer tableConfigurer;
- private GenericTableComparator comparator;
-
- // to be set by client to display all columns
- private boolean displayAllColumns = false;
-
- protected void createResultPart(Composite parent) {
- viewer = new TableViewer(parent);
- Table table = viewer.getTable();
- table.getParent().setLayout(new GridLayout(1, false));
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- viewer.getTable().setHeaderVisible(true);
- viewer.getTable().setLinesVisible(true);
-
- viewer.setLabelProvider(new ViewLabelProvider());
- viewer.setContentProvider(new ViewContentProvider());
- // viewer.addDoubleClickListener(new GenericDoubleClickListener());
-
- tableConfigurer = new ArtifactsTableConfigurer(viewer, 1,
- GenericTableComparator.DESCENDING);
-
- comparator = tableConfigurer.getComparator();
- viewer.setComparator(comparator);
- }
-
- protected void executeQuery(String statement) {
- try {
- Calendar stStamp = new GregorianCalendar();
- if (log.isDebugEnabled()) {
- log.debug("Executed query: " + statement);
- }
- QueryResult qr = session.getWorkspace().getQueryManager()
- .createQuery(statement, Query.JCR_SQL2).execute();
-
- if (log.isDebugEnabled()) {
- Calendar enStamp = new GregorianCalendar();
- long duration = enStamp.getTimeInMillis()
- - stStamp.getTimeInMillis();
- log.debug("Query executed in : " + duration / 1000 + "s.");
- }
-
- // remove previous columns
- for (TableViewerColumn tvc : tableViewerColumns)
- tvc.getColumn().dispose();
-
- // If a pre(-defined list of columns has been injected, we use it,
- // otherwise we display all results of the resultSet
- if (!displayAllColumns && columnProperties != null) {
- int i = 0;
-
- Iterator<String> it = columnProperties.iterator();
- while (it.hasNext()) {
- String columnName = it.next();
-
- TableViewerColumn tvc = new TableViewerColumn(viewer,
- SWT.NONE);
- tableConfigurer.configureColumn(columnName, tvc, i);
- tvc.setLabelProvider(tableConfigurer
- .getLabelProvider(columnName));
- tableViewerColumns.add(tvc);
- i++;
- }
- } else {
- int i = 0;
- for (final String columnName : qr.getColumnNames()) {
- TableViewerColumn tvc = new TableViewerColumn(viewer,
- SWT.NONE);
- // Small hack to remove prefix from the column name
- // String tmpStr = columnName.substring(columnName
- // .lastIndexOf(".") + 1);
- tableConfigurer.configureColumn(columnName, tvc, i);
- tvc.setLabelProvider(tableConfigurer
- .getLabelProvider(columnName));
- tableViewerColumns.add(tvc);
- i++;
- }
- }
- // We must create a local list because query result can be read only
- // once.
- try {
- List<Row> rows = new ArrayList<Row>();
- RowIterator rit = qr.getRows();
- while (rit.hasNext()) {
- rows.add(rit.nextRow());
- }
- viewer.setInput(rows);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot read query result", e);
- }
-
- } catch (RepositoryException e) {
- ErrorDialog.openError(null, "Error", "Cannot execute JCR query: "
- + statement, new Status(IStatus.ERROR,
- "org.argeo.eclipse.ui.jcr", e.getMessage()));
- }
- }
-
- /**
- * Client must use this method to display all columns of the result set
- * instead of a limited predifined and injected set
- **/
- public void displayAllColumns(boolean flag) {
- displayAllColumns = flag;
- }
-
- // Can be overridden by subclasses.
- protected String generateSelectStatement() {
- StringBuffer sb = new StringBuffer("select " + SAVB + ".* ");
- return sb.toString();
- }
-
- protected String generateFromStatement() {
- StringBuffer sb = new StringBuffer(" from ");
- sb.append(SAVB);
- sb.append(" ");
- return sb.toString();
- }
-
- // Providers
- protected class ViewContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = 5286293288979552056L;
-
- public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
- }
-
- public void dispose() {
- }
-
- @SuppressWarnings("unchecked")
- public Object[] getElements(Object obj) {
- return ((List<String[]>) obj).toArray();
- }
- }
-
- protected class ViewLabelProvider extends LabelProvider implements
- ITableLabelProvider {
- private static final long serialVersionUID = -2407263563879116348L;
-
- public String getColumnText(Object obj, int index) {
- if (!(obj instanceof String[]))
- return "Object is not properly formatted ";
-
- String[] value = (String[]) obj;
-
- return value[index];
- }
-
- public Image getColumnImage(Object obj, int index) {
- return null;
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setSession(Session session) {
- this.session = session;
- }
-
- public void setColumnProperties(List<String> columnProperties) {
- this.columnProperties = columnProperties;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeComparator;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeDoubleClickListener;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeLabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Browse, manipulate and manage distributions accross multiple repositories
- * (like fetch, merge, publish, etc.).
- */
-public class AnonymousDistributionsView extends ViewPart implements SlcNames,
- ArgeoNames {
- // private final static CmsLog log = CmsLog
- // .getLog(AnonymousDistributionsView.class);
- public final static String ID = DistPlugin.PLUGIN_ID
- + ".anonymousDistributionsView";
-
- /* DEPENDENCY INJECTION */
- private ITreeContentProvider treeContentProvider;
-
- // This view widgets
- private TreeViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- // Define the TableViewer
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.FULL_SELECTION | SWT.BORDER);
-
- TreeViewerColumn col = new TreeViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(400);
- col.setLabelProvider(new DistTreeLabelProvider());
-
- final Tree tree = viewer.getTree();
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
-
- // viewer.setContentProvider(new DistTreeContentProvider());
- viewer.setContentProvider(treeContentProvider);
- viewer.addDoubleClickListener(new DistTreeDoubleClickListener(viewer));
- viewer.setComparator(new DistTreeComparator());
-
- // Initialize
- refresh();
- }
-
- /**
- * Force refresh of the whole view
- */
- public void refresh() {
- Object[] ee = viewer.getExpandedElements();
- viewer.setInput(DistConstants.DEFAULT_PUBLIC_REPOSITORY_URI);
- // viewer.expandToLevel(2);
- viewer.setExpandedElements(ee);
- }
-
- @Override
- public void setFocus() {
- viewer.getTree().setFocus();
- }
-
- /*
- * DEPENDENCY INJECTION
- */
- public void setTreeContentProvider(ITreeContentProvider treeContentProvider) {
- this.treeContentProvider = treeContentProvider;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.controllers.ArtifactsTreeContentProvider;
-import org.argeo.slc.repo.RepoConstants;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Basic View to browse a maven based repository.
- *
- * By Default size of the various bundles is not computed but it can be
- * activated the view command.
- */
-
-public class ArtifactsBrowser extends ViewPart implements DistConstants,
- RepoConstants {
- // private final static CmsLog log = CmsLog.getLog(ArtifactsBrowser.class);
- public final static String ID = DistPlugin.PLUGIN_ID + ".artifactsBrowser";
-
- /* DEPENDENCY INJECTION */
- private Session jcrSession;
-
- // Business objects
- private Node rootNode;
-
- // This page widgets
- private TreeViewer artifactTreeViewer;
- private boolean isSizeVisible = false;
-
- // To be able to configure columns easily
- public static final int COLUMN_TREE = 0;
- public static final int COLUMN_DATE = 1;
- public static final int COLUMN_SIZE = 2;
- private static final int SIZE_COL_WIDTH = 55;
-
- @Override
- public void createPartControl(Composite parent) {
- // Enable the different parts to fill the whole page when the tab is
- // maximized
- parent.setLayout(new FillLayout());
- artifactTreeViewer = createArtifactsTreeViewer(parent);
-
- // context menu : it is completely defined in the plugin.xml file.
- // Nothing in the context menu for the time being
- // MenuManager menuManager = new MenuManager();
- // Menu menu =
- // menuManager.createContextMenu(artifactTreeViewer.getTree());
- // artifactTreeViewer.getTree().setMenu(menu);
- // getSite().registerContextMenu(menuManager, artifactTreeViewer);
-
- getSite().setSelectionProvider(artifactTreeViewer);
- // packagesViewer.setComparer(new NodeViewerComparer());
-
- // Model initialisation
- if (jcrSession != null) {
- try {
- rootNode = jcrSession.getNode(DEFAULT_ARTIFACTS_BASE_PATH);
- artifactTreeViewer.setInput(rootNode);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot load base artifact nodes", e);
- }
- }
- }
-
- protected TreeViewer createArtifactsTreeViewer(Composite parent) {
- int style = SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION;
- Tree tree = new Tree(parent, style);
- createColumn(tree, "Artifacts", SWT.LEFT, 300);
- createColumn(tree, "Date created", SWT.LEFT, 105);
- createColumn(tree, "Size", SWT.RIGHT, 0);
- tree.setLinesVisible(true);
- tree.setHeaderVisible(true);
-
- TreeViewer viewer = new TreeViewer(tree);
-
- viewer.setContentProvider(new ArtifactsTreeContentProvider());
- viewer.setLabelProvider(new ArtifactLabelProvider());
- viewer.addSelectionChangedListener(new ArtifactTreeSelectionListener());
- // viewer.addDoubleClickListener(new GenericDoubleClickListener());
- viewer.setInput(rootNode);
-
- return viewer;
- }
-
- private static TreeColumn createColumn(Tree parent, String name, int style,
- int width) {
- TreeColumn result = new TreeColumn(parent, style);
- result.setText(name);
- result.setWidth(width);
- result.setMoveable(true);
- result.setResizable(true);
- return result;
- }
-
- protected TreeViewer getArtifactTreeViewer() {
- return artifactTreeViewer;
- }
-
- @Override
- public void setFocus() {
- // TODO Auto-generated method stub
-
- }
-
- /**
- * Refresh the given element of the tree browser. If null is passed as a
- * parameter, it refreshes the whole tree
- */
- public void refresh(Object element) {
- if (element == null) {
- artifactTreeViewer.refresh(rootNode);
- } else
- artifactTreeViewer.refresh(element);
- }
-
- /** Returns wether size column is visible or not */
- public boolean isSizeVisible() {
- return isSizeVisible;
- }
-
- /** Sets the visibility of the size column */
- public void setSizeVisible(boolean visible) {
- if (isSizeVisible == visible)
- return; // nothing has changed
- else
- isSizeVisible = visible;
-
- if (visible) {
- artifactTreeViewer.getTree().getColumn(COLUMN_SIZE)
- .setWidth(SIZE_COL_WIDTH);
- } else {
- // we just hide the column, we don't refresh the whole tree.
- artifactTreeViewer.getTree().getColumn(COLUMN_SIZE).setWidth(0);
- }
- }
-
- private class ArtifactLabelProvider extends ColumnLabelProvider implements
- DistConstants, SlcTypes {
- private static final long serialVersionUID = 7516705499556141806L;
-
- // Utils
- protected DateFormat timeFormatter = new SimpleDateFormat(
- DATE_TIME_FORMAT);
-
- public void update(ViewerCell cell) {
- int colIndex = cell.getColumnIndex();
- Object element = cell.getElement();
- cell.setText(getColumnText(element, colIndex));
-
- if (element instanceof Node && colIndex == 0) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SLC_ARTIFACT_BASE))
- cell.setImage(DistImages.IMG_ARTIFACT_BASE);
- else if (node.isNodeType(SLC_ARTIFACT_VERSION_BASE))
- cell.setImage(DistImages.IMG_ARTIFACT_VERSION_BASE);
- } catch (RepositoryException e) {
- // Silent
- }
- }
- }
-
- @Override
- public Image getImage(Object element) {
-
- if (element instanceof Node) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SLC_ARTIFACT_BASE)) {
- return DistImages.IMG_ARTIFACT_BASE;
- } else if (node.isNodeType(SLC_ARTIFACT_VERSION_BASE)) {
- return DistImages.IMG_ARTIFACT_VERSION_BASE;
- }
- } catch (RepositoryException e) {
- // Silent
- }
- }
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex) {
- try {
- if (element instanceof Node) {
- Node node = (Node) element;
- switch (columnIndex) {
- case COLUMN_TREE:
- return node.getName();
- case COLUMN_SIZE:
- if (isSizeVisible) {
- long size = JcrUtils.getNodeApproxSize(node) / 1024;
- if (size > 1024)
- return size / 1024 + " MB";
- else
- return size + " KB";
- } else
- return "";
- case COLUMN_DATE:
- if (node.hasProperty(Property.JCR_CREATED))
- return timeFormatter.format(node
- .getProperty(Property.JCR_CREATED)
- .getDate().getTime());
- else
- return null;
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexepected error while getting property values", re);
- }
- return null;
- }
-
- // private String formatValueAsString(Value value) {
- // // TODO enhance this method
- // try {
- // String strValue;
- //
- // if (value.getType() == PropertyType.BINARY)
- // strValue = "<binary>";
- // else if (value.getType() == PropertyType.DATE)
- // strValue = timeFormatter.format(value.getDate().getTime());
- // else
- // strValue = value.getString();
- // return strValue;
- // } catch (RepositoryException e) {
- // throw new SlcException(
- // "unexpected error while formatting value", e);
- // }
- // }
- }
-
- private class ArtifactTreeSelectionListener implements
- ISelectionChangedListener {
-
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- if (selection != null && selection instanceof IStructuredSelection) {
- IStructuredSelection iss = (IStructuredSelection) selection;
- if (iss.size() == 1) {
- artifactTreeViewer.refresh(iss.getFirstElement());
- }
- }
-
- }
-
- }
-
- /* DEPENDENCY INJECTION */
- public void setJcrSession(Session jcrSession) {
- this.jcrSession = jcrSession;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.commands.CopyLocalJavaWorkspace;
-import org.argeo.slc.client.ui.dist.commands.CopyWorkspace;
-import org.argeo.slc.client.ui.dist.commands.CreateLocalJavaWorkspace;
-import org.argeo.slc.client.ui.dist.commands.CreateWorkspace;
-import org.argeo.slc.client.ui.dist.commands.DeleteWorkspace;
-import org.argeo.slc.client.ui.dist.commands.DisplayRepoInformation;
-import org.argeo.slc.client.ui.dist.commands.Fetch;
-import org.argeo.slc.client.ui.dist.commands.NormalizeDistribution;
-import org.argeo.slc.client.ui.dist.commands.NormalizeWorkspace;
-import org.argeo.slc.client.ui.dist.commands.OpenGenerateBinariesWizard;
-import org.argeo.slc.client.ui.dist.commands.PublishWorkspace;
-import org.argeo.slc.client.ui.dist.commands.RegisterRepository;
-import org.argeo.slc.client.ui.dist.commands.RunInOsgi;
-import org.argeo.slc.client.ui.dist.commands.UnregisterRemoteRepo;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeComparator;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeComparer;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeContentProvider;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeDoubleClickListener;
-import org.argeo.slc.client.ui.dist.controllers.DistTreeLabelProvider;
-import org.argeo.slc.client.ui.dist.model.DistParentElem;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionBaseElem;
-import org.argeo.slc.client.ui.dist.model.ModularDistVersionElem;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.client.ui.dist.model.WkspGroupElem;
-import org.argeo.slc.client.ui.dist.model.WorkspaceElem;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * Browse, manipulate and manage distributions across multiple repositories
- * (like fetch, merge, publish, etc.).
- */
-public class DistributionsView extends ViewPart implements SlcNames, ArgeoNames {
- // private final static Log log =
- // LogFactory.getLog(DistributionsView.class);
-
- public final static String ID = DistPlugin.PLUGIN_ID + ".distributionsView";
-
- /* DEPENDENCY INJECTION */
- private Repository nodeRepository;
- private DistTreeContentProvider treeContentProvider;
-
- private TreeViewer viewer;
-
- @Override
- public void createPartControl(Composite parent) {
- // Define the TableViewer
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.FULL_SELECTION | SWT.BORDER);
-
- TreeViewerColumn col = new TreeViewerColumn(viewer, SWT.NONE);
- col.getColumn().setWidth(400);
- col.setLabelProvider(new DistTreeLabelProvider());
-
- final Tree tree = viewer.getTree();
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
-
- // viewer.setContentProvider(new DistTreeContentProvider());
- viewer.setContentProvider(treeContentProvider);
- viewer.addDoubleClickListener(new DistTreeDoubleClickListener(viewer));
- viewer.setComparer(new DistTreeComparer());
- viewer.setComparator(new DistTreeComparator());
-
- @SuppressWarnings("unused")
- ViewerComparator vc = viewer.getComparator();
-
- // Enable retrieving current tree selected items from outside the view
- getSite().setSelectionProvider(viewer);
-
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(viewer.getTree());
- menuManager.addMenuListener(new IMenuListener() {
- private static final long serialVersionUID = -1454108001335038652L;
-
- public void menuAboutToShow(IMenuManager manager) {
- contextMenuAboutToShow(manager);
- }
- });
- viewer.getTree().setMenu(menu);
- getSite().registerContextMenu(menuManager, viewer);
-
- // Initialize
- refresh();
- }
-
- /** Programatically configure the context menu */
- protected void contextMenuAboutToShow(IMenuManager menuManager) {
- IWorkbenchWindow window = DistPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
-
- // Most of the implemented commands support only one selected
- // element
- boolean singleElement = ((IStructuredSelection) viewer.getSelection())
- .size() == 1;
- // Get Current selected item :
- Object firstElement = ((IStructuredSelection) viewer.getSelection())
- .getFirstElement();
-
- try {
-
- if (firstElement instanceof TreeParent
- || firstElement instanceof DistParentElem) {
-
- String targetRepoPath = null, workspaceName = null, workspacePrefix = null;
- String modularDistBasePath = null;
- String modularDistPath = null;
- // String targetRepoUri = null;
- // Build conditions depending on element type
- boolean isDistribElem = false, isModularDistVersionBaseElem = false, isRepoElem = false, isDistribGroupElem = false;
- boolean isLocal = false, isReadOnly = true;
-
- RepoElem re = null;
-
- if (firstElement instanceof RepoElem) {
- re = (RepoElem) firstElement;
- isRepoElem = true;
- isLocal = re.inHome();
- isReadOnly = re.isReadOnly();
- } else if (firstElement instanceof WkspGroupElem) {
- WkspGroupElem wge = (WkspGroupElem) firstElement;
- isReadOnly = wge.isReadOnly();
- isDistribGroupElem = true;
- re = (RepoElem) wge.getParent();
- workspacePrefix = wge.getName();
- } else if (firstElement instanceof WorkspaceElem) {
- WorkspaceElem we = (WorkspaceElem) firstElement;
- re = we.getRepoElem();
- isDistribElem = true;
- isReadOnly = we.isReadOnly();
- workspaceName = we.getWorkspaceName();
- isLocal = we.inHome();
- } else if (firstElement instanceof ModularDistVersionBaseElem) {
- ModularDistVersionBaseElem mdbe = (ModularDistVersionBaseElem) firstElement;
- isModularDistVersionBaseElem = true;
- re = mdbe.getWkspElem().getRepoElem();
- isLocal = re.inHome();
- isReadOnly = re.isReadOnly();
- workspaceName = mdbe.getWkspElem().getWorkspaceName();
- modularDistBasePath = mdbe.getModularDistBase().getPath();
- } else if (firstElement instanceof ModularDistVersionElem) {
- ModularDistVersionElem mdbe = (ModularDistVersionElem) firstElement;
- re = mdbe.getWorkspaceElem().getRepoElem();
- isLocal = re.inHome();
- isReadOnly = re.isReadOnly();
- workspaceName = mdbe.getWorkspaceElem().getWorkspaceName();
- modularDistPath = mdbe.getModularDistVersionNode()
- .getPath();
- }
-
- if (re != null) {
- targetRepoPath = re.getRepoNodePath();
- }
-
- // Display repo info
- CommandUtils.refreshCommand(menuManager, window,
- DisplayRepoInformation.ID,
- DisplayRepoInformation.DEFAULT_LABEL,
- DisplayRepoInformation.DEFAULT_ICON, isRepoElem
- && singleElement);
-
- // create workspace
- Map<String, String> params = new HashMap<String, String>();
- params.put(CreateWorkspace.PARAM_TARGET_REPO_PATH,
- targetRepoPath);
- params.put(CreateWorkspace.PARAM_WORKSPACE_PREFIX,
- workspacePrefix);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- CreateWorkspace.ID, CreateWorkspace.DEFAULT_LABEL,
- CreateWorkspace.DEFAULT_ICON,
- (isRepoElem || isDistribGroupElem) && singleElement
- && !isReadOnly && !isLocal, params);
-
- // TODO Manage the case where it is not a java workspace
- params = new HashMap<String, String>();
- params.put(CreateLocalJavaWorkspace.PARAM_WORKSPACE_PREFIX,
- workspacePrefix);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- CreateLocalJavaWorkspace.ID,
- CreateLocalJavaWorkspace.DEFAULT_LABEL,
- CreateLocalJavaWorkspace.DEFAULT_ICON,
- (isRepoElem || isDistribGroupElem) && singleElement
- && !isReadOnly && isLocal, params);
-
- // Register a remote repository
- CommandUtils.refreshCommand(menuManager, window,
- RegisterRepository.ID,
- RegisterRepository.DEFAULT_LABEL,
- RegisterRepository.DEFAULT_ICON, isRepoElem
- && singleElement);
-
- // Unregister a remote repository
- params = new HashMap<String, String>();
- params.put(UnregisterRemoteRepo.PARAM_REPO_PATH, targetRepoPath);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- UnregisterRemoteRepo.ID,
- UnregisterRemoteRepo.DEFAULT_LABEL,
- UnregisterRemoteRepo.DEFAULT_ICON, isRepoElem
- && !isLocal && singleElement, params);
-
- // Fetch repository
- params = new HashMap<String, String>();
- params.put(Fetch.PARAM_TARGET_REPO_PATH, targetRepoPath);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- Fetch.ID, Fetch.DEFAULT_LABEL, Fetch.DEFAULT_ICON,
- isRepoElem && isLocal && singleElement && !isReadOnly,
- params);
-
- // Normalize workspace
- params = new HashMap<String, String>();
- params.put(NormalizeWorkspace.PARAM_TARGET_REPO_PATH,
- targetRepoPath);
- params.put(NormalizeWorkspace.PARAM_WORKSPACE_NAME,
- workspaceName);
-
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- NormalizeWorkspace.ID, "Normalize...",
- NormalizeWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && !isReadOnly, params);
-
- // Copy workspace
- params = new HashMap<String, String>();
- params.put(CopyWorkspace.PARAM_TARGET_REPO_PATH, targetRepoPath);
- params.put(CopyWorkspace.PARAM_SOURCE_WORKSPACE_NAME,
- workspaceName);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- CopyWorkspace.ID, CopyWorkspace.DEFAULT_LABEL,
- CopyWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && !isLocal, params);
-
- params = new HashMap<String, String>();
- params.put(CopyLocalJavaWorkspace.PARAM_SOURCE_WORKSPACE_NAME,
- workspaceName);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- CopyLocalJavaWorkspace.ID,
- CopyLocalJavaWorkspace.DEFAULT_LABEL,
- CopyLocalJavaWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && isLocal, params);
-
- // Clear Workspace
- params = new HashMap<String, String>();
- params.put(DeleteWorkspace.PARAM_TARGET_REPO_PATH,
- targetRepoPath);
- params.put(DeleteWorkspace.PARAM_WORKSPACE_NAME, workspaceName);
- CommandUtils.refreshParameterizedCommand(menuManager, window,
- DeleteWorkspace.ID, DeleteWorkspace.DEFAULT_LABEL,
- DeleteWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && !isReadOnly, params);
-
- // Advanced submenu
- MenuManager submenu = new MenuManager("Advanced",
- DistPlugin.PLUGIN_ID + ".advancedSubmenu");
- IContributionItem ici = menuManager.find(DistPlugin.PLUGIN_ID
- + ".advancedSubmenu");
- if (ici != null)
- menuManager.remove(ici);
-
- // Publish workspace
- params = new HashMap<String, String>();
- params.put(PublishWorkspace.PARAM_TARGET_REPO_PATH,
- targetRepoPath);
- params.put(PublishWorkspace.PARAM_WORKSPACE_NAME, workspaceName);
- CommandUtils.refreshParameterizedCommand(submenu, window,
- PublishWorkspace.ID, PublishWorkspace.DEFAULT_LABEL,
- PublishWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && !isReadOnly, params);
-
- // Normalize distribution (Legacy)
- params = new HashMap<String, String>();
- params.put(NormalizeDistribution.PARAM_TARGET_REPO_PATH,
- targetRepoPath);
- params.put(NormalizeDistribution.PARAM_WORKSPACE_NAME,
- workspaceName);
- CommandUtils.refreshParameterizedCommand(submenu, window,
- NormalizeDistribution.ID,
- NormalizeDistribution.DEFAULT_LABEL,
- NormalizeDistribution.DEFAULT_ICON, isDistribElem
- && singleElement && !isReadOnly, params);
-
- // Run in OSGi
- params = new HashMap<String, String>();
- params.put(RunInOsgi.PARAM_MODULE_PATH, modularDistPath);
- params.put(RunInOsgi.PARAM_WORKSPACE_NAME, workspaceName);
- CommandUtils.refreshParameterizedCommand(submenu, window,
- RunInOsgi.ID, RunInOsgi.DEFAULT_LABEL,
- RunInOsgi.DEFAULT_ICON, modularDistPath != null
- && singleElement && isLocal, params);
-
- // Open generate binaries
- params = new HashMap<String, String>();
- params.put(OpenGenerateBinariesWizard.PARAM_REPO_NODE_PATH,
- targetRepoPath);
- params.put(OpenGenerateBinariesWizard.PARAM_MODULE_PATH,
- modularDistBasePath);
- params.put(OpenGenerateBinariesWizard.PARAM_WORKSPACE_NAME,
- workspaceName);
-
- CommandUtils.refreshParameterizedCommand(submenu, window,
- OpenGenerateBinariesWizard.ID,
- OpenGenerateBinariesWizard.DEFAULT_LABEL,
- OpenGenerateBinariesWizard.DEFAULT_ICON,
- isModularDistVersionBaseElem && !isReadOnly, params);
-
- if (submenu.getSize() > 0)
- menuManager.add(submenu);
-
- // // Manage workspace authorizations
- // params = new HashMap<String, String>();
- // params.put(ManageWorkspaceAuth.PARAM_WORKSPACE_NAME, wsName);
- // CommandHelpers.refreshParameterizedCommand(menuManager,
- // window,
- // ManageWorkspaceAuth.ID, ManageWorkspaceAuth.DEFAULT_LABEL,
- // ManageWorkspaceAuth.DEFAULT_ICON_PATH, isDistribElem
- // && singleElement && !isReadOnly, params);
- }
- } catch (RepositoryException e) {
- throw new SlcException("unexpected errror while "
- + "building context menu for element " + firstElement, e);
- }
- }
-
- @Override
- public void setFocus() {
- viewer.getTree().setFocus();
- }
-
- /**
- * Force refresh of the whole view
- */
- public void refresh() {
- viewer.setInput(nodeRepository);
- viewer.expandToLevel(2);
- }
-
- /* DEPENDENCY INJECTION */
- public void setNodeRepository(Repository nodeRepository) {
- this.nodeRepository = nodeRepository;
- }
-
- public void setTreeContentProvider(
- DistTreeContentProvider treeContentProvider) {
- this.treeContentProvider = treeContentProvider;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.browser.Browser;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-/** Display some info about the distribution */
-public class HelpView extends ViewPart {
- public final static String ID = DistPlugin.PLUGIN_ID + ".helpView";
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new GridLayout(2, false));
- Browser browser = new Browser(parent, SWT.NONE);
- browser.setUrl("/repo/howto.html");
- browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- }
-
- /** Force refresh of the whole view */
- public void refresh() {
- }
-
- @Override
- public void setFocus() {
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-
-/** Query SLC Repo to get some artifacts given some predefined parameters */
-public class QueryArtifactsForm extends AbstractQueryArtifactsView implements
- SlcNames {
- // private static final CmsLog log = CmsLog.getLog(QueryArtifactsForm.class);
- public static final String ID = DistPlugin.PLUGIN_ID + ".queryArtifactsForm";
-
- // widgets
- private Button executeBtn;
- private Text groupId;
- private Text artifactId;
- private Text version;
- private SashForm sashForm;
-
- private Composite top, bottom;
-
- @Override
- public void createPartControl(Composite parent) {
-
- sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- // Enable the different parts to fill the whole page when the tab is
- // maximized
- sashForm.setLayout(new FillLayout());
-
- top = new Composite(sashForm, SWT.NONE);
- top.setLayout(new GridLayout(1, false));
-
- bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
-
- sashForm.setWeights(new int[] { 25, 75 });
-
- createQueryForm(top);
- createResultPart(bottom);
- }
-
- public void createQueryForm(Composite parent) {
- Label lbl;
- GridData gd;
-
- GridLayout gl = new GridLayout(2, false);
- gl.marginTop = 5;
- parent.setLayout(gl);
-
- // lbl = new Label(parent, SWT.SINGLE);
- // lbl.setText("Query by coordinates");
- // gd = new GridData();
- // gd.horizontalSpan = 2;
- // lbl.setLayoutData(gd);
-
- // Group ID
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Group ID");
- groupId = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- groupId.setLayoutData(gd);
-
- // Artifact ID
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Artifact ID");
- artifactId = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- artifactId.setLayoutData(gd);
-
- // Version
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Version");
- version = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- version.setLayoutData(gd);
-
- executeBtn = new Button(parent, SWT.PUSH);
- executeBtn.setText("Search");
- gd = new GridData();
- gd.horizontalSpan = 2;
- executeBtn.setLayoutData(gd);
-
- Listener executeListener = new Listener() {
- private static final long serialVersionUID = 7161585477628774129L;
-
- public void handleEvent(Event event) {
- refreshQuery();
- }
- };
- executeBtn.addListener(SWT.Selection, executeListener);
- }
-
- public void refreshQuery() {
- String queryStr = generateSelectStatement() + generateFromStatement()
- + generateWhereStatement();
- executeQuery(queryStr);
- bottom.layout();
- sashForm.layout();
- }
-
- private String generateWhereStatement() {
- try {
- boolean hasFirstClause = false;
- StringBuffer sb = new StringBuffer(" where ");
-
- if (groupId.getText() != null
- && !groupId.getText().trim().equals("")) {
- sb.append("[" + SLC_GROUP_ID + "] like '"
- + groupId.getText().replace('*', '%') + "'");
- hasFirstClause = true;
- }
-
- if (artifactId.getText() != null
- && !artifactId.getText().trim().equals("")) {
- if (hasFirstClause)
- sb.append(" AND ");
- sb.append("[" + SLC_ARTIFACT_ID + "] like '"
- + artifactId.getText().replace('*', '%') + "'");
- hasFirstClause = true;
- }
-
- if (version.getText() != null
- && !version.getText().trim().equals("")) {
- if (hasFirstClause)
- sb.append(" AND ");
- sb.append("[" + SLC_ARTIFACT_VERSION + "] like '"
- + version.getText().replace('*', '%') + "'");
- }
-
- return sb.toString();
- } catch (Exception e) {
- throw new SlcException(
- "Cannot generate where statement to get artifacts", e);
- }
- }
-
- @Override
- public void setFocus() {
- executeBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-
-/** Query SLC Repo to get some artifacts with a JCR SQL 2 request. */
-public class QueryArtifactsText extends AbstractQueryArtifactsView implements
- SlcNames {
- // private static final Log log =
- // LogFactory.getLog(QueryArtifactsText.class);
- public static final String ID = DistPlugin.PLUGIN_ID + ".queryArtifactsText";
-
- // widgets
- private Button executeBtn;
- private Text queryText;
- private SashForm sashForm;
-
- private Composite top, bottom;
-
- @Override
- public void createPartControl(Composite parent) {
-
- sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- // Enable the different parts to fill the whole page when the tab is
- // maximized
- sashForm.setLayout(new FillLayout());
-
- top = new Composite(sashForm, SWT.NONE);
- top.setLayout(new GridLayout(1, false));
-
- bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
-
- sashForm.setWeights(new int[] { 25, 75 });
-
- createQueryForm(top);
- createResultPart(bottom);
- }
-
- public void createQueryForm(Composite parent) {
- Label lbl;
- GridData gd;
-
- GridLayout gl = new GridLayout(2, false);
- gl.marginTop = 5;
- parent.setLayout(gl);
-
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Enter a JCR:SQL2 Query");
-
- executeBtn = new Button(parent, SWT.PUSH);
- executeBtn.setText("Search");
-
- queryText = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- gd.heightHint = 100;
- gd.horizontalSpan = 2;
- queryText.setLayoutData(gd);
-
- String query = generateSelectStatement() + generateFromStatement()
- + generateWhereStatement();
- queryText.setText(query);
-
- Listener executeListener = new Listener() {
- private static final long serialVersionUID = -5028331930076117569L;
-
- public void handleEvent(Event event) {
- refreshQuery();
- }
- };
- executeBtn.addListener(SWT.Selection, executeListener);
- }
-
- public void refreshQuery() {
- String queryStr = queryText.getText();
- executeQuery(queryStr);
- bottom.layout();
- sashForm.layout();
- }
-
- private String generateWhereStatement() {
- StringBuffer sb = new StringBuffer(" where ");
- return sb.toString();
- }
-
- @Override
- public void setFocus() {
- executeBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-
-/** Query SLC Repo to get some artifacts given some predefined parameters */
-public class QueryBundlesForm extends AbstractQueryArtifactsView implements
- SlcNames, SlcTypes {
- // private static final CmsLog log = CmsLog.getLog(QueryBundlesForm.class);
- public static final String ID = DistPlugin.PLUGIN_ID + ".queryBundlesForm";
-
- // widgets
- private Button executeBtn;
- private Text symbolicName;
- private Text importedPackage;
- private Text exportedPackage;
- private SashForm sashForm;
-
- private Composite top, bottom;
-
- @Override
- public void createPartControl(Composite parent) {
-
- sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- // Enable the different parts to fill the whole page when the tab is
- // maximized
- sashForm.setLayout(new FillLayout());
-
- top = new Composite(sashForm, SWT.NONE);
- top.setLayout(new GridLayout(1, false));
-
- bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
-
- sashForm.setWeights(new int[] { 25, 75 });
-
- createQueryForm(top);
- createResultPart(bottom);
- }
-
- public void createQueryForm(Composite parent) {
- Label lbl;
- GridData gd;
-
- GridLayout gl = new GridLayout(2, false);
- gl.marginTop = 5;
- parent.setLayout(gl);
-
- // Bundle Name
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Symbolic name");
- symbolicName = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- symbolicName.setLayoutData(gd);
-
- // imported package
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Imported package");
- importedPackage = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- importedPackage.setLayoutData(gd);
-
- // exported package
- lbl = new Label(parent, SWT.SINGLE);
- lbl.setText("Exported package");
- exportedPackage = new Text(parent, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- exportedPackage.setLayoutData(gd);
-
- executeBtn = new Button(parent, SWT.PUSH);
- executeBtn.setText("Search");
- gd = new GridData();
- gd.horizontalSpan = 2;
- executeBtn.setLayoutData(gd);
-
- Listener executeListener = new Listener() {
- private static final long serialVersionUID = 6267263421349073712L;
-
- public void handleEvent(Event event) {
- refreshQuery();
- }
- };
- executeBtn.addListener(SWT.Selection, executeListener);
- }
-
- public void refreshQuery() {
- String queryStr = generateStatement();
- executeQuery(queryStr);
- bottom.layout();
- sashForm.layout();
- }
-
- private String generateStatement() {
- try {
- // shortcuts
- boolean hasFirstClause = false;
- boolean ipClause = importedPackage.getText() != null
- && !importedPackage.getText().trim().equals("");
- boolean epClause = exportedPackage.getText() != null
- && !exportedPackage.getText().trim().equals("");
-
- StringBuffer sb = new StringBuffer();
- // Select
- sb.append("select " + SBA + ".*, " + SAVB + ".* ");
- sb.append(" from " + SAVB);
-
- // join
- sb.append(" inner join ");
- sb.append(SBA);
- sb.append(" on isdescendantnode(" + SBA + ", " + SAVB + ") ");
- if (ipClause) {
- sb.append(" inner join ");
- sb.append(SIP);
- sb.append(" on isdescendantnode(" + SIP + ", " + SBA + ") ");
- }
-
- if (epClause) {
- sb.append(" inner join ");
- sb.append(SEP);
- sb.append(" on isdescendantnode(" + SEP + ", " + SBA + ") ");
- }
-
- // where
- sb.append(" where ");
- if (symbolicName.getText() != null
- && !symbolicName.getText().trim().equals("")) {
- sb.append(SBA + ".[" + SLC_SYMBOLIC_NAME + "] like '"
- + symbolicName.getText().replace('*', '%') + "'");
- hasFirstClause = true;
- }
-
- if (ipClause) {
- if (hasFirstClause)
- sb.append(" AND ");
- sb.append(SIP + ".[" + SLC_NAME + "] like '"
- + importedPackage.getText().replace('*', '%') + "'");
- hasFirstClause = true;
- }
-
- if (epClause) {
- if (hasFirstClause)
- sb.append(" AND ");
- sb.append(SEP + ".[" + SLC_NAME + "] like '"
- + exportedPackage.getText().replace('*', '%') + "'");
- }
- return sb.toString();
- } catch (Exception e) {
- throw new SlcException(
- "Cannot generate where statement to get artifacts", e);
- }
- }
-
- @Override
- public void setFocus() {
- executeBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.wizards;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.eclipse.jface.wizard.Wizard;
-
-/**
- * Small wizard to manage authorizations on the root node of the current
- * workspace
- */
-public class ChangeRightsWizard extends Wizard {
-
- private Session currentSession;
-
- // This page widget
- private ChooseRightsPage page;
-
- public ChangeRightsWizard(Session currentSession) {
- super();
- this.currentSession = currentSession;
- }
-
- @Override
- public void addPages() {
- try {
- page = new ChooseRightsPage();
- addPage(page);
- } catch (Exception e) {
- throw new SlcException("Cannot add page to wizard ", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- try {
- JcrUtils.addPrivilege(currentSession, "/", page.getGroupName(),
- page.getAuthTypeStr());
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while setting privileges", re);
- }
- return true;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.wizards;
-
-import javax.jcr.security.Privilege;
-
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-public class ChooseRightsPage extends WizardPage implements ModifyListener {
- private static final long serialVersionUID = 3016024222014878781L;
-
- // This page widget
- private Text groupNameTxt;
- private Combo authorizationCmb;
-
- // Define acceptable chars for the technical name
- // private static Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
-
- // USABLE SHORTCUTS
- protected final static String[] validAuthType = { Privilege.JCR_READ,
- Privilege.JCR_WRITE, Privilege.JCR_ALL };
-
- public ChooseRightsPage() {
- super("Main");
- setTitle("Manage authorizations on the current workspace");
- }
-
- public void createControl(Composite parent) {
- // specify subject
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- Label lbl = new Label(composite, SWT.LEAD);
- lbl.setText("Group or user name (no blank, no special chars)");
- lbl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
- groupNameTxt = new Text(composite, SWT.LEAD | SWT.BORDER);
- groupNameTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
- false));
- if (groupNameTxt != null)
- groupNameTxt.addModifyListener(this);
-
- // Choose rigths
- new Label(composite, SWT.NONE).setText("Choose corresponding rights");
- authorizationCmb = new Combo(composite, SWT.BORDER | SWT.V_SCROLL);
- authorizationCmb.setItems(validAuthType);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- authorizationCmb.setLayoutData(gd);
-
- authorizationCmb.select(0);
-
- // Compulsory
- setControl(composite);
- }
-
- protected String getGroupName() {
- return groupNameTxt.getText();
- }
-
- protected String getAuthTypeStr() {
- return authorizationCmb.getItem(authorizationCmb.getSelectionIndex());
- }
-
- // private static boolean match(String s) {
- // return p.matcher(s).matches();
- // }
-
- public void modifyText(ModifyEvent event) {
- String message = checkComplete();
- if (message != null)
- setMessage(message, WizardPage.ERROR);
- else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- }
-
- /** @return error message or null if complete */
- protected String checkComplete() {
- String groupStr = groupNameTxt.getText();
- if (groupStr == null || "".equals(groupStr))
- return "Please enter the name of the corresponding group.";
- // Remove regexp check for the time being.
- // else if (!match(groupStr))
- // return
- // "Please use only alphanumerical chars for the short technical name.";
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.dist.wizards;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Credentials;
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.security.Keyring;
-import org.argeo.cms.ui.workbench.util.PrivilegedJob;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.ViewerUtils;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoSync;
-import org.argeo.slc.repo.RepoUtils;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Defines parameters for the fetch process and run it using a {@link RepoSync}
- * object.
- */
-public class FetchWizard extends Wizard {
- // private final static CmsLog log = CmsLog.getLog(FetchWizard.class);
-
- // Business objects
- private Keyring keyring;
- private RepositoryFactory repositoryFactory;
- private Session currSession;
- private Node targetRepoNode, sourceRepoNode;
-
- private List<WkspObject> selectedWorkspaces = new ArrayList<WkspObject>();
-
- // The pages
- private ChooseWkspPage chooseWkspPage;
- private RecapPage recapPage;
-
- // Cache the advanced pages
- private Map<WkspObject, AdvancedFetchPage> advancedPages = new HashMap<FetchWizard.WkspObject, FetchWizard.AdvancedFetchPage>();
-
- // Controls with parameters
- private Button filesOnlyBtn;
- private Button advancedBtn;
- private CheckboxTableViewer wkspViewer;
-
- public FetchWizard(Keyring keyring, RepositoryFactory repositoryFactory,
- Repository nodeRepository) {
- super();
- this.keyring = keyring;
- this.repositoryFactory = repositoryFactory;
- try {
- currSession = nodeRepository.login();
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected error while initializing fetch wizard", e);
- }
- }
-
- @Override
- public void dispose() {
- JcrUtils.logoutQuietly(currSession);
- super.dispose();
- }
-
- @Override
- public void addPages() {
- try {
- chooseWkspPage = new ChooseWkspPage();
- addPage(chooseWkspPage);
- recapPage = new RecapPage();
- addPage(recapPage);
- setWindowTitle("Define Fetch Procedure");
- } catch (Exception e) {
- throw new SlcException("Cannot add page to wizard ", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- try {
- // Target Repository
- String targetRepoUri = targetRepoNode.getProperty(
- ArgeoNames.ARGEO_URI).getString();
- Repository targetRepo = RepoUtils.getRepository(repositoryFactory,
- keyring, targetRepoNode);
- Credentials targetCredentials = RepoUtils.getRepositoryCredentials(
- keyring, targetRepoNode);
-
- // Source Repository
- String sourceRepoUri = sourceRepoNode.getProperty(
- ArgeoNames.ARGEO_URI).getString();
- Repository sourceRepo = RepoUtils.getRepository(repositoryFactory,
- keyring, sourceRepoNode);
- Credentials sourceCredentials = RepoUtils.getRepositoryCredentials(
- keyring, sourceRepoNode);
-
- String msg = "Your are about to fetch data from repository: \n\t"
- + sourceRepoUri + "\ninto target repository: \n\t"
- + targetRepoUri + "\nDo you really want to proceed ?";
-
- boolean result = MessageDialog.openConfirm(DistPlugin.getDefault()
- .getWorkbench().getDisplay().getActiveShell(),
- "Confirm Fetch Launch", msg);
-
- if (result) {
- RepoSync repoSync = new RepoSync(sourceRepo, sourceCredentials,
- targetRepo, targetCredentials);
- repoSync.setTargetRepoUri(targetRepoUri);
- repoSync.setSourceRepoUri(sourceRepoUri);
-
- // Specify workspaces to synchronise
- Map<String, String> wksps = new HashMap<String, String>();
- for (Object obj : wkspViewer.getCheckedElements()) {
- WkspObject stn = (WkspObject) obj;
- wksps.put(stn.srcName, stn.targetName);
- }
- repoSync.setWkspMap(wksps);
-
- // Set the import files only option
- repoSync.setFilesOnly(filesOnlyBtn.getSelection());
- FetchJob job = new FetchJob(repoSync);
- job.setUser(true);
- job.schedule();
- }
- } catch (Exception e) {
- throw new SlcException(
- "Unexpected error while launching the fetch", e);
- }
- return true;
- }
-
- // ///////////////////////////////
- // ////// THE PAGES
-
- private class ChooseWkspPage extends WizardPage {
- private static final long serialVersionUID = 211336700788047638L;
-
- private Map<String, Node> sourceReposMap;
- private Combo chooseSourceRepoCmb;
-
- public ChooseWkspPage() {
- super("Main");
- setTitle("Choose workspaces to fetch");
- setDescription("Check 'advanced fetch' box to "
- + "rename workspaces and fine tune the process");
-
- // Initialise with registered Repositories
- sourceReposMap = getSourceRepoUris();
- }
-
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NO_FOCUS);
- composite.setLayout(new GridLayout(2, false));
-
- // Choose source repository combo
- new Label(composite, SWT.NONE)
- .setText("Choose a source repository");
- chooseSourceRepoCmb = new Combo(composite, SWT.BORDER
- | SWT.V_SCROLL);
- chooseSourceRepoCmb.setItems(sourceReposMap.keySet().toArray(
- new String[sourceReposMap.size()]));
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- chooseSourceRepoCmb.setLayoutData(gd);
-
- // Check boxes
- final Button selectAllBtn = new Button(composite, SWT.CHECK);
- selectAllBtn.setText("Select/Unselect all");
-
- advancedBtn = new Button(composite, SWT.CHECK);
- advancedBtn.setText("Advanced fetch");
- advancedBtn.setToolTipText("Check this for further "
- + "parameterization of the fetch process");
-
- // Workspace table
- Table table = new Table(composite, SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.BORDER | SWT.CHECK);
- gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- gd.horizontalSpan = 2;
- table.setLayoutData(gd);
- configureWkspTable(table);
-
- // Import only files
- filesOnlyBtn = new Button(composite, SWT.CHECK | SWT.WRAP);
- filesOnlyBtn
- .setText("Import only files (faster, a normalized action should be launched once done)");
- filesOnlyBtn.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false,
- false, 2, 1));
-
- // Listeners
- selectAllBtn.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -2071840477444152170L;
-
- public void widgetSelected(SelectionEvent e) {
- wkspViewer.setAllChecked(selectAllBtn.getSelection());
- getContainer().updateButtons();
- }
- });
-
- // advancedBtn.addSelectionListener(new SelectionAdapter() {
- // public void widgetSelected(SelectionEvent e) {
- // if (advancedBtn.getSelection()){
- //
- // }
- // wkspViewer.setAllChecked();
- // }
- // });
-
- chooseSourceRepoCmb.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = 932462568382594523L;
-
- public void modifyText(ModifyEvent e) {
- String chosenUri = chooseSourceRepoCmb
- .getItem(chooseSourceRepoCmb.getSelectionIndex());
- sourceRepoNode = sourceReposMap.get(chosenUri);
- wkspViewer.setInput(sourceRepoNode);
- }
- });
-
- wkspViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- getContainer().updateButtons();
- }
- });
-
- // Initialise to first available repo
- if (chooseSourceRepoCmb.getItemCount() > 0)
- chooseSourceRepoCmb.select(0);
-
- // Compulsory
- setControl(composite);
- }
-
- @Override
- public boolean isPageComplete() {
- return wkspViewer.getCheckedElements().length != 0;
- }
-
- @Override
- public IWizardPage getNextPage() {
- // WARNING: page are added and never removed.
- if (advancedBtn.getSelection()
- && wkspViewer.getCheckedElements().length != 0) {
- IWizardPage toReturn = null;
- for (Object obj : wkspViewer.getCheckedElements()) {
- WkspObject curr = (WkspObject) obj;
- // currSelecteds.add(curr);
- AdvancedFetchPage page;
- if (!advancedPages.containsKey(curr)) {
- page = new AdvancedFetchPage(curr.srcName, curr);
- addPage(page);
- advancedPages.put(curr, page);
- } else
- page = advancedPages.get(curr);
- if (toReturn == null)
- toReturn = page;
- }
- return toReturn;
- } else {
- return recapPage;
- }
- }
-
- // Configure the workspace table
- private void configureWkspTable(Table table) {
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
- wkspViewer = new CheckboxTableViewer(table);
-
- // WORKSPACE COLUMNS
- TableViewerColumn column = ViewerUtils.createTableViewerColumn(
- wkspViewer, "Source names", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 5906079281065061967L;
-
- @Override
- public String getText(Object element) {
- return ((WkspObject) element).srcName;
- }
- });
-
- // column = ViewerUtils.createTableViewerColumn(wkspViewer, "Size",
- // SWT.NONE, 250);
- // column.setLabelProvider(new ColumnLabelProvider() {
- // @Override
- // public String getText(Object element) {
- // return ((WkspObject) element).getFormattedSize();
- // }
- // });
-
- wkspViewer.setContentProvider(new WkspContentProvider());
- // A basic comparator
- wkspViewer.setComparator(new ViewerComparator());
- }
- }
-
- private class AdvancedFetchPage extends WizardPage {
- private static final long serialVersionUID = 1109183561920445169L;
-
- private final WkspObject currentWorkspace;
-
- private Text targetNameTxt;
-
- protected AdvancedFetchPage(String pageName, WkspObject currentWorkspace) {
- super(pageName);
- this.currentWorkspace = currentWorkspace;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- String msg = "Define advanced parameters to fetch workspace "
- + currentWorkspace.srcName;
- setMessage(msg);
- targetNameTxt.setText(currentWorkspace.targetName);
- }
- // else
- // currentWorkspace.targetName = targetNameTxt.getText();
- }
-
- public void createControl(Composite parent) {
- Composite body = new Composite(parent, SWT.NO_FOCUS);
- body.setLayout(new GridLayout(2, false));
- new Label(body, SWT.NONE).setText("Choose a new name");
- targetNameTxt = new Text(body, SWT.BORDER);
- targetNameTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
- true, false));
- setControl(body);
- }
-
- protected WkspObject getWorkspaceObject() {
- currentWorkspace.targetName = targetNameTxt.getText();
- return currentWorkspace;
- }
-
- @Override
- public IWizardPage getNextPage() {
- // WARNING: page are added and never removed.
- // IWizardPage toReturn = null;
- // IWizardPage[] pages = ((Wizard) getContainer()).getPages();
- Object[] selected = wkspViewer.getCheckedElements();
- for (int i = 0; i < selected.length - 1; i++) {
- WkspObject curr = (WkspObject) selected[i];
- if (curr.equals(currentWorkspace))
- return advancedPages.get((WkspObject) selected[i + 1]);
- }
- return recapPage;
- }
- }
-
- private class RecapPage extends WizardPage {
- private static final long serialVersionUID = -7064862323304300989L;
- private TableViewer recapViewer;
-
- public RecapPage() {
- super("Validate and launch");
- setTitle("Validate and launch");
- }
-
- @Override
- public boolean isPageComplete() {
- return isCurrentPage();
- }
-
- public IWizardPage getNextPage() {
- // always last....
- return null;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- try {
- String targetRepoUri = targetRepoNode.getProperty(
- ArgeoNames.ARGEO_URI).getString();
- String sourceRepoUri = sourceRepoNode.getProperty(
- ArgeoNames.ARGEO_URI).getString();
-
- String msg = "Fetch data from: " + sourceRepoUri
- + "\ninto target repository: " + targetRepoUri;
- // + "\nDo you really want to proceed ?";
- setMessage(msg);
-
- // update values that will be used for the fetch
- selectedWorkspaces.clear();
-
- for (Object obj : wkspViewer.getCheckedElements()) {
- WkspObject curr = (WkspObject) obj;
-
- if (advancedBtn.getSelection()) {
- AdvancedFetchPage page = advancedPages.get(curr);
- selectedWorkspaces.add(page.getWorkspaceObject());
- } else
- selectedWorkspaces.add(curr);
- }
- recapViewer.setInput(selectedWorkspaces);
- recapViewer.refresh();
-
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get repositories URIs",
- re);
- }
- }
- }
-
- public void createControl(Composite parent) {
- Table table = new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.BORDER);
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
- recapViewer = new TableViewer(table);
-
- // WORKSPACE COLUMNS
- TableViewerColumn column = ViewerUtils.createTableViewerColumn(
- recapViewer, "Sources", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 3913459002502680377L;
-
- @Override
- public String getText(Object element) {
- return ((WkspObject) element).srcName;
- }
- });
-
- column = ViewerUtils.createTableViewerColumn(recapViewer,
- "targets", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -517920072332563632L;
-
- @Override
- public String getText(Object element) {
- return ((WkspObject) element).targetName;
- }
- });
-
- recapViewer.setContentProvider(new IStructuredContentProvider() {
- private static final long serialVersionUID = 4926999891003040865L;
-
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- // TODO Auto-generated method stub
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object inputElement) {
- return selectedWorkspaces.toArray();
- }
- });
-
- // A basic comparator
- recapViewer.setComparator(new ViewerComparator());
- setControl(table);
- }
- }
-
- /**
- * Define the privileged job that will be run asynchronously to accomplish
- * the sync
- */
- private class FetchJob extends PrivilegedJob {
- private RepoSync repoSync;
-
- public FetchJob(RepoSync repoSync) {
- super("Fetch");
- this.repoSync = repoSync;
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- try {
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- repoSync.setMonitor(monitor);
- repoSync.run();
- } catch (Exception e) {
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID,
- "Cannot fetch repository", e);
- }
- return Status.OK_STATUS;
- }
- }
-
- // ///////////////////////
- // Local classes
- private class WkspObject {
- protected final String srcName;
- protected String targetName;
-
- protected WkspObject(String srcName) {
- this.srcName = srcName;
- this.targetName = srcName;
- }
-
- @Override
- public String toString() {
- return "[" + srcName + " to " + targetName + "]";
- }
- }
-
- // private class WkspComparator extends ViewerComparator {
- //
- // }
-
- private class WkspContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -925058051598536307L;
- // caches current repo
- private Node currSourceNodeRepo;
- private Repository currSourceRepo;
- private Credentials currSourceCred;
-
- private List<WkspObject> workspaces = new ArrayList<WkspObject>();
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput != null && newInput instanceof Node) {
- Session session = null;
- try {
- Node newRepoNode = (Node) newInput;
- if (currSourceNodeRepo == null
- || !newRepoNode.getPath().equals(
- currSourceNodeRepo.getPath())) {
-
- // update cache
- currSourceNodeRepo = newRepoNode;
- currSourceRepo = RepoUtils.getRepository(
- repositoryFactory, keyring, currSourceNodeRepo);
- currSourceCred = RepoUtils.getRepositoryCredentials(
- keyring, currSourceNodeRepo);
-
- // reset workspace list
- wkspViewer.setAllChecked(false);
- workspaces.clear();
- // FIXME make it more generic
- session = currSourceRepo.login(currSourceCred,RepoConstants.DEFAULT_DEFAULT_WORKSPACE);
- // remove unvalid elements
- for (String name : session.getWorkspace()
- .getAccessibleWorkspaceNames())
- // TODO implement a cleaner way to filter
- // workspaces out
- if (name.lastIndexOf('-') > 0) {
- WkspObject currWksp = new WkspObject(name);
- // compute wkspace size
- // TODO implement this
- // Session currSession = null;
- // try {
- // currSession = currSourceRepo.login(
- // currSourceCred, name);
- // currWksp.size = JcrUtils
- // .getNodeApproxSize(currSession
- // .getNode("/"));
- //
- // } catch (RepositoryException re) {
- // log.warn(
- // "unable to compute size of workspace "
- // + name, re);
- // } finally {
- // JcrUtils.logoutQuietly(currSession);
- // }
- workspaces.add(currWksp);
- }
- }
-
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while "
- + "initializing fetch wizard", e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- viewer.refresh();
- }
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object obj) {
- return workspaces.toArray();
- }
- }
-
- // ////////////////////////////
- // // Helpers
-
- // populate available source repo list
- private Map<String, Node> getSourceRepoUris() {
- try {
- Node repoList = currSession.getNode(CmsJcrUtils.getUserHome(
- currSession).getPath()
- + RepoConstants.REPOSITORIES_BASE_PATH);
-
- String targetRepoUri = null;
- if (targetRepoNode != null) {
- targetRepoUri = targetRepoNode
- .getProperty(ArgeoNames.ARGEO_URI).getString();
- }
- NodeIterator ni = repoList.getNodes();
- // List<String> sourceRepoNames = new ArrayList<String>();
- // // caches a map of the source repo nodes with their URI as a key
- // // to ease further processing
- Map<String, Node> sourceReposMap = new HashMap<String, Node>();
- while (ni.hasNext()) {
- Node currNode = ni.nextNode();
- if (currNode.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY)) {
- String currUri = currNode.getProperty(ArgeoNames.ARGEO_URI)
- .getString();
- if (targetRepoUri == null || !targetRepoUri.equals(currUri)) {
- sourceReposMap.put(currUri, currNode);
- // sourceRepoNames.add(currUri);
- }
- }
- }
- return sourceReposMap;
- // sourceRepoNames.toArray(new String[sourceRepoNames
- // .size()]);
- } catch (RepositoryException e) {
- throw new SlcException("Error while getting repo aliases", e);
- }
- }
-
- public void setTargetRepoNode(Node targetRepoNode) {
- this.targetRepoNode = targetRepoNode;
- }
-
- public void setSourceRepoNode(Node sourceRepoNode) {
- this.sourceRepoNode = sourceRepoNode;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.wizards;
-
-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 org.argeo.api.cms.CmsLog;
-import org.argeo.cms.ui.workbench.util.PrivilegedJob;
-import org.argeo.eclipse.ui.jcr.EclipseJcrMonitor;
-import org.argeo.jcr.JcrMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.utils.ViewerUtils;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoService;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.GenerateBinaries;
-import org.eclipse.aether.artifact.Artifact;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Define parameters to asynchronously generate binaries, sources and sdk pom
- * artifacts for this group using a {@link GenerateBinaries} runnable
- */
-public class GenerateBinariesWizard extends Wizard {
- private final static CmsLog log = CmsLog
- .getLog(GenerateBinariesWizard.class);
-
- // Business objects
- private final RepoService repoService;
- private final String repoNodePath;
- private String wkspName;
- private String groupNodePath;
-
- // The pages
- private RecapPage recapPage;
-
- // Controls with parameters
- private Text versionTxt;
- private Text latestVersionTxt;
- private Text highestArtifactVersionTxt;
-
- public GenerateBinariesWizard(RepoService repoService, String repoNodePath,
- String wkspName, String groupNodePath) {
- super();
- this.repoService = repoService;
- this.repoNodePath = repoNodePath;
- this.wkspName = wkspName;
- this.groupNodePath = groupNodePath;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- }
-
- @Override
- public void addPages() {
- try {
- recapPage = new RecapPage();
- addPage(recapPage);
- setWindowTitle("Define Binary Generation Procedure");
- } catch (Exception e) {
- throw new SlcException("Cannot add page to wizard ", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- try {
- String msg = "Your are about to generate binaries, sources and sdk "
- + "pom artifacts for this group, "
- + "do you really want to proceed ?";
-
- boolean result = MessageDialog.openConfirm(DistPlugin.getDefault()
- .getWorkbench().getDisplay().getActiveShell(),
- "Confirm Launch", msg);
-
- if (result) {
- GenerateBinaryJob job = new GenerateBinaryJob(repoService,
- repoNodePath, wkspName, groupNodePath,
- versionTxt.getText());
- job.setUser(true);
- job.schedule();
- }
- } catch (Exception e) {
- throw new SlcException(
- "Unexpected error while launching the fetch", e);
- }
- return true;
- }
-
- // ///////////////////////////////
- // ////// THE PAGES
- private class RecapPage extends WizardPage {
- private static final long serialVersionUID = 904196417910874087L;
- private TableViewer recapViewer;
-
- public RecapPage() {
- super("Define parameters and launch");
- setTitle("Define parameters and launch");
- }
-
- @Override
- public boolean isPageComplete() {
- return isCurrentPage();
- }
-
- public IWizardPage getNextPage() {
- return null; // always last
- }
-
- private void refreshValues() {
- Session session = null;
- try {
- session = repoService.getRemoteSession(repoNodePath, null,
- wkspName);
- Node groupNode = session.getNode(groupNodePath);
- GenerateBinaries gb = GenerateBinaries.preProcessGroupNode(
- groupNode, null);
-
- List<Artifact> binaries = new ArrayList<Artifact>();
- binaries.addAll(gb.getBinaries());
-
- Artifact highestVersion = gb.getHighestArtifactVersion();
- if (highestVersion != null)
- highestArtifactVersionTxt.setText(highestVersion
- .getBaseVersion());
-
- if (groupNode.hasNode(RepoConstants.BINARIES_ARTIFACT_ID)) {
- Node binaryNode = groupNode
- .getNode(RepoConstants.BINARIES_ARTIFACT_ID);
- Artifact currHighestVersion = null;
- for (NodeIterator ni = binaryNode.getNodes(); ni.hasNext();) {
- Node currN = ni.nextNode();
- if (currN
- .isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
- Artifact currVersion = RepoUtils.asArtifact(currN);
-
- if (currHighestVersion == null
- || currVersion.getBaseVersion()
- .compareTo(
- currHighestVersion
- .getBaseVersion()) > 0)
- currHighestVersion = currVersion;
- }
- }
- if (currHighestVersion != null)
- latestVersionTxt.setText(currHighestVersion
- .getBaseVersion());
- }
- recapViewer.setInput(binaries);
- recapViewer.refresh();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to get repositories URIs", re);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- }
-
- public void createControl(Composite parent) {
- setMessage("Configure Maven Indexing", IMessageProvider.NONE);
-
- Composite composite = new Composite(parent, SWT.NO_FOCUS);
- composite.setLayout(new GridLayout(2, false));
-
- versionTxt = createLT(composite, "Version");
- versionTxt
- .setToolTipText("Enter a version for the new Modular Distribution");
-
- latestVersionTxt = createLT(composite, "Latest version");
- latestVersionTxt.setEditable(false);
- latestVersionTxt
- .setToolTipText("The actual latest version of this modular distribution");
-
- highestArtifactVersionTxt = createLT(composite,
- "Highest version in current category");
- highestArtifactVersionTxt.setEditable(false);
- highestArtifactVersionTxt
- .setToolTipText("The highest version among all version of the below listed modules.");
-
- // Creates the table
- Table table = new Table(composite, SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.BORDER);
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2,
- 1));
- recapViewer = new TableViewer(table);
-
- TableViewerColumn column = ViewerUtils.createTableViewerColumn(
- recapViewer, "Name", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -9145709097621022043L;
-
- @Override
- public String getText(Object element) {
- return ((Artifact) element).getArtifactId();
- }
- });
-
- column = ViewerUtils.createTableViewerColumn(recapViewer,
- "Version", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 5524185741667651628L;
-
- @Override
- public String getText(Object element) {
- return ((Artifact) element).getBaseVersion();
- }
- });
-
- recapViewer.setContentProvider(new IStructuredContentProvider() {
- private static final long serialVersionUID = -4579434453554442858L;
-
-
- List<Artifact> artifacts;
-
- @SuppressWarnings("unchecked")
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- artifacts = (List<Artifact>) newInput;
- if (artifacts != null)
- recapViewer.refresh();
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object inputElement) {
- return artifacts == null ? null : artifacts.toArray();
- }
- });
-
- // A basic comparator
- recapViewer.setComparator(new ViewerComparator());
- refreshValues();
- setControl(composite);
- }
- }
-
- /**
- * Define the privileged job that will be run asynchronously generate
- * corresponding artifacts
- */
- private class GenerateBinaryJob extends PrivilegedJob {
-
- private final RepoService repoService;
- private final String repoNodePath;
- private final String wkspName;
- private final String groupNodePath;
- private final String version;
-
- public GenerateBinaryJob(RepoService repoService, String repoNodePath,
- String wkspName, String groupNodePath, String version) {
- super("Fetch");
- this.version = version;
- this.repoService = repoService;
- this.repoNodePath = repoNodePath;
- this.wkspName = wkspName;
- this.groupNodePath = groupNodePath;
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- Session session = null;
- try {
- JcrMonitor monitor = new EclipseJcrMonitor(progressMonitor);
- session = repoService.getRemoteSession(repoNodePath, null,
- wkspName);
- Node groupBaseNode = session.getNode(groupNodePath);
- GenerateBinaries.processGroupNode(groupBaseNode, version,
- monitor);
- } catch (Exception e) {
- if (log.isDebugEnabled())
- e.printStackTrace();
- return new Status(IStatus.ERROR, DistPlugin.PLUGIN_ID,
- "Cannot normalize group", e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return Status.OK_STATUS;
- }
- }
-
- // ////////////////////////////
- // // Helpers
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER
- | SWT.NONE);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return text;
- }
-
- /** Creates label and check. */
- protected Button createLC(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Button check = new Button(parent, SWT.CHECK);
- check.setSelection(false);
- check.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return check;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.dist.wizards;
-
-import java.net.URI;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ArgeoNames;
-import org.argeo.cms.ArgeoTypes;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.cms.security.Keyring;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- *
- * Registers a new remote repository in the current Node.
- *
- */
-public class RegisterRepoWizard extends Wizard {
-
- // Business objects
- private Keyring keyring;
- private RepositoryFactory repositoryFactory;
- private Repository nodeRepository;
-
- // Pages
- private DefineModelPage page;
-
- // Widgets of model page
- private Text name;
- private Text uri;
- private Text username;
- private Text password;
- private Button saveInKeyring;
-
- // Default values
- private final static String DEFAULT_NAME = "Argeo Public Repository";
- private final static String DEFAULT_URI = "https://forge.argeo.org/jcr/java";
- private final static String DEFAULT_USER_NAME = "anonymous";
- private final static boolean DEFAULT_ANONYMOUS = true;
-
- public RegisterRepoWizard(Keyring keyring, RepositoryFactory repositoryFactory, Repository nodeRepository) {
- super();
- this.keyring = keyring;
- this.repositoryFactory = repositoryFactory;
- this.nodeRepository = nodeRepository;
- }
-
- @Override
- public void addPages() {
- try {
- page = new DefineModelPage();
- addPage(page);
- setWindowTitle("Register a new remote repository");
- } catch (Exception e) {
- throw new SlcException("Cannot add page to wizard ", e);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
-
- Session nodeSession = null;
- try {
- nodeSession = nodeRepository.login(CmsConstants.HOME_WORKSPACE);
- String reposPath = CmsJcrUtils.getUserHome(nodeSession).getPath() + RepoConstants.REPOSITORIES_BASE_PATH;
-
- Node repos = nodeSession.getNode(reposPath);
- String repoNodeName = JcrUtils.replaceInvalidChars(name.getText());
- if (repos.hasNode(repoNodeName))
- throw new SlcException("There is already a remote repository named " + repoNodeName);
-
- // check if the same URI has already been registered
- NodeIterator ni = repos.getNodes();
- while (ni.hasNext()) {
- Node node = ni.nextNode();
- if (node.isNodeType(ArgeoTypes.ARGEO_REMOTE_REPOSITORY) && node.hasProperty(ArgeoNames.ARGEO_URI)
- && node.getProperty(ArgeoNames.ARGEO_URI).getString().equals(uri.getText()))
- throw new SlcException("This URI " + uri.getText() + " is already registered, "
- + "for the time being, only one instance of a single "
- + "repository at a time is implemented.");
- }
-
- Node repoNode = repos.addNode(repoNodeName, ArgeoTypes.ARGEO_REMOTE_REPOSITORY);
- repoNode.setProperty(ArgeoNames.ARGEO_URI, uri.getText());
- repoNode.setProperty(ArgeoNames.ARGEO_USER_ID, username.getText());
- repoNode.addMixin(NodeType.MIX_TITLE);
- repoNode.setProperty(Property.JCR_TITLE, name.getText());
- nodeSession.save();
- if (saveInKeyring.getSelection()) {
- String pwdPath = repoNode.getPath() + '/' + ArgeoNames.ARGEO_PASSWORD;
- keyring.set(pwdPath, password.getText().toCharArray());
- nodeSession.save();
- }
- MessageDialog.openInformation(getShell(), "Repository Added",
- "Remote repository " + uri.getText() + "' added");
- } catch (Exception e) {
- ErrorFeedback.show("Cannot add remote repository", e);
- } finally {
- JcrUtils.logoutQuietly(nodeSession);
- }
- return true;
- }
-
- private class DefineModelPage extends WizardPage {
- private static final long serialVersionUID = 874386824101995060L;
-
- public DefineModelPage() {
- super("Main");
- setTitle("Fill information to register a repository");
- }
-
- public void createControl(Composite parent) {
-
- // main layout
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- // Create various fields
- // setMessage("Login to remote repository", IMessageProvider.NONE);
- name = createLT(composite, "Name", DEFAULT_NAME);
- uri = createLT(composite, "URI", DEFAULT_URI);
-
- final Button anonymousLogin = createLC(composite, "Log as anonymous", true);
- anonymousLogin.addSelectionListener(new SelectionListener() {
- private static final long serialVersionUID = 4874716406036981039L;
-
- public void widgetSelected(SelectionEvent e) {
- if (anonymousLogin.getSelection()) {
- username.setText(DEFAULT_USER_NAME);
- password.setText("");
- username.setEnabled(false);
- password.setEnabled(false);
- } else {
- username.setText("");
- password.setText("");
- username.setEnabled(true);
- password.setEnabled(true);
- }
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- username = createLT(composite, "User", DEFAULT_USER_NAME);
- password = createLP(composite, "Password");
- saveInKeyring = createLC(composite, "Remember password", false);
-
- if (DEFAULT_ANONYMOUS) {
- username.setEnabled(false);
- password.setEnabled(false);
- }
-
- Button test = createButton(composite, "Test");
- GridData gd = new GridData(SWT.CENTER, SWT.CENTER, false, false, 2, 1);
- gd.widthHint = 140;
- test.setLayoutData(gd);
-
- test.addSelectionListener(new SelectionAdapter() {
- private static final long serialVersionUID = -4034851916548656293L;
-
- public void widgetSelected(SelectionEvent arg0) {
- testConnection();
- }
- });
-
- // Compulsory
- setControl(composite);
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite parent, String label, String initial) {
- new Label(parent, SWT.RIGHT).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- text.setText(initial);
- return text;
- }
-
- /** Creates label and check. */
- protected Button createLC(Composite parent, String label, Boolean initial) {
- new Label(parent, SWT.RIGHT).setText(label);
- Button check = new Button(parent, SWT.CHECK);
- check.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- check.setSelection(initial);
- return check;
- }
-
- /** Creates a button with a label. */
- protected Button createButton(Composite parent, String label) {
- Button button = new Button(parent, SWT.PUSH);
- button.setText(label);
- button.setFont(JFaceResources.getDialogFont());
- setButtonLayoutData(button);
- return button;
- }
-
- /** Creates label and password field */
- protected Text createLP(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.BORDER | SWT.PASSWORD);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- return text;
- }
-
- }
-
- void testConnection() {
- Session session = null;
- try {
- if (uri.getText().startsWith("http")) {// http, https
- URI checkedUri = new URI(uri.getText());
- String checkedUriStr = checkedUri.toString();
- Repository repository = CmsJcrUtils.getRepositoryByUri(repositoryFactory, checkedUriStr);
- if (username.getText().trim().equals("")) {// anonymous
- session = repository.login(RepoConstants.DEFAULT_DEFAULT_WORKSPACE);
- } else {
- char[] pwd = password.getTextChars();
- SimpleCredentials sc = new SimpleCredentials(username.getText(), pwd);
- session = repository.login(sc, RepoConstants.DEFAULT_DEFAULT_WORKSPACE);
- }
- } else {// alias
- Repository repository = CmsJcrUtils.getRepositoryByAlias(repositoryFactory, uri.getText());
- session = repository.login();
- }
- MessageDialog.openInformation(getShell(), "Success", "Connection to '" + uri.getText() + "' successful");
- } catch (Exception e) {
- ErrorFeedback.show("Connection test failed for " + uri.getText(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.client.ui</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <bean id="updateModule"
- class="org.argeo.slc.client.ui.commands.UpdateModule"
- scope="prototype">
- <property name="modulesManager" ref="modulesManager"/>
- </bean>
-<!-- <bean name="runSlc/Flow" -->
-<!-- class="org.argeo.slc.client.ui.commands.RunSlcFlow" -->
-<!-- scope="prototype"> -->
-<!-- <property name="modulesManager" ref="modulesManager"/> -->
-<!-- </bean> -->
-
- <!-- Result list view commands-->
-<!-- <bean id="org.argeo.slc.client.ui.refreshResultList" -->
-<!-- class="org.argeo.slc.client.ui.commands.ResultListViewRefreshHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-
-<!-- <bean id="org.argeo.slc.client.ui.removeSelectedResultFromResultList" -->
-<!-- class="org.argeo.slc.client.ui.commands.RemoveSelectedResultFromResultList" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-
-
-<!-- <bean id="org.argeo.slc.client.ui.refreshExecutionModulesView" -->
-<!-- class="org.argeo.slc.client.ui.commands.ExecutionModulesViewRefreshHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.refreshProcessList" -->
-<!-- class="org.argeo.slc.client.ui.commands.ProcessListViewRefreshHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.displayProcessDetails" -->
-<!-- class="org.argeo.slc.client.ui.commands.ProcessDetailsDisplayHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.displayResultDetails" -->
-<!-- class="org.argeo.slc.client.ui.commands.ResultDetailsDisplayHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.launchBatch" class="org.argeo.slc.client.ui.commands.LaunchBatchHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.removeSelectedFromBatch" -->
-<!-- class="org.argeo.slc.client.ui.commands.RemoveSelectedProcessFromBatchHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.clearBatch" class="org.argeo.slc.client.ui.commands.ClearBatchHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-<!-- <bean id="org.argeo.slc.client.ui.manageBundles" class="org.argeo.slc.client.ui.commands.ManageBundlesHandler" -->
-<!-- scope="prototype"> -->
-<!-- </bean> -->
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <bean id="processController" class="org.argeo.slc.client.ui.controllers.ProcessController">
- <property name="agent" ref="agent" />
- </bean>
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <bean id="processEditor" class="org.argeo.slc.client.ui.editors.ProcessEditor"
- scope="prototype">
- <property name="processController" ref="processController" />
- <property name="modulesManager" ref="modulesManager" />
- <property name="repository" ref="repository" />
- </bean>
-</beans>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:osgi="http://www.springframework.org/schema/osgi"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"\r
- osgi:default-timeout="30000">\r
-\r
- <beans:description>SLC UI</beans:description>\r
-\r
- <!-- REFERENCES -->\r
- <reference id="repository" interface="javax.jcr.Repository"\r
- filter="(cn=ego)" />\r
-\r
- <reference id="agent" interface="org.argeo.slc.execution.SlcAgent" />\r
-\r
- <reference id="modulesManager"\r
- interface="org.argeo.slc.execution.ExecutionModulesManager" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
-
- <bean id="jcrExecutionModulesView" class="org.argeo.slc.client.ui.views.JcrExecutionModulesView"
- scope="prototype">
- <property name="repository" ref="repository" />
- <property name="modulesManager" ref="modulesManager" />
- </bean>
-
- <bean id="jcrProcessListView" class="org.argeo.slc.client.ui.views.JcrProcessListView"
- scope="prototype">
- <property name="repository" ref="repository" />
- </bean>
-
- <bean id="jcrResultListView" class="org.argeo.slc.client.ui.views.JcrResultListView"
- scope="prototype">
- <property name="repository" ref="repository" />
- </bean>
-
- <bean id="jcrResultTreeView" class="org.argeo.slc.client.ui.views.JcrResultTreeView"
- scope="prototype">
- <property name="repository" ref="repository" />
- </bean>
-
-</beans>
\ No newline at end of file
+++ /dev/null
-Bundle-SymbolicName: org.argeo.slc.client.ui;singleton=true
-Bundle-ActivationPolicy: lazy
-Require-Bundle: org.eclipse.ui;resolution:=optional,\
-org.eclipse.core.runtime,\
-org.eclipse.rap.ui;resolution:=optional,\
-org.eclipse.rap.ui.workbench;resolution:=optional
-
-Bundle-Activator: org.argeo.slc.client.ui.ClientUiPlugin
-Import-Package: org.argeo.eclipse.spring,\
-org.eclipse.core.runtime,\
-org.osgi.*;version=0.0.0,\
-*
+++ /dev/null
-source.. = src
-bin.includes = plugin.xml,\
- META-INF/,\
- .,\
- icons/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
-
- <!-- Views -->
- <extension
- point="org.eclipse.ui.views">
- <view
- id="org.argeo.slc.client.ui.jcrExecutionModulesView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- icon="icons/execution_module.gif"
- name="Execution"
- restorable="true">
- </view>
- <view
- id="org.argeo.slc.client.ui.jcrResultListView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- icon="icons/results.gif"
- name="Results"
- restorable="true">
- </view>
- <view
- id="org.argeo.slc.client.ui.jcrResultTreeView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- icon="icons/results.gif"
- name="Results"
- restorable="true">
- </view>
- <view
- id="org.argeo.slc.client.ui.jcrProcessListView"
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- name="Processes"
- icon="icons/processes.gif"
- restorable="true">
- </view>
- </extension>
-
- <!-- Commands definitions -->
- <extension
- point="org.eclipse.ui.commands">
- <command
- defaultHandler="org.argeo.eclipse.spring.SpringCommandHandler"
- id="org.argeo.slc.client.ui.updateModule"
- name="Update Module">
- </command>
-
- <!-- Commands that do not need dependency injection -->
- <command
- defaultHandler="org.argeo.slc.client.ui.commands.AddResultFolder"
- id="org.argeo.slc.client.ui.addResultFolder"
- name="Add result folder">
- </command>
- <command
- id="org.argeo.slc.client.ui.deleteItems"
- defaultHandler="org.argeo.slc.client.ui.commands.DeleteItems"
- name="Delete selected item(s)">
- </command>
- <command
- defaultHandler="org.argeo.slc.client.ui.commands.RenameResultFolder"
- id="org.argeo.slc.client.ui.renameResultFolder"
- name="Rename folder">
- </command>
- <command
- defaultHandler="org.argeo.slc.client.ui.commands.RenameResultNode"
- id="org.argeo.slc.client.ui.renameResultNode"
- name="Rename result">
- </command>
- <command
- defaultHandler="org.argeo.slc.client.ui.commands.RefreshJcrResultTreeView"
- id="org.argeo.slc.client.ui.refreshJcrResultTreeView"
- name="Refresh">
- <commandParameter
- id="org.argeo.slc.client.ui.param.refreshType"
- name="Refresh type">
- </commandParameter>
- </command>
- </extension>
-
- <!-- Menu definitions -->
- <extension
- id="menu:org.eclipse.ui.main.menu"
- point="org.eclipse.ui.menus">
- <menuContribution
- locationURI="toolbar:org.argeo.slc.client.ui.jcrExecutionModulesView">
- <command
- commandId="org.argeo.slc.client.ui.updateModule"
- icon="icons/refresh.png"
- label="Update module"
- tooltip="Update module">
- </command>
- </menuContribution>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- class="org.argeo.slc.client.ui.SlcExecutionPerspective"
- icon="icons/slc_execution_perspective.gif"
- id="org.argeo.slc.client.ui.slcExecutionPerspective"
- name="SLC Execution">
- </perspective>
- </extension>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="org.argeo.eclipse.spring.SpringExtensionFactory"
- default="false"
- icon="icons/batch.gif"
- id="org.argeo.slc.client.ui.processEditor"
- name="Process">
- </editor>
- </extension>
- <extension
- point="org.eclipse.ui.elementFactories">
- <factory
- class="org.argeo.slc.client.ui.editors.ProcessEditorInputFactory"
- id="org.argeo.slc.client.ui.processEditorInputFactory">
- </factory>
- </extension>
- <extension
- point="org.eclipse.ui.activities">
- </extension>
- <extension
- point="org.eclipse.ui.activities">
- <activity
- description="SLC users"
- id="org.argeo.slc.client.ui.slcActivity"
- name="SLC">
- <enabledWhen>
- <with variable="roles">
- <iterate ifEmpty="false" operator="or">
- <equals value="cn=org.argeo.slc.user,ou=roles,ou=node" />
- </iterate>
- </with>
- </enabledWhen>
- </activity>
- <!-- TODO: find a way to exclude evrything -->
- <activityPatternBinding
- activityId="org.argeo.slc.client.ui.slcActivity"
- isEqualityPattern="true"
- pattern="org.argeo.slc.client.ui/org.argeo.slc.client.ui.slcExecutionPerspective">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.argeo.security.ui.adminActivity"
- isEqualityPattern="true"
- pattern="org.argeo.slc.client.ui/org.argeo.slc.client.ui.slcExecutionPerspective">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.argeo.security.ui.adminActivity"
- isEqualityPattern="true"
- pattern="org.argeo.jcr.ui.explorer/org.argeo.jcr.ui.explorer.perspective">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.argeo.security.ui.adminActivity"
- isEqualityPattern="true"
- pattern="org.argeo.security.ui/org.argeo.security.ui.userHomePerspective">
- </activityPatternBinding>
- </extension>
-</plugin>
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.ui</artifactId>
- <name>SLC Client UI</name>
- <packaging>jar</packaging>
- <dependencies>
- <!-- SLC -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.spring</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Argeo Commons -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.swt</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.rap</groupId>
- <artifactId>org.argeo.swt.specific.rap</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc.legacy.commons</groupId>
- <artifactId>org.argeo.cms.ui.workbench</artifactId>
- <version>${version.argeo-commons-legacy}</version>
- </dependency>
-
- <!-- RAP workbench -->
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>argeo-tp-rap-e3</artifactId>
- <version>${version.argeo-tp}</version>
- <type>pom</type>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
+++ /dev/null
-package org.argeo.slc.client.ui;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.BasicNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.deploy.ModulesManager;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/** The activator class controls the plug-in life cycle */
-public class ClientUiPlugin extends AbstractUIPlugin implements SlcNames {
- public static final String ID = "org.argeo.slc.client.ui";
- private static ClientUiPlugin plugin;
-
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- public static ClientUiPlugin getDefault() {
- return plugin;
- }
-
- /** Creates the image */
- public static Image img(String path) {
- return getImageDescriptor(path).createImage();
- }
-
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(ID, path);
- }
-
- /** Start execution module if it was stopped and vice-versa */
- public static void startStopExecutionModule(
- final ModulesManager modulesManager, Node node) {
- try {
- if (!node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE))
- throw new SlcException(node + " is not an execution module");
-
- String name = node.getProperty(SLC_NAME).getString();
- String version = node.getProperty(SLC_VERSION).getString();
- final NameVersion nameVersion = new BasicNameVersion(name, version);
- Boolean started = node.getProperty(SLC_STARTED).getBoolean();
-
- Job job;
- if (started) {
- job = new Job("Stop " + nameVersion) {
- protected IStatus run(IProgressMonitor monitor) {
- monitor.beginTask("Stop " + nameVersion, 1);
- modulesManager.stop(nameVersion);
- monitor.worked(1);
- return Status.OK_STATUS;
- }
-
- protected void canceling() {
- getThread().interrupt();
- super.canceling();
- }
- };
- } else {
- job = new Job("Start " + nameVersion) {
- protected IStatus run(IProgressMonitor monitor) {
- monitor.beginTask("Start " + nameVersion, 1);
- modulesManager.start(nameVersion);
- monitor.worked(1);
- return Status.OK_STATUS;
- }
-
- protected void canceling() {
- getThread().interrupt();
- super.canceling();
- }
- };
- }
- job.setUser(true);
- job.schedule();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot start " + node, e);
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui;
-
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-/** Perspective to manage SLC execution flows. */
-public class SlcExecutionPerspective implements IPerspectiveFactory {
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
- layout.setFixed(false);
-
- IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT,
- 0.35f, editorArea);
- left.addView(ClientUiPlugin.ID + ".jcrExecutionModulesView");
- // left.addView(ClientUiPlugin.ID + ".jcrResultListView");
- left.addView(ClientUiPlugin.ID + ".jcrResultTreeView");
- // Sleak view for SWT resource debugging
- // left.addView("org.eclipse.swt.tools.views.SleakView");
-
- IFolderLayout bottom = layout.createFolder("bottom",
- IPageLayout.BOTTOM, 0.65f, editorArea);
-// BOTTOM.ADDVIEW(SECURITYUIPLUGIN.PLUGIN_ID + ".LOGVIEW");
- bottom.addView(ClientUiPlugin.ID + ".jcrProcessListView");
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui;
-
-import static org.argeo.slc.client.ui.ClientUiPlugin.getImageDescriptor;
-import static org.argeo.slc.client.ui.ClientUiPlugin.img;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-
-/** Shared images. */
-public class SlcImages {
- public final static Image AGENT = img("icons/agent.gif");
- public final static Image AGENT_FACTORY = img("icons/agentFactory.gif");
- public final static Image MODULE = img("icons/module.png");
- public final static Image MODULE_STOPPED = img("icons/module_stopped.gif");
- public final static Image FOLDER = img("icons/folder.gif");
- public final static Image MY_RESULTS_FOLDER = img("icons/myResult.png");
- public final static Image RENAME = img("icons/rename.png");
- public final static Image FLOW = img("icons/flow.png");
- public final static Image PROCESSES = img("icons/processes.gif");
- public final static Image PASSED = img("icons/passed.gif");
- public final static Image ERROR = img("icons/error.gif");
- public final static Image LAUNCH = img("icons/launch.gif");
- public final static Image RELAUNCH = img("icons/relaunch.gif");
- public final static Image KILL = img("icons/kill.png");
- public final static Image REMOVE_ONE = img("icons/remove_one.gif");
- public final static Image REMOVE_ALL = img("icons/removeAll.png");
- public final static Image EXECUTION_SPECS = img("icons/executionSpecs.gif");
- public final static Image EXECUTION_SPEC = img("icons/executionSpec.gif");
- public final static Image EXECUTION_SPEC_ATTRIBUTE = img("icons/executionSpecAttribute.gif");
- public final static Image CHOICES = img("icons/choices.gif");
- public final static Image PROCESS_ERROR = img("icons/process_error.png");
- public final static Image PROCESS_SCHEDULED = img("icons/process_scheduled.gif");
- public final static Image PROCESS_RUNNING = img("icons/process_running.png");
- public final static Image PROCESS_COMPLETED = img("icons/process_completed.png");
-
- // Decorators
- public final static ImageDescriptor EXECUTION_ERROR = getImageDescriptor("icons/executionError.gif");
- public final static ImageDescriptor EXECUTION_PASSED = getImageDescriptor("icons/executionPassed.gif");
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui;
-
-/** SLC UI common constants */
-public interface SlcUiConstants {
-
- /*
- * Labels
- */
- public final static String DEFAULT_MY_RESULTS_FOLDER_LABEL = "My Results";
-
- /*
- * MISCEALLENEOUS
- */
- public final static String DEFAULT_DISPLAY_DATE_TIME_FORMAT = "yyyy-MM-dd, HH:mm:ss";
-}
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.model.ParentNodeFolder;
-import org.argeo.slc.client.ui.model.ResultFolder;
-import org.argeo.slc.jcr.SlcJcrResultUtils;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Add a new SlcType.SLC_RESULT_FOLDER node to the current user "my result"
- * tree. This handler is only intended to bu used with JcrResultTreeView and its
- * descendants.
- */
-
-public class AddResultFolder extends AbstractHandler {
- public final static String ID = ClientUiPlugin.ID + ".addResultFolder";
- public final static String DEFAULT_ICON_REL_PATH = "icons/addFolder.gif";
- public final static String DEFAULT_LABEL = "Add folder...";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IStructuredSelection selection = (IStructuredSelection) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();
-
- // Sanity check, already done when populating the corresponding popup
- // menu.
- if (selection != null && selection.size() == 1) {
- Object obj = selection.getFirstElement();
- try {
- Node parentNode = null;
- if (obj instanceof ResultFolder) {
- ResultFolder rf = (ResultFolder) obj;
- parentNode = rf.getNode();
- } else if (obj instanceof ParentNodeFolder) {
- Node node = ((ParentNodeFolder) obj).getNode();
- if (node.getPath().startsWith(
- SlcJcrResultUtils.getMyResultsBasePath(node
- .getSession())))
- parentNode = node;
- }
-
- if (parentNode != null) {
- String folderName = SingleValue.ask("Folder name",
- "Enter folder name");
- if (folderName != null) {
- if (folderName.contains("/")) {
- ErrorFeedback
- .show("Folder names can't contain a '/'.");
- return null;
- }
-
- String absPath = parentNode.getPath() + "/"
- + folderName;
- SlcJcrResultUtils.createResultFolderNode(
- parentNode.getSession(), absPath);
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while creating result folder", e);
- }
- } else {
- ErrorFeedback.show("Can only add file folder to a node");
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.model.ResultFolder;
-import org.argeo.slc.client.ui.model.ResultParent;
-import org.argeo.slc.client.ui.model.ResultParentUtils;
-import org.argeo.slc.client.ui.model.SingleResultNode;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Deletes one or many results */
-public class DeleteItems extends AbstractHandler {
- public final static String ID = ClientUiPlugin.ID + ".deleteItems";
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin
- .getImageDescriptor("icons/removeAll.png");
- public final static String DEFAULT_LABEL = "Delete selected item(s)";
-
- public Object execute(final ExecutionEvent event) throws ExecutionException {
- final ISelection selection = HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();
-
- // confirmation
- StringBuilder buf = new StringBuilder("");
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();
- while (lst.hasNext()) {
- Object obj = lst.next();
- if (obj instanceof ResultParent) {
- ResultParent rp = ((ResultParent) obj);
- buf.append(rp.getName()).append(", ");
- }
- }
-
- String msg = "Nothing to delete";
- // remove last separator
- if (buf.lastIndexOf(", ") > -1) {
- msg = "Do you want to delete following objects (and their children): "
- + buf.substring(0, buf.lastIndexOf(", ")) + "?";
- }
- Boolean ok = MessageDialog.openConfirm(
- HandlerUtil.getActiveShell(event), "Confirm deletion", msg);
-
- if (!ok)
- return null;
-
- Job job = new Job("Delete results") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- if (selection != null
- && selection instanceof IStructuredSelection) {
- Map<String, Node> nodes = new HashMap<String, Node>();
- Iterator<?> it = ((IStructuredSelection) selection)
- .iterator();
- Object obj = null;
- try {
-
- while (it.hasNext()) {
- obj = it.next();
- if (obj instanceof ResultFolder) {
- Node node = ((ResultFolder) obj).getNode();
- nodes.put(node.getPath(), node);
- } else if (obj instanceof SingleResultNode) {
- Node node = ((SingleResultNode) obj).getNode();
- nodes.put(node.getPath(), node);
- }
- }
- if (!nodes.isEmpty()) {
- Session session = null;
- monitor.beginTask("Delete results", nodes.size());
- for (String path : nodes.keySet()) {
- if (session == null)
- session = nodes.get(path).getSession();
-
- // check if the item has not already been
- // deleted while deleting one of its ancestor
- if (session.itemExists(path)) {
- Node parent = nodes.get(path).getParent();
- nodes.get(path).remove();
- ResultParentUtils.updatePassedStatus(
- parent, true);
- }
- monitor.worked(1);
- }
- session.save();
- }
-
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected error while deleteting node(s)", e);
- }
- monitor.done();
- }
- return Status.OK_STATUS;
- }
-
- };
- job.setUser(true);
- job.schedule();
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import java.util.Iterator;
-
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.model.ResultParent;
-import org.argeo.slc.client.ui.views.JcrResultTreeView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Force refresh the ResultTreeView. This command is only intended to be called
- * by either the toolbar menu of the view or by the popup menu. Refresh due to
- * data changes must be triggered by Observers
- */
-public class RefreshJcrResultTreeView extends AbstractHandler {
- public final static String ID = ClientUiPlugin.ID
- + ".refreshJcrResultTreeView";
- public final static String PARAM_REFRESH_TYPE = ClientUiPlugin.ID
- + ".param.refreshType";
- public final static String PARAM_REFRESH_TYPE_FULL = "fullRefresh";
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin
- .getImageDescriptor("icons/refresh.png");
- public final static String DEFAULT_LABEL = "Refresh selected";
-
- public Object execute(final ExecutionEvent event) throws ExecutionException {
- String refreshType = event.getParameter(PARAM_REFRESH_TYPE);
- JcrResultTreeView view = (JcrResultTreeView) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .getActivePart();
-
- // force full refresh without preserving selection from the tool bar
- if (PARAM_REFRESH_TYPE_FULL.equals(refreshType))
- view.refresh(null);
- else {
- IStructuredSelection selection = (IStructuredSelection) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage()
- .getSelection();
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- while (it.hasNext()) {
- Object obj = it.next();
- if (obj instanceof ResultParent) {
- view.refresh((ResultParent) obj);
- }
- }
- }
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.model.ResultFolder;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Rename a node of type SlcType.SLC_RESULT_FOLDER by moving it.
- */
-
-public class RenameResultFolder extends AbstractHandler {
- public final static String ID = ClientUiPlugin.ID + ".renameResultFolder";
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin
- .getImageDescriptor("icons/rename.png");
- public final static String DEFAULT_LABEL = "Rename...";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IStructuredSelection selection = (IStructuredSelection) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();
-
- // Sanity check, already done when populating the corresponding popup
- // menu.
- if (selection != null && selection.size() == 1) {
- Object obj = selection.getFirstElement();
- try {
- if (obj instanceof ResultFolder) {
- ResultFolder rf = (ResultFolder) obj;
- Node sourceNode = rf.getNode();
- String folderName = SingleValue.ask("Rename folder",
- "Enter a new folder name");
- if (folderName != null) {
- String sourcePath = sourceNode.getPath();
- String targetPath = JcrUtils.parentPath(sourcePath)
- + "/" + folderName;
- Session session = sourceNode.getSession();
- session.move(sourcePath, targetPath);
- session.save();
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while refactoring result folder",
- e);
- }
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.eclipse.ui.dialogs.SingleValue;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.model.SingleResultNode;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Rename a node of type SlcType.SLC_RESULT_FOLDER by moving it.
- */
-
-public class RenameResultNode extends AbstractHandler {
- public final static String ID = ClientUiPlugin.ID + ".renameResultNode";
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin
- .getImageDescriptor("icons/rename.png");
- public final static String DEFAULT_LABEL = "Rename result";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IStructuredSelection selection = (IStructuredSelection) HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();
-
- // Sanity check, already done when populating the corresponding popup
- // menu.
- if (selection != null && selection.size() == 1) {
- Object obj = selection.getFirstElement();
- try {
- if (obj instanceof SingleResultNode) {
- SingleResultNode rf = (SingleResultNode) obj;
- Node sourceNode = rf.getNode();
- String folderName = SingleValue.ask("Rename result",
- "Enter a new result name");
- if (folderName != null) {
-
- if (sourceNode.getParent().hasNode(folderName)) {
- MessageDialog
- .openError(Display.getDefault()
- .getActiveShell(), "Error",
- "Another object with the same name already exists.");
- return null;
- }
-
- String sourcePath = sourceNode.getPath();
- String targetPath = JcrUtils.parentPath(sourcePath)
- + "/" + folderName;
- Session session = sourceNode.getSession();
- session.move(sourcePath, targetPath);
- session.getNode(targetPath).setProperty(
- Property.JCR_TITLE, folderName);
- session.save();
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception while refactoring result folder",
- e);
- }
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.execution.ExecutionFlowDescriptor;
-import org.argeo.slc.execution.ExecutionModulesManager;
-import org.argeo.slc.execution.RealizedFlow;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.IParameter;
-
-@Deprecated
-public class RunSlcFlow extends AbstractHandler {
- private ExecutionModulesManager modulesManager;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- Command command = event.getCommand();
- String name = command.getName();
- String module = name.substring(0, name.indexOf(':'));
- String flowName = name.substring(name.indexOf(':') + 1);
-
- final RealizedFlow realizedFlow = new RealizedFlow();
- realizedFlow.setModuleName(module);
- // FIXME deal with version
- String version = "0.0.0";
- realizedFlow.setModuleVersion(version);
- ExecutionFlowDescriptor efd = new ExecutionFlowDescriptor();
- efd.setName(flowName);
-
- Map<String, Object> values = new HashMap<String, Object>();
- if (command.getParameters() != null) {
- for (IParameter param : command.getParameters()) {
- String argName = param.getId();
- // FIXME make it safer
- Object value = param.getValues().getParameterValues()
- .values().iterator().next();
- values.put(argName, value);
- }
- efd.setValues(values);
- }
- realizedFlow.setFlowDescriptor(efd);
- // new Thread("SLC Flow " + name + " from Eclipse command "
- // + command.getId()) {
- // public void run() {
- modulesManager.start(realizedFlow.getModuleNameVersion());
- modulesManager.execute(realizedFlow);
- // }
- // }.start();
- return null;
- } catch (Exception e) {
- throw new SlcException("Could not execute command "
- + event.getCommand() + " as SLC flow", e);
- }
- }
-
- public void setModulesManager(
- ExecutionModulesManager executionModulesManager) {
- this.modulesManager = executionModulesManager;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.commands;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.jcr.Node;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.BasicNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.deploy.ModulesManager;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Deletes one or many results */
-public class UpdateModule extends AbstractHandler {
- private final static CmsLog log = CmsLog.getLog(UpdateModule.class);
-
- private ModulesManager modulesManager;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final ISelection selection = HandlerUtil
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();
- if (selection != null && selection instanceof IStructuredSelection) {
- UpdateJob job = new UpdateJob(selection);
- job.setUser(true);
- job.schedule();
- }
- return null;
- }
-
- private class UpdateJob extends Job {
- private final IStructuredSelection selection;
-
- public UpdateJob(ISelection selection) {
- super("Update modules");
- this.selection = ((IStructuredSelection) selection);
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- Iterator<?> it = selection.iterator();
- Object obj = null;
- try {
- Map<String, Node> nodes = new HashMap<String, Node>();
- nodes: while (it.hasNext()) {
- obj = it.next();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- Node executionModuleNode = null;
- while (executionModuleNode == null) {
- if (node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE)) {
- executionModuleNode = node;
- }
- node = node.getParent();
- if (node.getPath().equals("/"))// root
- continue nodes;
- }
-
- if (!nodes.containsKey(executionModuleNode.getPath()))
- nodes.put(executionModuleNode.getPath(),
- executionModuleNode);
- }
- }
-
- monitor.beginTask("Update modules", nodes.size());
- for (Node executionModuleNode : nodes.values()) {
- monitor.subTask("Update " + executionModuleNode.getName());
- NameVersion nameVersion = new BasicNameVersion(
- executionModuleNode.getProperty(SlcNames.SLC_NAME)
- .getString(), executionModuleNode
- .getProperty(SlcNames.SLC_VERSION)
- .getString());
- modulesManager.upgrade(nameVersion);
- monitor.worked(1);
- log.info("Module " + nameVersion + " updated");
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- }
- return Status.OK_STATUS;
- } catch (Exception e) {
- throw new SlcException("Cannot update module " + obj, e);
- // return Status.CANCEL_STATUS;
- }
- }
-
- @Override
- protected void canceling() {
- getThread().interrupt();
- super.canceling();
- }
-
- }
-
- public void setModulesManager(ModulesManager modulesManager) {
- this.modulesManager = modulesManager;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.controllers;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.execution.ExecutionProcess;
-import org.argeo.slc.execution.SlcAgent;
-import org.argeo.slc.jcr.execution.JcrExecutionProcess;
-
-/**
- * We use a separate class (not in UI components) so that it can be a singleton
- * in an application context.
- */
-public class ProcessController {
- // private final static Log log =
- // LogFactory.getLog(ProcessController.class);
- // private Map<String, SlcAgentFactory> agentFactories = new HashMap<String,
- // SlcAgentFactory>();
-
- private SlcAgent agent;
-
- public ExecutionProcess process(Node processNode) {
- JcrExecutionProcess process = new JcrExecutionProcess(processNode);
- try {
- SlcAgent slcAgent = findAgent(processNode);
- if (slcAgent == null)
- throw new SlcException("Cannot find agent for " + processNode);
- slcAgent.process(process);
- return process;
- } catch (Exception e) {
- if (!process.getStatus().equals(ExecutionProcess.ERROR))
- process.setStatus(ExecutionProcess.ERROR);
- throw new SlcException("Cannot execute " + processNode, e);
- }
- }
-
- public void kill(Node processNode) {
- JcrExecutionProcess process = new JcrExecutionProcess(processNode);
- try {
- SlcAgent slcAgent = findAgent(processNode);
- if (slcAgent == null)
- throw new SlcException("Cannot find agent for " + processNode);
- slcAgent.kill(process.getUuid());
- } catch (Exception e) {
- if (!process.getStatus().equals(ExecutionProcess.ERROR))
- process.setStatus(ExecutionProcess.ERROR);
- throw new SlcException("Cannot execute " + processNode, e);
- }
- }
-
- /** Always return the default runtime agent */
- protected SlcAgent findAgent(Node processNode) throws RepositoryException {
- // we currently only deal with single agents
- // Node realizedFlowNode = processNode.getNode(SlcNames.SLC_FLOW);
- // NodeIterator nit = realizedFlowNode.getNodes();
- // if (nit.hasNext()) {
- // // TODO find a better way to determine which agent to use
- // // currently we check the agent of the first registered flow
- // Node firstRealizedFlow = nit.nextNode();
- // // we assume there is an nt:address
- // String firstFlowPath = firstRealizedFlow
- // .getNode(SlcNames.SLC_ADDRESS)
- // .getProperty(Property.JCR_PATH).getString();
- // Node flowNode = processNode.getSession().getNode(firstFlowPath);
- // String agentFactoryPath = SlcJcrUtils
- // .flowAgentFactoryPath(firstFlowPath);
- // if (!agentFactories.containsKey(agentFactoryPath))
- // throw new SlcException("No agent factory registered under "
- // + agentFactoryPath);
- // SlcAgentFactory agentFactory = agentFactories.get(agentFactoryPath);
- // Node agentNode = ((Node) flowNode
- // .getAncestor(SlcJcrUtils.AGENT_FACTORY_DEPTH + 1));
- // String agentUuid = agentNode.getProperty(SlcNames.SLC_UUID)
- // .getString();
- //
- // // process
- // return agentFactory.getAgent(agentUuid);
- // }
-
- return agent;
- }
-
- public void setAgent(SlcAgent agent) {
- this.agent = agent;
- }
-
- // public synchronized void register(SlcAgentFactory agentFactory,
- // Map<String, String> properties) {
- // String path = properties.get(SlcJcrConstants.PROPERTY_PATH);
- // if (log.isDebugEnabled())
- // log.debug("Agent factory registered under " + path);
- // agentFactories.put(path, agentFactory);
- // }
- //
- // public synchronized void unregister(SlcAgentFactory agentFactory,
- // Map<String, String> properties) {
- // String path = properties.get(SlcJcrConstants.PROPERTY_PATH);
- // if (log.isDebugEnabled())
- // log.debug("Agent factory unregistered from " + path);
- // agentFactories.remove(path);
- // }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.decorators;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.client.ui.SlcUiConstants;
-import org.argeo.slc.client.ui.model.ResultFolder;
-import org.argeo.slc.client.ui.model.ResultParent;
-import org.argeo.slc.client.ui.model.SingleResultNode;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.DecorationOverlayIcon;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-
-/** Dynamically decorates the results tree. */
-public class ResultFailedDecorator extends LabelProvider implements
- ILabelDecorator {
-
- // FIXME why not use? org.eclipse.jface.viewers.DecoratingLabelProvider
-
- // private final static CmsLog log = CmsLog
- // .getLog(ResultFailedDecorator.class);
-
- private final static DateFormat dateFormat = new SimpleDateFormat(
- SlcUiConstants.DEFAULT_DISPLAY_DATE_TIME_FORMAT);
-
- // hack for SWT resource leak
- // see http://www.eclipse.org/articles/swt-design-2/swt-design-2.html
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=181215
- private final Image passedFolder;
- private final Image failedFolder;
- private final Image failedSingleResult;
- private final Image errorSingleResult;
- private final Image passedSingleResult;
-
- public ResultFailedDecorator() {
- super();
- ImageDescriptor failedDesc = ClientUiPlugin.getDefault().getWorkbench()
- .getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR);
- failedFolder = new DecorationOverlayIcon(SlcImages.FOLDER, failedDesc,
- IDecoration.TOP_LEFT).createImage();
- passedFolder = new DecorationOverlayIcon(SlcImages.FOLDER,
- SlcImages.EXECUTION_PASSED, IDecoration.TOP_LEFT).createImage();
- failedSingleResult = new DecorationOverlayIcon(
- SlcImages.PROCESS_COMPLETED, failedDesc, IDecoration.TOP_LEFT)
- .createImage();
- errorSingleResult = new DecorationOverlayIcon(
- SlcImages.PROCESS_COMPLETED, SlcImages.EXECUTION_ERROR,
- IDecoration.TOP_LEFT).createImage();
- passedSingleResult = new DecorationOverlayIcon(
- SlcImages.PROCESS_COMPLETED, SlcImages.EXECUTION_PASSED,
- IDecoration.TOP_LEFT).createImage();
- }
-
- // Method to decorate Image
- public Image decorateImage(Image image, Object object) {
-
- // This method returns an annotated image or null if the
- // image need not be decorated. Returning a null image
- // decorates resource icon with basic decorations provided
- // by Eclipse
- if (object instanceof ResultParent) {
- if (((ResultParent) object).isPassed()) {
- if (object instanceof SingleResultNode)
- return passedSingleResult;
- else if (object instanceof ResultFolder)
- return passedFolder;
- else
- return null;
- } else {
- // ImageDescriptor desc = ClientUiPlugin.getDefault()
- // .getWorkbench().getSharedImages()
- // .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR);
- // DecorationOverlayIcon decoratedImage = new
- // DecorationOverlayIcon(
- // image, desc, IDecoration.TOP_LEFT);
- // return decoratedImage.createImage();
- if (object instanceof SingleResultNode) {
- SingleResultNode srn = (SingleResultNode) object;
- boolean isError = false;
- try {
- isError = srn.getNode()
- .getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .hasProperty(SlcNames.SLC_ERROR_MESSAGE);
- } catch (RepositoryException re) {
- // Silent node might not exist
- }
- if (isError)
- return errorSingleResult;
- else
- return failedSingleResult;
-
- } else
- return failedFolder;
- }
- }
- return null;
- }
-
- // Method to decorate Text
- public String decorateText(String label, Object object) {
- if (object instanceof SingleResultNode) {
- SingleResultNode srNode = (SingleResultNode) object;
- Node node = srNode.getNode();
- String decoration = null;
- try {
- if (node.hasProperty(SlcNames.SLC_COMPLETED))
- decoration = dateFormat.format(node
- .getProperty(SlcNames.SLC_COMPLETED).getDate()
- .getTime());
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error defining text decoration for result",
- re);
- }
- return label + " [" + decoration + "]";
- } else
- return null;
- }
-
- @Override
- public void dispose() {
- failedFolder.dispose();
- failedSingleResult.dispose();
- super.dispose();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.editors;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.jcr.LoginException;
-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 javax.jcr.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.observation.ObservationManager;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryManager;
-
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.execution.ExecutionProcess;
-import org.argeo.slc.jcr.SlcJcrUtils;
-import org.argeo.slc.primitive.PrimitiveAccessor;
-import org.argeo.slc.primitive.PrimitiveUtils;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ColumnViewer;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowData;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/** Definition of the process. */
-public class ProcessBuilderPage extends FormPage implements SlcNames {
- // private final static Log log =
- // LogFactory.getLog(ProcessBuilderPage.class);
-
- public final static String ID = "processBuilderPage";
-
- /** To be displayed in empty lists */
- final static String NONE = "<none>";
-
- private Node processNode;
- private Session agentSession;
-
- private TreeViewer flowsViewer;
- private TableViewer valuesViewer;
- private Label statusLabel;
- private Button run;
- private Button remove;
- private Button clear;
-
- private AbstractFormPart formPart;
- private EventListener statusObserver;
-
- public ProcessBuilderPage(ProcessEditor editor, Node processNode) {
- super(editor, ID, "Definition");
- this.processNode = processNode;
- try {
- this.agentSession = processNode.getSession().getRepository().login();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot open agent session", e);
- }
- }
-
- @Override
- protected void createFormContent(IManagedForm mf) {
- try {
- ScrolledForm form = mf.getForm();
- form.setExpandHorizontal(true);
- form.setExpandVertical(true);
- form.setText("Process " + processNode.getName());
- GridLayout mainLayout = new GridLayout(1, true);
- form.getBody().setLayout(mainLayout);
-
- createControls(form.getBody());
- createBuilder(form.getBody());
-
- // form
- formPart = new AbstractFormPart() {
-
- };
- getManagedForm().addPart(formPart);
-
- // observation
- statusObserver = new AsyncUiEventListener(form.getDisplay()) {
- protected void onEventInUiThread(List<Event> events) {
- statusChanged();
- }
- };
- ObservationManager observationManager = processNode.getSession().getWorkspace().getObservationManager();
- observationManager.addEventListener(statusObserver, Event.PROPERTY_CHANGED, processNode.getPath(), true,
- null, null, false);
-
- // make sure all controls are in line with status
- statusChanged();
-
- // add initial flows
- addInitialFlows();
-
- } catch (RepositoryException e) {
- throw new SlcException("Cannot create form content", e);
- }
- }
-
- protected void createControls(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
-
- Composite controls = tk.createComposite(parent);
- controls.setLayout(new RowLayout());
- controls.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- run = tk.createButton(controls, null, SWT.PUSH);
- run.setToolTipText("Run");
- run.setImage(SlcImages.LAUNCH);
- run.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- if (isFinished(getProcessStatus())) {
- ((ProcessEditor) getEditor()).relaunch();
- } else if (isRunning(getProcessStatus())) {
- ((ProcessEditor) getEditor()).kill();
- } else {
- ((ProcessEditor) getEditor()).process();
- }
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
-
- remove = tk.createButton(controls, null, SWT.PUSH);
- remove.setImage(SlcImages.REMOVE_ONE);
- remove.setToolTipText("Remove selected flows");
- remove.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- removeSelectedFlows();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
-
- clear = tk.createButton(controls, null, SWT.PUSH);
- clear.setImage(SlcImages.REMOVE_ALL);
- clear.setToolTipText("Clear all flows");
- clear.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- removeAllFlows();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
-
- Composite statusComposite = tk.createComposite(controls);
- RowData rowData = new RowData();
- rowData.width = 100;
- rowData.height = 16;
- statusComposite.setLayoutData(rowData);
- statusComposite.setLayout(new FillLayout());
- statusLabel = tk.createLabel(statusComposite, getProcessStatus());
-
- }
-
- protected void createBuilder(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);
- sashForm.setSashWidth(4);
- GridData sahFormGd = new GridData(SWT.FILL, SWT.FILL, true, true);
- sahFormGd.widthHint = 400;
- sashForm.setLayoutData(sahFormGd);
-
- Composite flowsComposite = tk.createComposite(sashForm);
- flowsComposite.setLayout(new GridLayout(1, false));
-
- flowsViewer = new TreeViewer(flowsComposite);
- flowsViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- flowsViewer.setLabelProvider(new FlowsLabelProvider());
- flowsViewer.setContentProvider(new FlowsContentProvider());
- flowsViewer.addSelectionChangedListener(new FlowsSelectionListener());
-
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- flowsViewer.addDropSupport(operations, tt, new FlowsDropListener(flowsViewer));
-
- // Context menu
- addContextMenu();
-
- flowsViewer.setInput(getEditorSite());
- flowsViewer.setInput(processNode);
-
- Composite valuesComposite = tk.createComposite(sashForm);
- valuesComposite.setLayout(new GridLayout(1, false));
-
- valuesViewer = new TableViewer(valuesComposite);
- GridData valuedGd = new GridData(SWT.FILL, SWT.FILL, true, true);
- // valuedGd.widthHint = 200;
- valuesViewer.getTable().setLayoutData(valuedGd);
- valuesViewer.getTable().setHeaderVisible(true);
-
- valuesViewer.setContentProvider(new ValuesContentProvider());
- initializeValuesViewer(valuesViewer);
- sashForm.setWeights(getWeights());
- valuesViewer.setInput(getEditorSite());
- }
-
- /** Creates the columns of the values viewer */
- protected void initializeValuesViewer(TableViewer viewer) {
- String[] titles = { "Name", "Value" };
- int[] bounds = { 200, 100 };
-
- for (int i = 0; i < titles.length; i++) {
- TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setText(titles[i]);
- column.getColumn().setWidth(bounds[i]);
- column.getColumn().setResizable(true);
- column.getColumn().setMoveable(true);
- if (i == 0) {
- column.setLabelProvider(new ColumnLabelProvider() {
- public String getText(Object element) {
- try {
- Node specAttrNode = (Node) element;
- return specAttrNode.getName();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get value", e);
- }
- }
- });
- } else if (i == 1) {
- column.setLabelProvider(new ColumnLabelProvider() {
- public String getText(Object element) {
- return getAttributeSpecText((Node) element);
- }
- });
- column.setEditingSupport(new ValuesEditingSupport(viewer));
- }
-
- }
- Table table = viewer.getTable();
- table.setHeaderVisible(false);
- table.setLinesVisible(true);
- }
-
- protected int[] getWeights() {
- return new int[] { 50, 50 };
- }
-
- /*
- * CONTROLLERS
- */
- /** Reflects a status change */
- protected void statusChanged() {
- String status = getProcessStatus();
- statusLabel.setText(status);
- Boolean isEditable = isEditable(status);
- run.setEnabled(status.equals(ExecutionProcess.RUNNING) || isEditable);
- remove.setEnabled(isEditable);
- clear.setEnabled(isEditable);
- // flowsViewer.getTree().setEnabled(isEditable);
- if (status.equals(ExecutionProcess.RUNNING)) {
- run.setEnabled(true);
- run.setImage(SlcImages.KILL);
- run.setToolTipText("Kill");
- } else if (isFinished(status)) {
- run.setEnabled(true);
- run.setImage(SlcImages.RELAUNCH);
- run.setToolTipText("Relaunch");
- }
-
- if (flowsViewer != null)
- flowsViewer.refresh();
- }
-
- /** Adds initial flows from the editor input if any */
- protected void addInitialFlows() {
- for (String path : ((ProcessEditorInput) getEditorInput()).getInitialFlowPaths()) {
- addFlow(path);
- }
- }
-
- /**
- * Adds a new flow.
- *
- * @param path the path of the flow
- */
- protected void addFlow(String path) {
- try {
- Node flowNode = agentSession.getNode(path);
- Node realizedFlowNode = processNode.getNode(SLC_FLOW).addNode(SLC_FLOW);
- realizedFlowNode.setProperty(SLC_NAME, flowNode.getProperty(SLC_NAME).getString());
- realizedFlowNode.addMixin(SlcTypes.SLC_REALIZED_FLOW);
- Node address = realizedFlowNode.addNode(SLC_ADDRESS, NodeType.NT_ADDRESS);
- address.setProperty(Property.JCR_PATH, path);
-
- // copy spec attributes
- Node specAttrsBase;
- if (flowNode.hasProperty(SLC_SPEC)) {
- Node executionSpecNode = flowNode.getProperty(SLC_SPEC).getNode();
- specAttrsBase = executionSpecNode;
- String executionSpecName = executionSpecNode.getProperty(SLC_NAME).getString();
- realizedFlowNode.setProperty(SLC_SPEC, executionSpecName);
- } else
- specAttrsBase = flowNode;
-
- specAttrs: for (NodeIterator nit = specAttrsBase.getNodes(); nit.hasNext();) {
- Node specAttrNode = nit.nextNode();
- String attrName = specAttrNode.getName();
- if (!specAttrNode.isNodeType(SlcTypes.SLC_EXECUTION_SPEC_ATTRIBUTE))
- continue specAttrs;
- Node realizedAttrNode = realizedFlowNode.addNode(specAttrNode.getName());
- JcrUtils.copy(specAttrNode, realizedAttrNode);
-
- // override with flow value
- if (flowNode.hasNode(attrName)) {
- // assuming this is a primitive
- Node attrNode = flowNode.getNode(attrName);
- if (attrNode.hasProperty(SLC_VALUE))
- realizedAttrNode.setProperty(SLC_VALUE, attrNode.getProperty(SLC_VALUE).getValue());
- }
- }
-
- // Part title
- StringBuilder editorTitle = new StringBuilder();
- NodeIterator it = realizedFlowNode.getParent().getNodes(SLC_FLOW);
- while (it.hasNext()) {
- Node rFlowNode = it.nextNode();
- String name = rFlowNode.getProperty(SLC_NAME).getString();
- editorTitle.append(name).append(' ');
- }
- ((ProcessEditor) getEditor()).setEditorTitle(editorTitle.toString());
-
- flowsViewer.refresh();
- formPart.markDirty();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot add flow " + path, e);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected void removeSelectedFlows() {
- if (!flowsViewer.getSelection().isEmpty()) {
- Iterator<Object> it = ((StructuredSelection) flowsViewer.getSelection()).iterator();
- while (it.hasNext()) {
- Node node = (Node) it.next();
- try {
- node.remove();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot remove " + node, e);
- }
- }
- flowsViewer.refresh();
- formPart.markDirty();
- }
- }
-
- protected void removeAllFlows() {
- try {
- for (NodeIterator nit = processNode.getNode(SLC_FLOW).getNodes(); nit.hasNext();) {
- nit.nextNode().remove();
- }
- flowsViewer.refresh();
- formPart.markDirty();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot remove flows from " + processNode, e);
- }
- }
-
- public void commit(Boolean onSave) {
- if (onSave)
- statusLabel.setText(getProcessStatus());
- formPart.commit(onSave);
- }
-
- /*
- * STATE
- */
- protected String getProcessStatus() {
- try {
- return processNode.getProperty(SLC_STATUS).getString();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot retrieve status for " + processNode, e);
- }
- }
-
- /** Optimization so that we don't call the node each time */
- protected static Boolean isEditable(String status) {
- return status.equals(ExecutionProcess.NEW) || status.equals(ExecutionProcess.INITIALIZED);
- }
-
- protected static Boolean isFinished(String status) {
- return status.equals(ExecutionProcess.COMPLETED) || status.equals(ExecutionProcess.ERROR)
- || status.equals(ExecutionProcess.KILLED);
- }
-
- protected static Boolean isRunning(String status) {
- return status.equals(ExecutionProcess.RUNNING);
- }
-
- /*
- * LIFECYCLE
- */
- @Override
- public void dispose() {
- JcrUtils.unregisterQuietly(processNode, statusObserver);
- JcrUtils.logoutQuietly(agentSession);
- super.dispose();
- }
-
- /*
- * UTILITIES
- */
- protected static String getAttributeSpecText(Node specAttrNode) {
- try {
- if (specAttrNode.isNodeType(SlcTypes.SLC_PRIMITIVE_SPEC_ATTRIBUTE)) {
- if (!specAttrNode.hasProperty(SLC_VALUE))
- return "";
- String type = specAttrNode.getProperty(SLC_TYPE).getString();
- if (PrimitiveAccessor.TYPE_PASSWORD.equals(type))
- return "****************";
- Object value = PrimitiveUtils.convert(type, specAttrNode.getProperty(SLC_VALUE).getString());
- return value.toString();
- } else if (specAttrNode.isNodeType(SlcTypes.SLC_REF_SPEC_ATTRIBUTE)) {
- if (specAttrNode.hasProperty(SLC_VALUE)) {
- int value = (int) specAttrNode.getProperty(SLC_VALUE).getLong();
- NodeIterator children = specAttrNode.getNodes();
- int index = 0;
- while (children.hasNext()) {
- Node child = children.nextNode();
- if (index == value)
- return child.getProperty(Property.JCR_TITLE).getString();
- index++;
- }
- throw new SlcException("No child node with index " + value + " for spec attribute " + specAttrNode);
- } else
- return "";
- }
- throw new SlcException("Unsupported type for spec attribute " + specAttrNode);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get value", e);
- }
- }
-
- /*
- * FLOWS SUBCLASSES
- */
- class FlowsContentProvider implements ITreeContentProvider {
- public Object[] getElements(Object obj) {
- if (!(obj instanceof Node))
- return new Object[0];
-
- try {
- Node node = (Node) obj;
- List<Node> children = new ArrayList<Node>();
- for (NodeIterator nit = node.getNode(SLC_FLOW).getNodes(); nit.hasNext();) {
- Node flowNode = nit.nextNode();
- children.add(flowNode);
- }
- return children.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot list flows of " + obj, e);
- }
- }
-
- public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
- }
-
- public void dispose() {
- }
-
- public Object[] getChildren(Object parentElement) {
- // no children for the time being
- return null;
- }
-
- public Object getParent(Object element) {
- return null;
- }
-
- public boolean hasChildren(Object element) {
- return false;
- }
-
- }
-
- static class FlowsLabelProvider extends ColumnLabelProvider {
- @Override
- public String getText(Object element) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SlcTypes.SLC_REALIZED_FLOW)) {
- if (node.hasNode(SLC_ADDRESS)) {
- String path = node.getNode(SLC_ADDRESS).getProperty(Property.JCR_PATH).getString();
- String executionModuleName = SlcJcrUtils.moduleName(path);
- // Node executionModuleNode = node.getSession().getNode(
- // SlcJcrUtils.modulePath(path));
- // String executionModuleName = executionModuleNode
- // .getProperty(SLC_NAME).getString();
- return executionModuleName + ":" + SlcJcrUtils.flowRelativePath(path);
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot display " + element, e);
- }
- return super.getText(element);
- }
-
- @Override
- public Image getImage(Object element) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SlcTypes.SLC_REALIZED_FLOW)) {
- if (node.hasProperty(SLC_STATUS)) {
- String status = node.getProperty(SLC_STATUS).getString();
- // TODO: factorize with process view ?
- if (status.equals(ExecutionProcess.RUNNING))
- return SlcImages.PROCESS_RUNNING;
- else if (status.equals(ExecutionProcess.ERROR) || status.equals(ExecutionProcess.KILLED))
- return SlcImages.PROCESS_ERROR;
- else if (status.equals(ExecutionProcess.COMPLETED))
- return SlcImages.PROCESS_COMPLETED;
- }
- return SlcImages.FLOW;
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot display " + element, e);
- }
- return super.getImage(element);
- }
-
- }
-
- /** Parameter view is updated each time a new line is selected */
- class FlowsSelectionListener implements ISelectionChangedListener {
- public void selectionChanged(SelectionChangedEvent evt) {
- if (evt.getSelection().isEmpty()) {
- valuesViewer.setInput(getEditorSite());
- return;
- }
- Node realizedFlowNode = (Node) ((IStructuredSelection) evt.getSelection()).getFirstElement();
- valuesViewer.setInput(realizedFlowNode);
- }
- }
-
- /**
- * Add a context menu that call private methods. It only relies on selected
- * item(s) not on parameter that are passed in the menuAboutToShow method
- **/
- private void addContextMenu() {
- Menu menu = new Menu(flowsViewer.getControl());
-
- MenuItem removeItems = new MenuItem(menu, SWT.PUSH);
- removeItems.addSelectionListener(new SelectionListener() {
-
- public void widgetSelected(SelectionEvent e) {
- removeSelectedFlows();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
- removeItems.setText("Remove selected flow(s)");
-
- MenuItem removeAllItems = new MenuItem(menu, SWT.PUSH);
- removeAllItems.addSelectionListener(new SelectionListener() {
-
- public void widgetSelected(SelectionEvent e) {
- removeAllFlows();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
- removeAllItems.setText("Remove all flows");
- flowsViewer.getTree().setMenu(menu);
- }
-
- /** Manages drop event. */
- class FlowsDropListener extends ViewerDropAdapter {
-
- public FlowsDropListener(Viewer viewer) {
- super(viewer);
- }
-
- @Override
- public boolean performDrop(Object data) {
-
- // Parse the received String, paths are separated with a carriage
- // return
- String[] paths = data.toString().split(new String("\n"));
- SortedSet<String> resultPaths = new TreeSet<String>();
- for (String path : paths) {
- try {
- // either a node or a whole directory can have been dragged
- QueryManager qm = processNode.getSession().getWorkspace().getQueryManager();
- String statement = "SELECT * FROM [" + SlcTypes.SLC_EXECUTION_FLOW + "] WHERE ISDESCENDANTNODE(['"
- + path + "']) OR ISSAMENODE(['" + path + "'])";
- Query query = qm.createQuery(statement, Query.JCR_SQL2);
-
- // order paths
- for (NodeIterator nit = query.execute().getNodes(); nit.hasNext();) {
- String currPath = nit.nextNode().getPath();
- // do not add twice a same flow
- if (!resultPaths.contains(currPath))
- resultPaths.add(currPath);
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot query flows under " + path, e);
- }
- }
- for (String p : resultPaths) {
- addFlow(p);
- }
- return true;
-
- }
-
- @Override
- public boolean validateDrop(Object target, int operation, TransferData transferType) {
- return isEditable(getProcessStatus());
- }
- }
-
- /*
- * VALUES SUBCLASSES
- */
- static class ValuesContentProvider implements IStructuredContentProvider {
-
- public Object[] getElements(Object inputElement) {
- if (!(inputElement instanceof Node))
- return new Object[0];
-
- try {
- Node realizedFlowNode = (Node) inputElement;
- List<Node> specAttributes = new ArrayList<Node>();
- specAttrs: for (NodeIterator nit = realizedFlowNode.getNodes(); nit.hasNext();) {
- Node specAttrNode = nit.nextNode();
- if (!specAttrNode.isNodeType(SlcTypes.SLC_EXECUTION_SPEC_ATTRIBUTE))
- continue specAttrs;
- // workaround to enable hiding of necessary but unusable
- // flow parameters
- else if (specAttrNode.hasProperty(SlcNames.SLC_IS_HIDDEN)
- && specAttrNode.getProperty(SlcNames.SLC_IS_HIDDEN).getBoolean())
- continue specAttrs;
- specAttributes.add(specAttrNode);
- }
- return specAttributes.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get elements", e);
- }
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- class ValuesEditingSupport extends EditingSupport {
- private final TableViewer tableViewer;
-
- public ValuesEditingSupport(ColumnViewer viewer) {
- super(viewer);
- tableViewer = (TableViewer) viewer;
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- try {
- Node specAttrNode = (Node) element;
- if (specAttrNode.isNodeType(SlcTypes.SLC_PRIMITIVE_SPEC_ATTRIBUTE)) {
- String type = specAttrNode.getProperty(SLC_TYPE).getString();
- if (PrimitiveAccessor.TYPE_PASSWORD.equals(type)) {
- return new TextCellEditor(tableViewer.getTable(), SWT.PASSWORD);
- } else {
- return new TextCellEditor(tableViewer.getTable());
- }
- } else if (specAttrNode.isNodeType(SlcTypes.SLC_REF_SPEC_ATTRIBUTE)) {
- NodeIterator children = specAttrNode.getNodes();
- ArrayList<String> items = new ArrayList<String>();
- while (children.hasNext()) {
- Node child = children.nextNode();
- if (child.isNodeType(NodeType.MIX_TITLE))
- items.add(child.getProperty(Property.JCR_TITLE).getString());
- }
- return new ComboBoxCellEditor(tableViewer.getTable(), items.toArray(new String[items.size()]));
- }
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get cell editor", e);
- }
- }
-
- @Override
- protected boolean canEdit(Object element) {
- try {
- Node specAttrNode = (Node) element;
- Boolean cannotEdit = specAttrNode.getProperty(SLC_IS_IMMUTABLE).getBoolean()
- || specAttrNode.getProperty(SLC_IS_CONSTANT).getBoolean();
- return !cannotEdit && isSupportedAttributeType(specAttrNode);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot check whether " + element + " is editable", e);
- }
- }
-
- /**
- * Supports {@link SlcTypes#SLC_PRIMITIVE_SPEC_ATTRIBUTE} and
- * {@link SlcTypes#SLC_REF_SPEC_ATTRIBUTE}
- */
- protected boolean isSupportedAttributeType(Node specAttrNode) throws RepositoryException {
- return specAttrNode.isNodeType(SlcTypes.SLC_PRIMITIVE_SPEC_ATTRIBUTE)
- || specAttrNode.isNodeType(SlcTypes.SLC_REF_SPEC_ATTRIBUTE);
- }
-
- @Override
- protected Object getValue(Object element) {
- Node specAttrNode = (Node) element;
- try {
- if (specAttrNode.isNodeType(SlcTypes.SLC_PRIMITIVE_SPEC_ATTRIBUTE)) {
- if (!specAttrNode.hasProperty(SLC_VALUE))
- return NONE;
- String type = specAttrNode.getProperty(SLC_TYPE).getString();
- // TODO optimize based on data type?
- Object value = PrimitiveUtils.convert(type, specAttrNode.getProperty(SLC_VALUE).getString());
- return value.toString();
- } else if (specAttrNode.isNodeType(SlcTypes.SLC_REF_SPEC_ATTRIBUTE)) {
- if (!specAttrNode.hasProperty(SLC_VALUE))
- return 0;
- // return the index of the sub node as set by setValue()
- // in the future we may manage references as well
- return (int) specAttrNode.getProperty(SLC_VALUE).getLong();
- }
- throw new SlcException("Unsupported type for spec attribute " + specAttrNode);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get value for " + element, e);
- }
- }
-
- @Override
- protected void setValue(Object element, Object value) {
- try {
- Node specAttrNode = (Node) element;
- if (specAttrNode.isNodeType(SlcTypes.SLC_PRIMITIVE_SPEC_ATTRIBUTE)) {
- String type = specAttrNode.getProperty(SLC_TYPE).getString();
- SlcJcrUtils.setPrimitiveAsProperty(specAttrNode, SLC_VALUE, type, value);
- valuesViewer.refresh();
- formPart.markDirty();
- } else if (specAttrNode.isNodeType(SlcTypes.SLC_REF_SPEC_ATTRIBUTE)) {
- specAttrNode.setProperty(SLC_VALUE, ((Integer) value).longValue());
- valuesViewer.refresh();
- formPart.markDirty();
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get celle editor", e);
- }
- }
-
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.editors;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-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 org.argeo.api.cms.CmsConstants;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.controllers.ProcessController;
-import org.argeo.slc.execution.ExecutionModulesManager;
-import org.argeo.slc.execution.ExecutionProcess;
-import org.argeo.slc.jcr.SlcJcrUtils;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.rap.rwt.service.ServerPushSession;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.editor.FormEditor;
-
-/** Editor for an execution process. */
-public class ProcessEditor extends FormEditor implements SlcTypes, SlcNames {
- private static final long serialVersionUID = 509589737739132467L;
-
- public final static String ID = ClientUiPlugin.ID + ".processEditor";
-
- private Repository repository;
- private Session homeSession;
- private Session agentSession;
- private Node processNode;
- private ProcessController processController;
- private ServerPushSession pushSession;
-
- private ProcessBuilderPage builderPage;
-
- private ExecutionModulesManager modulesManager;
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- super.init(site, input);
- pushSession = new ServerPushSession();
- pushSession.start();
- try {
- homeSession = repository.login(CmsConstants.HOME_WORKSPACE);
- agentSession = repository.login();
- } catch (RepositoryException e1) {
- throw new SlcException("Cannot log in to repository");
- }
-
- ProcessEditorInput pei = (ProcessEditorInput) input;
- String processPath = pei.getProcessPath();
- try {
- if (processPath != null) {
- if (!homeSession.itemExists(processPath))
- throw new SlcException("Process " + processPath + " does not exist");
- processNode = homeSession.getNode(processPath);
- } else {// new
- processNode = newProcessNode(pei);
- }
- setPartName(processNode.getName());
- } catch (RepositoryException e) {
- throw new SlcException("Cannot initialize editor for " + pei, e);
- }
-
- }
-
- protected Node newProcessNode(ProcessEditorInput pei) throws RepositoryException {
- String uuid = UUID.randomUUID().toString();
- String processPath = SlcJcrUtils.createExecutionProcessPath(homeSession, uuid);
- Node processNode = JcrUtils.mkdirs(homeSession, processPath, SLC_PROCESS);
- processNode.setProperty(SLC_UUID, uuid);
- processNode.setProperty(SLC_STATUS, ExecutionProcess.NEW);
- Node processFlow = processNode.addNode(SLC_FLOW);
- processFlow.addMixin(SLC_REALIZED_FLOW);
- return processNode;
- }
-
- @Override
- public boolean isDirty() {
- if (getProcessStatus().equals(ExecutionProcess.NEW))
- return true;
- return super.isDirty();
- }
-
- protected String getProcessStatus() {
- try {
- return processNode.getProperty(SLC_STATUS).getString();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot retrieve status for " + processNode, e);
- }
- }
-
- @Override
- public void dispose() {
- JcrUtils.logoutQuietly(homeSession);
- JcrUtils.logoutQuietly(agentSession);
- if (pushSession != null)
- pushSession.stop();
- super.dispose();
- }
-
- /** Actually runs the process. */
- void process() {
- // the modifications have to be saved before execution
- try {
- processNode.setProperty(SLC_STATUS, ExecutionProcess.SCHEDULED);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot update status of " + processNode, e);
- }
-
- // save
- doSave(null);
-
- try {
- // make sure modules are started for all nodes
- for (NodeIterator nit = processNode.getNode(SLC_FLOW).getNodes(); nit.hasNext();) {
- Node flowNode = nit.nextNode();
- try {
- String flowDefPath = flowNode.getNode(SLC_ADDRESS).getProperty(Property.JCR_PATH).getString();
- Node executionModuleNode = agentSession.getNode(SlcJcrUtils.modulePath(flowDefPath));
- if (!executionModuleNode.getProperty(SLC_STARTED).getBoolean())
- ClientUiPlugin.startStopExecutionModule(modulesManager, executionModuleNode);
- } catch (Exception e) {
- ErrorFeedback.show("Cannot start execution module related to " + flowNode, e);
- }
- }
-
- // Actually process
- ExecutionProcess process = processController.process(processNode);
- Map<String, String> properties = new HashMap<String, String>();
- properties.put(ExecutionModulesManager.SLC_PROCESS_ID, process.getUuid());
- // modulesManager.registerProcessNotifier(this, properties);
- } catch (Exception e) {
- ErrorFeedback.show("Execution of " + processNode + " failed", e);
- }
- }
-
- void kill() {
- processController.kill(processNode);
- }
-
- /** Opens a new editor with a copy of this process */
- void relaunch() {
- try {
- Node duplicatedNode = duplicateProcess();
- IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- activePage.openEditor(new ProcessEditorInput(duplicatedNode.getPath()), ProcessEditor.ID);
- close(false);
- } catch (Exception e1) {
- throw new SlcException("Cannot relaunch " + processNode, e1);
- }
- }
-
- /** Duplicates the process */
- protected Node duplicateProcess() {
- try {
- Session session = processNode.getSession();
- String uuid = UUID.randomUUID().toString();
- String destPath = SlcJcrUtils.createExecutionProcessPath(session, uuid);
- Node newNode = JcrUtils.mkdirs(session, destPath, SlcTypes.SLC_PROCESS);
-
- Node rootRealizedFlowNode = newNode.addNode(SLC_FLOW);
- // copy node
- JcrUtils.copy(processNode.getNode(SLC_FLOW), rootRealizedFlowNode);
-
- newNode.setProperty(SLC_UUID, uuid);
- newNode.setProperty(SLC_STATUS, ExecutionProcess.INITIALIZED);
-
- // reset realized flow status
- // we just manage one level for the time being
- NodeIterator nit = rootRealizedFlowNode.getNodes(SLC_FLOW);
- while (nit.hasNext()) {
- nit.nextNode().setProperty(SLC_STATUS, ExecutionProcess.INITIALIZED);
- }
-
- session.save();
- return newNode;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot duplicate process", e);
- }
- }
-
- @Override
- protected void addPages() {
- try {
- builderPage = new ProcessBuilderPage(this, processNode);
- addPage(builderPage);
- firePropertyChange(PROP_DIRTY);
- } catch (PartInitException e) {
- throw new SlcException("Cannot add pages", e);
- }
-
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- try {
- String status = processNode.getProperty(SLC_STATUS).getString();
- if (status.equals(ExecutionProcess.NEW))
- processNode.setProperty(SLC_STATUS, ExecutionProcess.INITIALIZED);
- homeSession.save();
- builderPage.commit(true);
- editorDirtyStateChanged();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot save " + processNode, e);
- // } finally {
- // JcrUtils.discardQuietly(session);
- }
- }
-
- public void setEditorTitle(String title) {
- setPartName(title);
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-
- public void setProcessController(ProcessController processController) {
- this.processController = processController;
- }
-
- public void setModulesManager(ExecutionModulesManager modulesManager) {
- this.modulesManager = modulesManager;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.editors;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPersistableElement;
-
-public class ProcessEditorInput implements IEditorInput, IPersistableElement {
- private String processPath;
- private List<String> initialFlowPaths = new ArrayList<String>();
- private Boolean launchImmediately = false;
-
- /** New empty process */
- public ProcessEditorInput() {
- }
-
- /** New process with some flows */
- public ProcessEditorInput(List<String> initialFlowPaths,
- Boolean launchImmediately) {
- this.initialFlowPaths = initialFlowPaths;
- this.launchImmediately = launchImmediately;
- }
-
- /** Existing process */
- public ProcessEditorInput(String processPath) {
- this.processPath = processPath;
- }
-
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class arg0) {
- return null;
- }
-
- public boolean exists() {
- return processPath != null;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return processPath != null ? processPath : "<new process>";
- }
-
- public IPersistableElement getPersistable() {
- return this;
- }
-
- public String getToolTipText() {
- return "";
- }
-
- public void saveState(IMemento memento) {
- memento.putString("processPath", processPath);
- }
-
- public String getFactoryId() {
- return ProcessEditorInputFactory.ID;
- }
-
- public String getProcessPath() {
- return processPath;
- }
-
- public List<String> getInitialFlowPaths() {
- return initialFlowPaths;
- }
-
- public Boolean getLaunchImmediately() {
- return launchImmediately;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof ProcessEditorInput))
- return false;
- ProcessEditorInput pei = (ProcessEditorInput) obj;
- if (processPath != null && pei.processPath != null)
- return processPath.equals(pei.processPath);
- return false;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.editors;
-
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IElementFactory;
-import org.eclipse.ui.IMemento;
-
-public class ProcessEditorInputFactory implements IElementFactory {
- public final static String ID = ClientUiPlugin.ID
- + ".processEditorInputFactory";
-
- public IAdaptable createElement(IMemento memento) {
- String path = memento.getString("processPath");
- return new ProcessEditorInput(path);
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.editors;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.List;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Workspace;
-import javax.jcr.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.query.Query;
-
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.execution.ExecutionStep;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-public class ProcessLogPage extends FormPage {
- public final static String ID = "processLogPage";
-
- private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
-
- /** Where the log is displayed. */
- private Text text;
- /**
- * Stores logs received before the text was shown. TODO : rather store in in
- * JCR and reads it from there.
- */
- private StringBuffer beforeTextInit = new StringBuffer("");
-
- private Node processNode;
- /**
- * optimization field: we compute once the length of the path to slc:log so
- * that we can easily substring the relative path of logs.
- */
- //private Integer logPathLength;
-
- public ProcessLogPage(FormEditor editor, Node processNode) {
- super(editor, ID, "Log");
- this.processNode = processNode;
-
- EventListener listener = new LogListener(editor.getSite().getPage()
- .getWorkbenchWindow().getWorkbench().getDisplay());
-
- try {
- String logBasePath = processNode.getPath() + '/' + SlcNames.SLC_LOG;
- //logPathLength = logBasePath.length();
-
- Workspace ws = processNode.getSession().getWorkspace();
-
- String statement = "SELECT * FROM ["
- + SlcTypes.SLC_LOG_ENTRY
- + "] as logEntry"
- + " WHERE ISDESCENDANTNODE('"
- + logBasePath
- + "')"
- + " ORDER BY logEntry.[slc:timestamp] ASC, NAME(logEntry) ASC";
- StringBuffer buf = new StringBuffer("");
- NodeIterator it = ws.getQueryManager()
- .createQuery(statement, Query.JCR_SQL2).execute()
- .getNodes();
- while (it.hasNext())
- appendLogEntry(buf, it.nextNode());
- beforeTextInit = new StringBuffer(buf.toString());
- // text.setText(buf.toString());
- ws.getObservationManager().addEventListener(listener,
- Event.NODE_ADDED, logBasePath, true, null, null, false);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot register listener", e);
- }
- }
-
- @Override
- public synchronized void createPartControl(Composite parent) {
- // bypass createFormContent
- FormToolkit tk = getEditor().getToolkit();
- // parent.setLayout(new FillLayout());
- text = tk.createText(parent, "", SWT.MULTI | SWT.H_SCROLL
- | SWT.V_SCROLL);
- text.setEditable(false);
-
- // transfer the existing buffer the first time
- if (beforeTextInit.length() > 0) {
- text.append(beforeTextInit.toString());
- // clear buffer
- beforeTextInit.setLength(0);
- }
-
- }
-
- // @Override
- // protected synchronized void createFormContent(IManagedForm mf) {
- // ScrolledForm form = mf.getForm();
- // form.setExpandHorizontal(true);
- // form.setExpandVertical(true);
- // // form.setText("Log");
- // FillLayout mainLayout = new FillLayout();
- // form.getBody().setLayout(mainLayout);
- //
- // FormToolkit tk = getManagedForm().getToolkit();
- // text = tk.createText(form.getBody(), "", SWT.MULTI | SWT.H_SCROLL
- // | SWT.V_SCROLL);
- // text.setEditable(false);
- // // transfer the existing buffer the first time
- // if (beforeTextInit.length() > 0) {
- // text.append(beforeTextInit.toString());
- // // clear buffer
- // beforeTextInit.setLength(0);
- // }
- // }
-
- protected void appendLogEntry(StringBuffer buf, Node logEntry)
- throws RepositoryException {
- // +1 in order to remove the first slash
-// String relPath = logEntry.getPath().substring(logPathLength + 1);
- //System.out.println("relPath=" + relPath);
-// int firstSlashIndex = relPath.indexOf('/');
-// int lastSlashIndex = relPath.lastIndexOf('/');
-// String thread = relPath.substring(0, firstSlashIndex);
-// String location = relPath.substring(firstSlashIndex, lastSlashIndex);
-
- // String date = dateFormat.format(logEntry
- // .getProperty(SlcNames.SLC_TIMESTAMP).getDate().getTime());
- String date = logEntry.getProperty(SlcNames.SLC_TIMESTAMP).getString();
- buf.append(date).append(' ');
- String type = logEntry.getPrimaryNodeType().getName().substring(7);
- buf.append(type).append('\t');
- // buf.append(thread).append('\t');
- // buf.append(location).append('\t');
- buf.append(logEntry.getProperty(SlcNames.SLC_MESSAGE).getString());
- buf.append('\n');
-
- }
-
- /** @deprecated */
- public synchronized void addSteps(List<ExecutionStep> steps) {
- final StringBuffer buf = new StringBuffer("");
- for (ExecutionStep step : steps) {
- buf.append(dateFormat.format(step.getTimestamp()));
- buf.append(' ');
- if (step.getType().equals(ExecutionStep.PHASE_START)) {
- buf.append("## START ").append(step.getLog());
- buf.append('\n');
- } else if (step.getType().equals(ExecutionStep.PHASE_END)) {
- buf.append("## END ").append(step.getLog());
- buf.append("\n");
- } else {
- buf.append(step.getLog());
- }
- }
-
- if (text != null) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- text.append(buf.toString());
- }
- });
- } else
- beforeTextInit.append(buf);
- }
-
- @Override
- public Control getPartControl() {
- return text;
- }
-
- @Override
- public void setFocus() {
- if (text != null)
- text.setFocus();
- }
-
- /** JCR event listener notifying when new nodes are added */
- private class LogListener extends AsyncUiEventListener {
-
- public LogListener(Display display) {
- super(display);
- }
-
- @Override
- protected void onEventInUiThread(List<Event> events)
- throws RepositoryException {
- // since we use batch save, order is not guaranteed
- // so we need to reorder, according to log line number for the time
- // being
- SortedMap<Long, Node> nodes = new TreeMap<Long, Node>();
-
- for (Event evt : events) {
- Node newNode = ProcessLogPage.this.processNode.getSession()
- .getNode(evt.getPath());
- if (newNode.isNodeType(SlcTypes.SLC_LOG_ENTRY)) {
- nodes.put(Long.parseLong(newNode.getName()), newNode);
- }
- }
-
- StringBuffer buf = new StringBuffer("");
- for (Node logEntry : nodes.values()) {
- appendLogEntry(buf, logEntry);
- }
-
- if (text != null)
- text.append(buf.toString());
- else
- beforeTextInit.append(buf);
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-
-/**
- * UI Tree component that wrap a node of type NT_UNSTRUCTURED or base node for
- * UI specific, user defined tree structure of type SLC_MY_RESULTS_ROOT_FOLDER.
- *
- * It is used for
- * <ul>
- * <li>automatically generated tree structure to store results (typically
- * Year/Month/Day...)</li>
- * <li>parent node for user defined tree structure (typically My Results node)</li>
- * </ul>
- * It thus lists either result folders, other folders and/or a list of results
- * and keeps a reference to its parent.
- */
-public class ParentNodeFolder extends ResultParent {
- // private final static CmsLog log = CmsLog.getLog(ParentNodeFolder.class);
-
- private Node node = null;
-
- /**
- *
- * @param parent
- * @param node
- * throws an exception if null
- * @param name
- */
- public ParentNodeFolder(ParentNodeFolder parent, Node node, String name) {
- super(name);
- if (node == null)
- throw new SlcException("Node Object cannot be null");
- setParent(parent);
- this.node = node;
- }
-
- @Override
- protected void initialize() {
- try {
- NodeIterator ni = node.getNodes();
- while (ni.hasNext()) {
- Node currNode = ni.nextNode();
- if (currNode.isNodeType(SlcTypes.SLC_TEST_RESULT)) {
- SingleResultNode srn = new SingleResultNode(this, currNode,
- currNode.getProperty(SlcNames.SLC_TEST_CASE)
- .getString());
- addChild(srn);
- } else if (currNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {
- // FIXME change label
- ResultFolder rf = new ResultFolder(this, currNode,
- currNode.getName());
- addChild(rf);
- } else if (currNode.isNodeType(SlcTypes.SLC_CHECK)) {
- // FIXME : manually skip node types that are not to be
- // displayed
- // Do nothing
- } else if (currNode.isNodeType(NodeType.NT_UNSTRUCTURED))
- addChild(new ParentNodeFolder(this, currNode,
- currNode.getName()));
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while initializing ParentNodeFolder : "
- + getName(), re);
- }
- }
-
- public Node getNode() {
- return node;
- }
-
- // /**
- // * Overriden in the specific case of "My result" root object to return an
- // * ordered list of children
- // */
- // public synchronized Object[] getChildren() {
- // Object[] children = super.getChildren();
- // try {
- // if (node.isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER))
- // return ResultParentUtils.orderChildren(children);
- // else
- // return children;
- // } catch (RepositoryException re) {
- // throw new SlcException(
- // "Unexpected error while initializing simple node folder : "
- // + getName(), re);
- // }
- // }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-
-/**
- * UI Tree component that wrap a node of type ResultFolder. list either other
- * folders and/or a list of results. keeps a reference to its parent.
- */
-public class ResultFolder extends ParentNodeFolder {
-
- /**
- *
- * @param parent
- * @param node
- * throws an exception if null
- * @param name
- */
- public ResultFolder(ParentNodeFolder parent, Node node, String name) {
- super(parent, node, name);
- try {
- // initialize passed status if possible
- if (node.hasNode(SlcNames.SLC_AGGREGATED_STATUS))
- setPassed(node.getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean());
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while initializing result folder : "
- + getName(), re);
- }
- }
-
- // /**
- // * Overriden to return an ordered list of children
- // */
- // public synchronized Object[] getChildren() {
- // Object[] children = super.getChildren();
- // return ResultParentUtils.orderChildren(children);
- // }
- //
- // public int compareTo(ResultFolder o) {
- // return super.compareTo(o);
- // }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-
-/** Enable specific sorting of the ResultTreeView */
-public class ResultItemsComparator extends ViewerComparator {
-
- @Override
- public int category(Object element) {
- if (element instanceof SingleResultNode) {
- return 10;
-
- }
- // folder always first
- return 5;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- int cat1 = category(e1);
- int cat2 = category(e2);
-
- if (cat1 != cat2) {
- return cat1 - cat2;
- }
-
- int result = 0;
-
- if (e1 instanceof TreeParent && ((TreeParent) e1).getParent() == null) {
- // preserve predefined order on UI root items
- return 0;
- }
-
- if (e1 instanceof SingleResultNode && e2 instanceof SingleResultNode) {
- Node an = ((SingleResultNode) e1).getNode();
- Node bn = ((SingleResultNode) e2).getNode();
- try {
- // Order is different if we are under my Result or )in the
- // rest of the tree structure
- if (an.getParent().isNodeType(
- SlcTypes.SLC_MY_RESULT_ROOT_FOLDER)
- || an.getParent()
- .isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {
- result = super.compare(viewer, e1, e2);
- // Specific case of two result with same name
- if (result == 0) {
- result = an
- .getProperty(SlcNames.SLC_COMPLETED)
- .getDate()
- .compareTo(
- bn.getProperty(SlcNames.SLC_COMPLETED)
- .getDate());
- }
- } else {
- result = an
- .getProperty(Property.JCR_CREATED)
- .getDate()
- .compareTo(
- bn.getProperty(Property.JCR_CREATED)
- .getDate());
- result = result * -1; // last are displayed first
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unable to compare date created", e);
- }
- } else if (e1 instanceof ParentNodeFolder
- && e2 instanceof ParentNodeFolder) {
- try {
- Node an = ((ParentNodeFolder) e1).getNode();
- // under my Result
- if (an.isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER)
- || an.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {
- result = super.compare(viewer, e1, e2);
- } else {
- // only remaining objects for the time being
- // NT_UNSTRUCTURED that display all result tree structures
- // We want the newest folders first
- result = super.compare(viewer, e1, e2) * -1;
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unable to compare date created", e);
- }
- }
- return result;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.eclipse.jface.viewers.IElementComparer;
-
-/**
- * Override default behaviour to insure that 2 distincts results that have the
- * same name will be correctly and distincly returned by corresponding
- * TreeViewer.getSelection() method.
- *
- */
-public class ResultItemsComparer implements IElementComparer {
- // private final static Log log =
- // LogFactory.getLog(ResultItemsComparer.class);
-
- public boolean equals(Object a, Object b) {
- if (b == null)
- return a == null ? true : false;
-
- if (a.hashCode() != b.hashCode() || !a.getClass().equals(b.getClass()))
- return false;
- else if (a instanceof SingleResultNode) {
- try {
- String ida = ((SingleResultNode) a).getNode().getIdentifier();
-
- String idb = ((SingleResultNode) b).getNode().getIdentifier();
-
- if (ida.equals(idb))
- return true;
- else
- return false;
-
- } catch (RepositoryException e) {
- throw new SlcException("Cannot compare single reult nodes", e);
- }
- } else
- return true;
- }
-
- public int hashCode(Object element) {
- return element.hashCode();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import org.argeo.eclipse.ui.TreeParent;
-
-/**
- * Common base UI object to build result Tree.
- */
-
-public abstract class ResultParent extends TreeParent {
-
- public ResultParent(String name) {
- super(name);
- }
-
- private boolean isPassed = true;
-
- protected synchronized void setPassed(boolean isPassed) {
- this.isPassed = isPassed;
- }
-
- public boolean isPassed() {
- return isPassed;
- }
-
- @Override
- public synchronized boolean hasChildren() {
- // only initialize when needed : correctly called by the jface framework
- if (!isLoaded())
- initialize();
- return super.hasChildren();
- }
-
- public void forceFullRefresh() {
- // if (isDisposed)
- // return;
- if (hasChildren())
- clearChildren();
- initialize();
- }
-
- protected abstract void initialize();
-}
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryManager;
-import javax.jcr.query.QueryResult;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.jcr.SlcJcrResultUtils;
-
-public class ResultParentUtils {
- // private final static Log log =
- // LogFactory.getLog(ResultParentUtils.class);
-
- // public static Object[] orderChildren(Object[] children) {
- // List<ResultFolder> folders = new ArrayList<ResultFolder>();
- // List<SingleResultNode> results = new ArrayList<SingleResultNode>();
- // for (Object child : children) {
- // if (child instanceof ResultFolder)
- // folders.add((ResultFolder) child);
- // else if (child instanceof SingleResultNode)
- // results.add((SingleResultNode) child);
- // }
- //
- // // Comparator first = Collections.reverseOrder();
- // Collections.sort(folders);
- // // Comparator<SingleResultNode> second = Collections.reverseOrder();
- // Collections.sort(results);
- //
- // Object[] orderedChildren = new Object[folders.size() + results.size()];
- // int i = 0;
- // Iterator<ResultFolder> it = folders.iterator();
- // while (it.hasNext()) {
- // orderedChildren[i] = it.next();
- // i++;
- // }
- // Iterator<SingleResultNode> it2 = results.iterator();
- // while (it2.hasNext()) {
- // orderedChildren[i] = it2.next();
- // i++;
- // }
- // return orderedChildren;
- // }
-
- public static List<Node> getResultsForDates(Session session,
- List<String> dateRelPathes) {
- if (dateRelPathes == null || dateRelPathes.size() == 0)
- throw new SlcException("Specify at least one correct date as Path");
-
- try {
- String basePath = SlcJcrResultUtils.getSlcResultsBasePath(session);
- Iterator<String> it = dateRelPathes.iterator();
- StringBuffer clause = new StringBuffer();
- clause.append("SELECT * FROM [");
- clause.append(SlcTypes.SLC_TEST_RESULT);
- clause.append("] as results");
- clause.append(" WHERE ");
- while (it.hasNext()) {
- String absPath = basePath + "/" + it.next();
- clause.append("ISDESCENDANTNODE(results, [");
- clause.append(absPath);
- clause.append("]) ");
- clause.append(" OR ");
- }
- // remove last " OR "
- clause.delete(clause.length() - 4, clause.length());
- clause.append(" ORDER BY results.[" + Property.JCR_CREATED
- + "] DESC");
-
- // log.debug("request : " + clause.toString());
- QueryManager qm = session.getWorkspace().getQueryManager();
- Query q = qm.createQuery(clause.toString(), Query.JCR_SQL2);
- QueryResult result = q.execute();
-
- NodeIterator ni = result.getNodes();
- List<Node> nodes = new ArrayList<Node>();
- while (ni.hasNext()) {
- nodes.add(ni.nextNode());
- }
- return nodes;
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while getting Results for given date", re);
- }
- }
-
- /**
- * recursively update passed status of the current ResultFolder and its
- * parent if needed
- *
- * @param node
- * cannot be null
- *
- */
- public static void updatePassedStatus(Node node, boolean passed) {
- try {
- if (!node.hasNode(SlcNames.SLC_AGGREGATED_STATUS))
- // we have reached the root of the tree. stop the
- // recursivity
- return;
- boolean pStatus = node.getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean();
- if (pStatus == passed)
- // nothing to update
- return;
- else if (!passed) {
- // New status is 'failed' : we only update status of the result
- // folder and its
- // parent if needed
- node.getNode(SlcNames.SLC_AGGREGATED_STATUS).setProperty(
- SlcNames.SLC_SUCCESS, passed);
- updatePassedStatus(node.getParent(), passed);
- } else {
- // New status is 'passed': we must first check if all siblings
- // have also
- // successfully completed
- boolean success = true;
- NodeIterator ni = node.getNodes();
- children: while (ni.hasNext()) {
- Node currNode = ni.nextNode();
- if ((currNode.isNodeType(SlcTypes.SLC_DIFF_RESULT) || currNode
- .isNodeType(SlcTypes.SLC_RESULT_FOLDER))
- && !currNode
- .getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS)
- .getBoolean()) {
- success = false;
- break children;
- }
- }
- if (success) {
- node.getNode(SlcNames.SLC_AGGREGATED_STATUS).setProperty(
- SlcNames.SLC_SUCCESS, passed);
- updatePassedStatus(node.getParent(), passed);
- } else
- // one of the siblings had also the failed status so
- // above tree remains unchanged.
- return;
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot update result passed status", e);
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Workspace;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-
-/**
- * UI Tree component. Wraps a result node of a JCR {@link Workspace}. It also
- * keeps a reference to its parent node that can either be a
- * {@link ResultFolder}, a {@link SingleResultNode} or a {@link VirtualFolder}.
- * It has no child.
- */
-
-public class SingleResultNode extends ResultParent implements
- Comparable<SingleResultNode> {
-
- private final Node node;
- private boolean passed;
-
- // keeps a local reference to the node's name to avoid exception when the
- // session is lost
-
- /** Creates a new UiNode in the UI Tree */
- public SingleResultNode(TreeParent parent, Node node, String name) {
- super(name);
- setParent(parent);
- this.node = node;
- setPassed(refreshPassedStatus());
- }
-
- public boolean refreshPassedStatus() {
- try {
- Node check;
- if (node.hasNode(SlcNames.SLC_AGGREGATED_STATUS)) {
- check = node.getNode(SlcNames.SLC_AGGREGATED_STATUS);
- passed = check.getProperty(SlcNames.SLC_SUCCESS).getBoolean();
- return passed;
- } else
- // Happens only if the UI triggers a refresh while the execution
- // is in progress and the corresponding node is being built
- return false;
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while checking result status", re);
- }
- }
-
- /** returns the node wrapped by the current UI object */
- public Node getNode() {
- return node;
- }
-
- /**
- * Override normal behavior : Results have no children for this view
- */
- @Override
- public synchronized Object[] getChildren() {
- return null;
- }
-
- @Override
- public boolean hasChildren() {
- return false;
- }
-
- public boolean isPassed() {
- return passed;
- }
-
- @Override
- protected void initialize() {
- // Do nothing this object is fully initialized at instantiation time.
- }
-
- public int compareTo(SingleResultNode o) {
- return super.compareTo(o);
- }
-
-}
+++ /dev/null
-package org.argeo.slc.client.ui.model;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-
-/**
- * UI Tree component. Virtual folder to list a list of results. Keeps a
- * reference to its parent that might be null. It also keeps a reference to all
- * nodes that must be displayed as children of the current virtual folder.
- */
-public class VirtualFolder extends ResultParent {
- List<Node> displayedNodes;
-
- public VirtualFolder(VirtualFolder parent, List<Node> displayedNodes,
- String name) {
- super(name);
- setParent(parent);
- this.displayedNodes = displayedNodes;
- }
-
- @Override
- protected void initialize() {
- try {
- for (Node currNode : displayedNodes) {
- if (currNode.isNodeType(SlcTypes.SLC_TEST_RESULT)) {
- SingleResultNode srn = new SingleResultNode(this, currNode,
- currNode.getProperty(SlcNames.SLC_TEST_CASE)
- .getString());
- addChild(srn);
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while initializing ParentNodeFolder : "
- + getName(), re);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.providers;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-/** Basic content provider for a tree of result */
-public class ResultTreeContentProvider implements ITreeContentProvider {
-
- /**
- * @param parent
- * Pass current user home as parameter
- *
- */
- public Object[] getElements(Object parent) {
- if (parent instanceof Object[])
- return (Object[]) parent;
- else
- return null;
- }
-
- public Object getParent(Object child) {
- return ((TreeParent) child).getParent();
- }
-
- public Object[] getChildren(Object parent) {
- return ((TreeParent) parent).getChildren();
- }
-
- public boolean hasChildren(Object parent) {
- return ((TreeParent) parent).hasChildren();
- }
-
- public void dispose() {
- // FIXME implement if needed
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.providers;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-import javax.jcr.nodetype.NodeType;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.client.ui.SlcUiConstants;
-import org.argeo.slc.client.ui.model.ParentNodeFolder;
-import org.argeo.slc.client.ui.model.ResultParent;
-import org.argeo.slc.client.ui.model.SingleResultNode;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-
-/** Basic label provider for a tree of result */
-public class ResultTreeLabelProvider extends LabelProvider {
- // private final static CmsLog log = CmsLog
- // .getLog(ResultTreeLabelProvider.class);
-
- @Override
- public String getText(Object element) {
- try {
-
- if (element instanceof SingleResultNode) {
- Node node = ((SingleResultNode) element).getNode();
- if (node.isNodeType(NodeType.MIX_TITLE))
- return node.getProperty(Property.JCR_TITLE).getString();
-
- } else if (element instanceof ParentNodeFolder) {
- Node node = ((ParentNodeFolder) element).getNode();
- if (node.hasProperty(Property.JCR_TITLE))
- return node.getProperty(Property.JCR_TITLE).getString();
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while getting "
- + "custom result label", e);
- }
- return ((TreeParent) element).getName();
- }
-
- public Image getImage(Object obj) {
- if (obj instanceof SingleResultNode) {
- // FIXME add realtime modification of process icon (SCHEDULED,
- // RUNNING, COMPLETED...)
- // Node resultNode = ((SingleResultNode) obj).getNode();
- // int status = SlcJcrUtils.aggregateTestStatus(resultNode);
- return SlcImages.PROCESS_COMPLETED;
- } else if (obj instanceof ResultParent) {
- ResultParent rParent = (ResultParent) obj;
- if (SlcUiConstants.DEFAULT_MY_RESULTS_FOLDER_LABEL.equals(rParent
- .getName()))
- return SlcImages.MY_RESULTS_FOLDER;
- else
- return SlcImages.FOLDER;
- } else
- return null;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.views;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-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.observation.Event;
-import javax.jcr.query.Query;
-import javax.jcr.query.QueryManager;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.eclipse.ui.jcr.DefaultNodeLabelProvider;
-import org.argeo.eclipse.ui.jcr.NodeElementComparer;
-import org.argeo.eclipse.ui.jcr.SimpleNodeContentProvider;
-import org.argeo.eclipse.ui.specific.EclipseUiSpecificUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.client.ui.editors.ProcessEditor;
-import org.argeo.slc.client.ui.editors.ProcessEditorInput;
-import org.argeo.slc.execution.ExecutionModulesManager;
-import org.argeo.slc.jcr.SlcJcrConstants;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.rap.rwt.service.ServerPushSession;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceAdapter;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-/** JCR based view of the execution modules. */
-public class JcrExecutionModulesView extends ViewPart implements SlcTypes, SlcNames {
- private final static CmsLog log = CmsLog.getLog(JcrExecutionModulesView.class);
-
- public static final String ID = ClientUiPlugin.ID + ".jcrExecutionModulesView";
-
- private TreeViewer viewer;
-
- private ServerPushSession pushSession;
-
- /* DEPENDENCY INJECTION */
- private Repository repository;
- private Session session;
- private ExecutionModulesManager modulesManager;
-
- public void createPartControl(Composite parent) {
- pushSession = new ServerPushSession();
- pushSession.start();
-
- try {
- session = repository.login();
- } catch (RepositoryException e1) {
- throw new SlcException("Cannot log in to repository");
- }
-
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- EclipseUiSpecificUtils.enableToolTipSupport(viewer);
- ViewContentProvider contentProvider = new ViewContentProvider(session);
- viewer.setContentProvider(contentProvider);
- viewer.setComparer(new NodeElementComparer());
- final ViewLabelProvider viewLabelProvider = new ViewLabelProvider();
- viewer.setLabelProvider(viewLabelProvider);
- viewer.setInput(getViewSite());
- viewer.addDoubleClickListener(new ViewDoubleClickListener());
- // context menu
- // addContextMenu(viewer);
-
- getViewSite().setSelectionProvider(viewer);
-
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- // Transfer[] tt = new Transfer[] { EditorInputTransfer.getInstance() };
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- viewer.addDragSupport(operations, tt, new ViewDragListener());
-
- try {
- String[] nodeTypes = { SlcTypes.SLC_AGENT, SlcTypes.SLC_AGENT_FACTORY, SlcTypes.SLC_EXECUTION_MODULE };
- session.getWorkspace().getObservationManager().addEventListener(
- new VmAgentObserver(viewer.getTree().getDisplay()),
- Event.NODE_ADDED | Event.NODE_REMOVED | Event.NODE_MOVED, SlcJcrConstants.VM_AGENT_FACTORY_PATH,
- true, null, nodeTypes, false);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot add observer", e);
- }
- }
-
- public void setFocus() {
- viewer.getControl().setFocus();
- }
-
- public TreeViewer getViewer() {
- return viewer;
- }
-
- public void refreshView() {
- viewer.setInput(getViewSite());
- }
-
- // Controllers
- class ViewContentProvider extends SimpleNodeContentProvider {
- private static final long serialVersionUID = 5117887833174813672L;
-
- public ViewContentProvider(Session session) {
- super(session, new String[] { SlcJcrConstants.VM_AGENT_FACTORY_PATH });
- }
-
- @Override
- protected Object[] sort(Object parent, Object[] children) {
- Object[] sorted = new Object[children.length];
- System.arraycopy(children, 0, sorted, 0, children.length);
- Arrays.sort(sorted, new ViewComparator());
- return sorted;
- }
-
- @Override
- protected List<Node> filterChildren(List<Node> children) throws RepositoryException {
- for (Iterator<Node> it = children.iterator(); it.hasNext();) {
- Node node = it.next();
- // execution spec definitions
- if (node.getName().equals(SLC_EXECUTION_SPECS))
- it.remove();
- // flow values
- else if (node.getParent().isNodeType(SlcTypes.SLC_EXECUTION_FLOW))
- it.remove();
- }
- return super.filterChildren(children);
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof Node) {
- Node node = (Node) element;
- try {
- if (node.isNodeType(SlcTypes.SLC_EXECUTION_FLOW))
- return false;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot check has children", e);
- }
- }
- return super.hasChildren(element);
- }
- }
-
- static class ViewComparator implements Comparator<Object> {
-
- public int compare(Object o1, Object o2) {
- try {
- if (o1 instanceof Node && o2 instanceof Node) {
- Node node1 = (Node) o1;
- Node node2 = (Node) o2;
-
- if (node1.getName().equals(SLC_EXECUTION_SPECS))
- return -100;
- if (node2.getName().equals(SLC_EXECUTION_SPECS))
- return 100;
-
- if (node1.isNodeType(SLC_EXECUTION_FLOW) && node2.isNodeType(SLC_EXECUTION_FLOW)) {
- return node1.getName().compareTo(node2.getName());
- } else if (node1.isNodeType(SLC_EXECUTION_FLOW) && !node2.isNodeType(SLC_EXECUTION_FLOW)) {
- return 1;
- } else if (!node1.isNodeType(SLC_EXECUTION_FLOW) && node2.isNodeType(SLC_EXECUTION_FLOW)) {
- return -1;
- } else {
- // TODO: check title
- return node1.getName().compareTo(node2.getName());
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot compare " + o1 + " and " + o2, e);
- }
- return 0;
- }
-
- }
-
- // private void addContextMenu(TreeViewer flowsViewer) {
- //
- // final MenuManager menuMgr = new MenuManager();
- // menuMgr.setRemoveAllWhenShown(true);
- // menuMgr.addMenuListener(new IMenuListener() {
- //
- // public void menuAboutToShow(IMenuManager manager) {
- // menuMgr.add(new Action("Test") {
- // public void run() {
- // log.debug("do something");
- // }
- // });
- // }
- // });
- // Menu menu = menuMgr.createContextMenu(flowsViewer.getControl());
- // flowsViewer.getTree().setMenu(menu);
- // getSite().registerContextMenu(menuMgr, flowsViewer);
- // }
-
- class VmAgentObserver extends AsyncUiEventListener {
-
- public VmAgentObserver(Display display) {
- super(display);
- }
-
- protected void onEventInUiThread(List<Event> events) {
- for (Event event : events) {
- try {
- String path = event.getPath();
-
- if (session.itemExists(path)) {
- Node parentNode = session.getNode(path);// .getParent();
- if (log.isTraceEnabled())
- log.trace("Refresh " + parentNode + " after event " + event);
- viewer.refresh(parentNode);
- }
- } catch (RepositoryException e) {
- log.warn("Cannot process event " + event + ": " + e);
- }
- }
-
- // TODO: optimize based on event
- viewer.refresh();
- }
- }
-
- class ViewLabelProvider extends DefaultNodeLabelProvider implements ITableLabelProvider {
- private static final long serialVersionUID = 2410754425574656399L;
-
- @Override
- protected String getText(Node node) throws RepositoryException {
- if (node.isNodeType(NodeType.MIX_TITLE) && node.hasProperty(Property.JCR_TITLE))
- return node.getProperty(Property.JCR_TITLE).getString();
- else if (node.getName().equals(SLC_EXECUTION_SPECS))
- return "Execution Specifications";
- else if (node.getPath().equals(SlcJcrConstants.VM_AGENT_FACTORY_PATH))
- return "Internal Agents";
- return super.getText(node);
- }
-
- @Override
- public Image getImage(Node node) throws RepositoryException {
- // we try to optimize a bit by putting deeper nodes first
- if (node.getParent().isNodeType(SlcTypes.SLC_EXECUTION_SPEC_ATTRIBUTE))
- return SlcImages.CHOICES;
- else if (node.isNodeType(SlcTypes.SLC_EXECUTION_SPEC_ATTRIBUTE))
- return SlcImages.EXECUTION_SPEC_ATTRIBUTE;
- else if (node.isNodeType(SlcTypes.SLC_EXECUTION_SPEC))
- return SlcImages.EXECUTION_SPEC;
- else if (node.getName().equals(SLC_EXECUTION_SPECS))
- return SlcImages.EXECUTION_SPECS;
- else if (node.isNodeType(SlcTypes.SLC_EXECUTION_FLOW))
- return SlcImages.FLOW;
- else if (node.isNodeType(SlcTypes.SLC_MODULE)) {
- if (node.getProperty(SLC_STARTED).getBoolean())
- return SlcImages.MODULE;
- else
- return SlcImages.MODULE_STOPPED;
- } else if (node.isNodeType(SlcTypes.SLC_AGENT))
- return SlcImages.AGENT;
- else if (node.isNodeType(SlcTypes.SLC_AGENT_FACTORY))
- return SlcImages.AGENT_FACTORY;
- else
- return SlcImages.FOLDER;
- }
-
- public String getToolTipText(Node node) throws RepositoryException {
- if (node.isNodeType(NodeType.MIX_TITLE) && node.hasProperty(Property.JCR_DESCRIPTION))
- return node.getProperty(Property.JCR_DESCRIPTION).getString();
- return super.getToolTipText(node);
- }
-
- public String getColumnText(Object obj, int index) {
- return getText(obj);
- }
-
- public Image getColumnImage(Object obj, int index) {
- return getImage(obj);
- }
-
- }
-
- class ViewDoubleClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- Object obj = ((IStructuredSelection) evt.getSelection()).getFirstElement();
- try {
- if (obj instanceof Node) {
- Node node = (Node) obj;
- if (node.isNodeType(SLC_EXECUTION_MODULE)) {
- ClientUiPlugin.startStopExecutionModule(modulesManager, node);
- } else {
- String path = node.getPath();
- // TODO factorize with editor
- QueryManager qm = node.getSession().getWorkspace().getQueryManager();
- String statement = "SELECT * FROM [" + SlcTypes.SLC_EXECUTION_FLOW
- + "] WHERE ISDESCENDANTNODE(['" + path + "']) OR ISSAMENODE(['" + path + "'])";
- // log.debug(statement);
- Query query = qm.createQuery(statement, Query.JCR_SQL2);
-
- // order paths
- SortedSet<String> paths = new TreeSet<String>();
- for (NodeIterator nit = query.execute().getNodes(); nit.hasNext();) {
- paths.add(nit.nextNode().getPath());
- }
-
- IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage();
- activePage.openEditor(new ProcessEditorInput(new ArrayList<String>(paths), true),
- ProcessEditor.ID);
- }
- }
- } catch (Exception e) {
- throw new SlcException("Cannot open " + obj, e);
- }
- }
-
- }
-
- /** Listen to drags */
- class ViewDragListener extends DragSourceAdapter {
- private static final long serialVersionUID = 250270504802674171L;
-
- // Check if the drag action should start.
- public void dragStart(DragSourceEvent event) {
- // we only start drag if at least one of the selected elements is
- // valid
- boolean doIt = false;
- IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- try {
- while (it.hasNext()) {
- Object obj = it.next();
- if (obj instanceof Node) {
- Node node = (Node) obj;
- if (node.isNodeType(SlcTypes.SLC_EXECUTION_FLOW)
- || node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE)) {
- doIt = true;
- }
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot read node to set drag data", e);
- }
- event.doit = doIt;
- }
-
- public void dragSetData(DragSourceEvent event) {
- IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
- StringBuilder buf = new StringBuilder();
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- try {
-
- while (it.hasNext()) {
- Object obj = it.next();
-
- if (obj instanceof Node) {
- Node node = (Node) obj;
- if ((node.isNodeType(SlcTypes.SLC_EXECUTION_FLOW)
- || node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE))
- && TextTransfer.getInstance().isSupportedType(event.dataType)) {
- buf.append(node.getPath()).append('\n');
- }
- }
- }
- } catch (RepositoryException e) {
- throw new SlcException("Cannot read node to set drag data", e);
- }
-
- if (buf.length() > 0) {
- if (buf.charAt(buf.length() - 1) == '\n')
- buf.deleteCharAt(buf.length() - 1);
- event.data = buf.toString();
- log.debug("data set to : " + buf.toString());
- }
- }
- }
-
- public void dispose() {
- JcrUtils.logoutQuietly(session);
- if (pushSession != null)
- pushSession.stop();
- super.dispose();
- }
-
- // DEPENDENCY INJECTION
-
- public void setModulesManager(ExecutionModulesManager modulesManager) {
- this.modulesManager = modulesManager;
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.views;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-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.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.observation.ObservationManager;
-import javax.jcr.query.Query;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.client.ui.editors.ProcessEditor;
-import org.argeo.slc.client.ui.editors.ProcessEditorInput;
-import org.argeo.slc.execution.ExecutionProcess;
-import org.argeo.slc.jcr.SlcJcrUtils;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.rap.rwt.service.ServerPushSession;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-/** Displays processes. */
-public class JcrProcessListView extends ViewPart {
- public static final String ID = ClientUiPlugin.ID + ".jcrProcessListView";
-
- private TableViewer viewer;
- private ServerPushSession pushSession;
-
- private Repository repository;
- private Session session;
-
- private EventListener processesObserver;
-
- private DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
- private Integer queryLimit = 2000;
-
- public void createPartControl(Composite parent) {
- pushSession = new ServerPushSession();
- pushSession.start();
- try {
- session = repository.login(CmsConstants.HOME_WORKSPACE);
- } catch (RepositoryException re) {
- throw new SlcException("Unable to log in Repository " + repository, re);
- }
- Table table = createTable(parent);
- viewer = new TableViewer(table);
- viewer.setLabelProvider(new LabelProvider());
- viewer.setContentProvider(new ContentProvider());
- viewer.setInput(getViewSite());
- viewer.addDoubleClickListener(new ViewDoubleClickListener());
-
- processesObserver = new AsyncUiEventListener(viewer.getTable().getDisplay()) {
- protected void onEventInUiThread(List<Event> events) {
- // TODO optimize by updating only the changed process
- viewer.refresh();
- }
- };
- try {
- ObservationManager observationManager = session.getWorkspace().getObservationManager();
- observationManager.addEventListener(processesObserver,
- Event.NODE_ADDED | Event.NODE_REMOVED | Event.PROPERTY_CHANGED,
- SlcJcrUtils.getSlcProcessesBasePath(session), true, null, null, false);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot register listeners", e);
- }
-
- }
-
- protected Table createTable(Composite parent) {
- int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION;
- // does not function with RAP, commented for the time being
- // | SWT.HIDE_SELECTION;
-
- Table table = new Table(parent, style);
-
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
-
- TableColumn column = new TableColumn(table, SWT.LEFT, 0);
- column.setText("Date");
- column.setWidth(200);
-
- column = new TableColumn(table, SWT.LEFT, 1);
- column.setText("Host");
- column.setWidth(100);
-
- column = new TableColumn(table, SWT.LEFT, 2);
- column.setText("Id");
- column.setWidth(300);
-
- column = new TableColumn(table, SWT.LEFT, 3);
- column.setText("Status");
- column.setWidth(100);
-
- return table;
- }
-
- public void setFocus() {
- viewer.getControl().setFocus();
- }
-
- class ContentProvider implements IStructuredContentProvider {
-
- public Object[] getElements(Object inputElement) {
- try {
- // TODO filter, optimize with virtual table, ...
- String sql = "SELECT * from [slc:process] ORDER BY [jcr:lastModified] DESC";
- Query query = session.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
- // TODO paging
- query.setLimit(queryLimit);
- List<Node> nodes = new ArrayList<Node>();
- for (NodeIterator nit = query.execute().getNodes(); nit.hasNext();) {
- nodes.add(nit.nextNode());
- }
- return nodes.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot retrieve processes", e);
- }
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- }
-
- class LabelProvider extends ColumnLabelProvider implements ITableLabelProvider {
-
- public Image getColumnImage(Object obj, int columnIndex) {
- if (columnIndex != 0)
- return null;
- try {
- Node node = (Node) obj;
- String status = node.getProperty(SlcNames.SLC_STATUS).getString();
- if (status.equals(ExecutionProcess.NEW) || status.equals(ExecutionProcess.INITIALIZED)
- || status.equals(ExecutionProcess.SCHEDULED))
- return SlcImages.PROCESS_SCHEDULED;
- else if (status.equals(ExecutionProcess.ERROR) || status.equals(ExecutionProcess.UNKOWN))
- return SlcImages.PROCESS_ERROR;
- else if (status.equals(ExecutionProcess.COMPLETED))
- return SlcImages.PROCESS_COMPLETED;
- else if (status.equals(ExecutionProcess.RUNNING))
- return SlcImages.PROCESS_RUNNING;
- else if (status.equals(ExecutionProcess.KILLED))
- return SlcImages.PROCESS_ERROR;
- else
- throw new SlcException("Unkown status " + status);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get column text", e);
- }
- }
-
- public String getColumnText(Object obj, int index) {
- try {
- Node node = (Node) obj;
- switch (index) {
-
- case 0:
- return dateFormat.format(node.getProperty(Property.JCR_LAST_MODIFIED).getDate().getTime());
- case 1:
- return "local";
- case 2:
- return node.getProperty(SlcNames.SLC_UUID).getString();
- case 3:
- return node.getProperty(SlcNames.SLC_STATUS).getString();
- }
- return getText(obj);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get column text", e);
- }
- }
-
- }
-
- class ViewDoubleClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- Object obj = ((IStructuredSelection) evt.getSelection()).getFirstElement();
- try {
- if (obj instanceof Node) {
- Node node = (Node) obj;
- if (node.isNodeType(SlcTypes.SLC_PROCESS)) {
- IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage();
- activePage.openEditor(new ProcessEditorInput(node.getPath()), ProcessEditor.ID);
- }
- }
- } catch (Exception e) {
- throw new SlcException("Cannot open " + obj, e);
- }
- }
-
- }
-
- public void dispose() {
- JcrUtils.unregisterQuietly(session.getWorkspace(), processesObserver);
- JcrUtils.logoutQuietly(session);
- if (pushSession != null)
- pushSession.stop();
- super.dispose();
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.views;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.observation.ObservationManager;
-import javax.jcr.query.Query;
-
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.eclipse.ui.jcr.NodeElementComparer;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.editors.ProcessEditor;
-import org.argeo.slc.client.ui.editors.ProcessEditorInput;
-import org.argeo.slc.jcr.SlcJcrResultUtils;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-/** Displays results. */
-public class JcrResultListView extends ViewPart implements SlcNames {
- public static final String ID = ClientUiPlugin.ID + ".jcrResultListView";
-
- private TableViewer viewer;
-
- private Repository repository;
- private Session session;
-
- private EventListener resultsObserver;
-
- private DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
- private Integer queryLimit = 2000;
-
- public void createPartControl(Composite parent) {
- try {
- session = repository.login();
- } catch (RepositoryException e1) {
- throw new SlcException("Cannot log in to repository");
- }
-
- Table table = createTable(parent);
- viewer = new TableViewer(table);
- viewer.setLabelProvider(createLabelProvider());
- viewer.setContentProvider(new ViewContentProvider());
- viewer.setInput(getViewSite());
- viewer.addDoubleClickListener(new ViewDoubleClickListener());
- viewer.setComparer(new NodeElementComparer());
-
- getViewSite().setSelectionProvider(viewer);
-
- resultsObserver = new ResultObserver(viewer.getTable().getDisplay());
- try {
- ObservationManager observationManager = session.getWorkspace().getObservationManager();
- String[] nodeTypes = { SlcTypes.SLC_TEST_RESULT };
- // FIXME Will not be notified if empty result is deleted
- observationManager.addEventListener(resultsObserver, Event.PROPERTY_ADDED | Event.NODE_REMOVED,
- SlcJcrResultUtils.getSlcResultsBasePath(session), true, null, nodeTypes, false);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot register listeners", e);
- }
-
- }
-
- protected Table createTable(Composite parent) {
- int style = SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.MULTI;
- // does not work with RAP, commented for the time being
- // | SWT.HIDE_SELECTION;
-
- Table table = new Table(parent, style);
-
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
-
- TableColumn column = new TableColumn(table, SWT.LEFT, 0);
- column.setText("Date");
- column.setWidth(200);
-
- column = new TableColumn(table, SWT.LEFT, 1);
- column.setText("Id");
- column.setWidth(300);
-
- return table;
- }
-
- // public void refresh() {
- // viewer.refresh();
- // }
-
- /*
- * METHODS TO BE OVERRIDDEN
- */
- protected IBaseLabelProvider createLabelProvider() {
- return new ViewLabelProvider();
- }
-
- protected void processDoubleClick(DoubleClickEvent evt) {
- Object obj = ((IStructuredSelection) evt.getSelection()).getFirstElement();
- try {
- if (obj instanceof Node) {
- Node node = (Node) obj;
- // FIXME: open a default result editor
- if (node.isNodeType(SlcTypes.SLC_PROCESS)) {
- IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- activePage.openEditor(new ProcessEditorInput(node.getPath()), ProcessEditor.ID);
- }
- }
- } catch (Exception e) {
- throw new SlcException("Cannot open " + obj, e);
- }
- }
-
- public void setFocus() {
- viewer.getControl().setFocus();
- }
-
- class ViewContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -4719077015405546260L;
-
- public Object[] getElements(Object inputElement) {
- try {
- // TODO filter, optimize with virtual table, ...
- String sql = "SELECT * from [" + SlcTypes.SLC_TEST_RESULT + "] ORDER BY [jcr:lastModified] DESC";
- Query query = session.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
- // TODO paging
- query.setLimit(queryLimit);
- List<Node> nodes = new ArrayList<Node>();
- for (NodeIterator nit = query.execute().getNodes(); nit.hasNext();) {
- nodes.add(nit.nextNode());
- }
- return nodes.toArray();
- } catch (RepositoryException e) {
- throw new SlcException("Cannot retrieve processes", e);
- }
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- }
-
- class ViewLabelProvider extends ColumnLabelProvider implements ITableLabelProvider {
- private static final long serialVersionUID = -6323202576386795247L;
-
- public Image getColumnImage(Object obj, int columnIndex) {
- if (columnIndex != 0)
- return null;
- try {
- Node node = (Node) obj;
- if (node.hasProperty(SLC_COMPLETED)) {
- // TODO
- }
- return null;
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get column text", e);
- }
- }
-
- public String getColumnText(Object obj, int index) {
- try {
- Node node = (Node) obj;
- switch (index) {
-
- case 0:
- if (node.hasProperty(SLC_COMPLETED)) {
- return dateFormat.format(node.getProperty(SLC_COMPLETED).getDate().getTime());
- } else {
- return "OPEN";
- }
- case 1:
- return node.getProperty(SlcNames.SLC_UUID).getString();
- }
- return getText(obj);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get column text", e);
- }
- }
-
- }
-
- class ViewDoubleClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- processDoubleClick(evt);
- }
-
- }
-
- class ResultObserver extends AsyncUiEventListener {
-
- public ResultObserver(Display display) {
- super(display);
- }
-
- @Override
- protected Boolean willProcessInUiThread(List<Event> events) throws RepositoryException {
- for (Event event : events) {
- // getLog().debug("Received event " + event);
- int eventType = event.getType();
- if (eventType == Event.NODE_REMOVED)
- return true;
- String path = event.getPath();
- int index = path.lastIndexOf('/');
- String propertyName = path.substring(index + 1);
- if (propertyName.equals(SLC_COMPLETED) || propertyName.equals(SLC_UUID)) {
- return true;
- }
- }
- return false;
- }
-
- protected void onEventInUiThread(List<Event> events) throws RepositoryException {
- if (getLog().isTraceEnabled())
- getLog().trace("Refresh result list");
- viewer.refresh();
- }
- }
-
- public void dispose() {
- JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);
- JcrUtils.logoutQuietly(session);
- super.dispose();
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.client.ui.views;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.List;
-
-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.observation.Event;
-import javax.jcr.observation.EventListener;
-import javax.jcr.observation.ObservationManager;
-
-import org.argeo.api.cms.CmsConstants;
-import org.argeo.cms.ui.workbench.util.CommandUtils;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.SlcNames;
-import org.argeo.slc.SlcTypes;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.SlcUiConstants;
-import org.argeo.slc.client.ui.commands.AddResultFolder;
-import org.argeo.slc.client.ui.commands.DeleteItems;
-import org.argeo.slc.client.ui.commands.RefreshJcrResultTreeView;
-import org.argeo.slc.client.ui.commands.RenameResultFolder;
-import org.argeo.slc.client.ui.commands.RenameResultNode;
-import org.argeo.slc.client.ui.editors.ProcessEditor;
-import org.argeo.slc.client.ui.editors.ProcessEditorInput;
-import org.argeo.slc.client.ui.model.ParentNodeFolder;
-import org.argeo.slc.client.ui.model.ResultFolder;
-import org.argeo.slc.client.ui.model.ResultItemsComparator;
-import org.argeo.slc.client.ui.model.ResultItemsComparer;
-import org.argeo.slc.client.ui.model.ResultParent;
-import org.argeo.slc.client.ui.model.ResultParentUtils;
-import org.argeo.slc.client.ui.model.SingleResultNode;
-import org.argeo.slc.client.ui.model.VirtualFolder;
-import org.argeo.slc.client.ui.providers.ResultTreeContentProvider;
-import org.argeo.slc.client.ui.providers.ResultTreeLabelProvider;
-import org.argeo.slc.jcr.SlcJcrResultUtils;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.DecoratingLabelProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-/** SLC generic JCR Result tree view. */
-public class JcrResultTreeView extends ViewPart {
- public final static String ID = ClientUiPlugin.ID + ".jcrResultTreeView";
-
- private final static DateFormat dateFormat = new SimpleDateFormat(
- SlcUiConstants.DEFAULT_DISPLAY_DATE_TIME_FORMAT);
-
- // private final static Log log =
- // LogFactory.getLog(JcrResultTreeView.class);
-
- /* DEPENDENCY INJECTION */
- private Repository repository;
- private Session session;
-
- // This page widgets
- private TreeViewer resultTreeViewer;
- private TableViewer propertiesViewer;
-
- private EventListener myResultsObserver = null;
- private EventListener allResultsObserver = null;
-
- // under My Results
- private final static String[] observedNodeTypesUnderMyResult = {
- SlcTypes.SLC_TEST_RESULT, SlcTypes.SLC_RESULT_FOLDER,
- SlcTypes.SLC_MY_RESULT_ROOT_FOLDER };
-
- private final static String[] observedNodeTypesUnderAllResults = {
- SlcTypes.SLC_TEST_RESULT, NodeType.NT_UNSTRUCTURED };
-
- private boolean isResultFolder = false;
-
- /**
- * To be overridden to adapt size of form and result frames.
- */
- protected int[] getWeights() {
- return new int[] { 70, 30 };
- }
-
- @Override
- public void createPartControl(Composite parent) {
- try {
- session = repository.login(CmsConstants.HOME_WORKSPACE);
- } catch (RepositoryException e1) {
- throw new SlcException("Cannot log in to repository");
- }
-
- parent.setLayout(new FillLayout());
- // Main layout
- SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
- sashForm.setSashWidth(4);
- sashForm.setLayout(new FillLayout());
-
- // Create the tree on top of the view
- Composite top = new Composite(sashForm, SWT.NONE);
- GridLayout gl = new GridLayout(1, false);
- top.setLayout(gl);
- resultTreeViewer = createResultsTreeViewer(top);
-
- // Create the property viewer on the bottom
- Composite bottom = new Composite(sashForm, SWT.NONE);
- bottom.setLayout(new GridLayout(1, false));
- propertiesViewer = createPropertiesViewer(bottom);
-
- sashForm.setWeights(getWeights());
-
- setOrderedInput(resultTreeViewer);
-
- // Initialize observer
- try {
- ObservationManager observationManager = session.getWorkspace()
- .getObservationManager();
- myResultsObserver = new MyResultsObserver(resultTreeViewer
- .getTree().getDisplay());
- allResultsObserver = new AllResultsObserver(resultTreeViewer
- .getTree().getDisplay());
-
- // observe tree changes under MyResults
- observationManager.addEventListener(myResultsObserver,
- Event.NODE_ADDED | Event.NODE_REMOVED,
- SlcJcrResultUtils.getMyResultsBasePath(session), true,
- null, observedNodeTypesUnderMyResult, false);
- // observe tree changes under All results
- observationManager.addEventListener(allResultsObserver,
- Event.NODE_ADDED | Event.NODE_REMOVED,
- SlcJcrResultUtils.getSlcResultsBasePath(session), true,
- null, observedNodeTypesUnderAllResults, false);
- } catch (RepositoryException e) {
- throw new SlcException("Cannot register listeners", e);
- }
- }
-
- /**
- * Override default behaviour so that default defined order remains
- * unchanged on first level of the tree
- */
- private void setOrderedInput(TreeViewer viewer) {
- // Add specific ordering
- viewer.setInput(null);
- viewer.setComparator(null);
- viewer.setInput(initializeResultTree());
- viewer.setComparator(new ResultItemsComparator());
- }
-
- // The main tree viewer
- protected TreeViewer createResultsTreeViewer(Composite parent) {
- int style = SWT.BORDER | SWT.MULTI;
-
- TreeViewer viewer = new TreeViewer(parent, style);
- viewer.getTree().setLayoutData(
- new GridData(SWT.FILL, SWT.FILL, true, true));
-
- viewer.setContentProvider(new ResultTreeContentProvider());
-
- // Add label provider with label decorator
- ResultTreeLabelProvider rtLblProvider = new ResultTreeLabelProvider();
- ILabelDecorator decorator = ClientUiPlugin.getDefault().getWorkbench()
- .getDecoratorManager().getLabelDecorator();
- viewer.setLabelProvider(new DecoratingLabelProvider(rtLblProvider,
- decorator));
- viewer.addDoubleClickListener(new ViewDoubleClickListener());
-
- // Override default behaviour to insure that 2 distincts results that
- // have the same name will be correctly and distincly returned by
- // corresponding TreeViewer.getSelection() method.
- viewer.setComparer(new ResultItemsComparer());
-
- // viewer.setLabelProvider(rtLblProvider);
- getSite().setSelectionProvider(viewer);
-
- // add drag & drop support
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- viewer.addDragSupport(operations, tt, new ViewDragListener());
- viewer.addDropSupport(operations, tt, new ViewDropListener(viewer));
-
- // add context menu
- MenuManager menuManager = new MenuManager();
- Menu menu = menuManager.createContextMenu(viewer.getTree());
- menuManager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- contextMenuAboutToShow(manager);
- }
- });
- viewer.getTree().setMenu(menu);
- menuManager.setRemoveAllWhenShown(true);
-
- getSite().registerContextMenu(menuManager, viewer);
-
- // add change listener to display TestResult information in the property
- // viewer
- viewer.addSelectionChangedListener(new MySelectionChangedListener());
- return viewer;
- }
-
- // Detailed property viewer
- protected TableViewer createPropertiesViewer(Composite parent) {
- propertiesViewer = new TableViewer(parent);
- propertiesViewer.getTable().setLayoutData(
- new GridData(SWT.FILL, SWT.FILL, true, true));
- propertiesViewer.getTable().setHeaderVisible(true);
- propertiesViewer.setContentProvider(new PropertiesContentProvider());
- TableViewerColumn col = new TableViewerColumn(propertiesViewer,
- SWT.NONE);
- col.getColumn().setText("Name");
- col.getColumn().setWidth(100);
- col.setLabelProvider(new ColumnLabelProvider() {
- public String getText(Object element) {
- try {
- String name = ((Property) element).getName();
- String value = null;
- if (SlcNames.SLC_TEST_CASE.equals(name))
- value = "Test case";
- else if (SlcNames.SLC_COMPLETED.equals(name))
- value = "Completed on";
- else if (SlcNames.SLC_SUCCESS.equals(name))
- value = "Status";
- else if (SlcNames.SLC_MESSAGE.equals(name))
- value = "Message";
- else if (SlcNames.SLC_ERROR_MESSAGE.equals(name))
- value = "Error";
- return value;
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception in label provider", e);
- }
- }
- });
- col = new TableViewerColumn(propertiesViewer, SWT.NONE);
- col.getColumn().setText("Value");
- col.getColumn().setWidth(200);
- col.setLabelProvider(new ColumnLabelProvider() {
- public String getText(Object element) {
- try {
- Property property = (Property) element;
- String name = property.getName();
- String value = null;
-
- if (SlcNames.SLC_TEST_CASE.equals(name)
- || SlcNames.SLC_ERROR_MESSAGE.equals(name)
- || SlcNames.SLC_MESSAGE.equals(name))
- value = property.getValue().getString();
- else if (SlcNames.SLC_COMPLETED.equals(name)) {
- Calendar date = property.getValue().getDate();
- value = dateFormat.format(date.getTime());
- } else if (SlcNames.SLC_SUCCESS.equals(name)) {
- if (property.getValue().getBoolean())
- value = "PASSED";
- else {
- if (property.getParent().hasProperty(
- SlcNames.SLC_ERROR_MESSAGE))
- value = "ERROR";
- else
- value = "FAILED";
- }
- }
- return value;
- } catch (RepositoryException e) {
- throw new SlcException(
- "Unexpected exception in label provider", e);
- }
- }
- });
- propertiesViewer.setInput(getViewSite());
- return propertiesViewer;
- }
-
- /**
- * Override to provide specific behaviour. Typically to enable the display
- * of a result file.
- *
- * @param evt
- */
- protected void processDoubleClick(DoubleClickEvent evt) {
- Object obj = ((IStructuredSelection) evt.getSelection())
- .getFirstElement();
- try {
- if (obj instanceof SingleResultNode) {
- SingleResultNode srNode = (SingleResultNode) obj;
- Node node = srNode.getNode();
- // FIXME: open a default result editor
- if (node.isNodeType(SlcTypes.SLC_PROCESS)) {
- IWorkbenchPage activePage = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- activePage.openEditor(
- new ProcessEditorInput(node.getPath()),
- ProcessEditor.ID);
- }
- }
- } catch (Exception e) {
- throw new SlcException("Cannot open " + obj, e);
- }
- }
-
- @Override
- public void setFocus() {
- }
-
- /**
- * refreshes the passed resultParent and its corresponding subtree. It
- * refreshes the whole viewer if null is passed.
- *
- * @param ResultParent
- *
- */
- public void refresh(ResultParent resultParent) {
- if (resultParent == null) {
- if (!resultTreeViewer.getTree().isDisposed()) {
- TreePath[] tps = resultTreeViewer.getExpandedTreePaths();
- setOrderedInput(resultTreeViewer);
- resultTreeViewer.setExpandedTreePaths(tps);
- } else
- setOrderedInput(resultTreeViewer);
- } else {
- if (resultParent instanceof ParentNodeFolder) {
- ParentNodeFolder currFolder = (ParentNodeFolder) resultParent;
- jcrRefresh(currFolder.getNode());
- currFolder.forceFullRefresh();
- }
- // FIXME: specific refresh does not work
- // resultTreeViewer.refresh(resultParent, true);
- refresh(null);
- }
- }
-
- /**
- * refreshes the passed node and its corresponding subtree.
- *
- * @param node
- * cannot be null
- *
- */
- public boolean jcrRefresh(Node node) {
- // if (log.isDebugEnabled())
- // log.debug(" JCR refreshing " + node + "...");
- // Thread.dumpStack();
- boolean isPassed = true;
- try {
- if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {
- isPassed = node.getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean();
- } else if (node.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {
- NodeIterator ni = node.getNodes();
- while (ni.hasNext()) {
- Node currChild = ni.nextNode();
- isPassed = isPassed & jcrRefresh(currChild);
- }
- if (isPassed != node.getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean()) {
- node.getNode(SlcNames.SLC_AGGREGATED_STATUS).setProperty(
- SlcNames.SLC_SUCCESS, isPassed);
- node.getSession().save();
- return isPassed;
- }
- } else
- ; // do nothing
- } catch (RepositoryException e) {
- throw new SlcException("Cannot register listeners", e);
- }
- return isPassed;
- }
-
- private ResultParent[] initializeResultTree() {
- try {
- // Force initialization of the tree structure if needed
- SlcJcrResultUtils.getSlcResultsParentNode(session);
- SlcJcrResultUtils.getMyResultParentNode(session);
- // Remove yesterday and last 7 days virtual folders
- // ResultParent[] roots = new ResultParent[5];
- ResultParent[] roots = new ResultParent[3];
-
- // My results
- roots[0] = new ParentNodeFolder(null,
- SlcJcrResultUtils.getMyResultParentNode(session),
- SlcUiConstants.DEFAULT_MY_RESULTS_FOLDER_LABEL);
-
- // today
- Calendar cal = Calendar.getInstance();
- String relPath = JcrUtils.dateAsPath(cal);
- List<String> datePathes = new ArrayList<String>();
- datePathes.add(relPath);
- roots[1] = new VirtualFolder(null,
- ResultParentUtils.getResultsForDates(session, datePathes),
- "Today");
-
- // // Yesterday
- // cal = Calendar.getInstance();
- // cal.add(Calendar.DAY_OF_YEAR, -1);
- // relPath = JcrUtils.dateAsPath(cal);
- // datePathes = new ArrayList<String>();
- // datePathes.add(relPath);
- // roots[2] = new VirtualFolder(null,
- // ResultParentUtils.getResultsForDates(session, datePathes),
- // "Yesterday");
- // // Last 7 days
- //
- // cal = Calendar.getInstance();
- // datePathes = new ArrayList<String>();
- //
- // for (int i = 0; i < 7; i++) {
- // cal.add(Calendar.DAY_OF_YEAR, -i);
- // relPath = JcrUtils.dateAsPath(cal);
- // datePathes.add(relPath);
- // }
- // roots[3] = new VirtualFolder(null,
- // ResultParentUtils.getResultsForDates(session, datePathes),
- // "Last 7 days");
-
- // All results
- Node otherResultsPar = session.getNode(SlcJcrResultUtils
- .getSlcResultsBasePath(session));
- // roots[4] = new ParentNodeFolder(null, otherResultsPar,
- // "All results");
- roots[2] = new ParentNodeFolder(null, otherResultsPar,
- "All results");
- return roots;
- } catch (RepositoryException re) {
- throw new SlcException(
- "Unexpected error while initializing ResultTree.", re);
- }
- }
-
- // Manage context menu
- /**
- * Defines the commands that will pop up in the context menu.
- **/
- protected void contextMenuAboutToShow(IMenuManager menuManager) {
- IWorkbenchWindow window = ClientUiPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
-
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer
- .getSelection();
- boolean canAddSubfolder = false;
- boolean canRenamefolder = false;
- boolean isSingleResultNode = false;
- boolean isUnderMyResult = false;
- boolean validMultipleDelete = false;
- try {
-
- // Building conditions
- if (selection.size() == 1) {
- Object obj = selection.getFirstElement();
- if (obj instanceof SingleResultNode)
- isSingleResultNode = true;
- else if (obj instanceof ParentNodeFolder) {
- Node cNode = ((ParentNodeFolder) obj).getNode();
- if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {
- canAddSubfolder = true;
- canRenamefolder = true;
- isUnderMyResult = true;
- } else if (cNode
- .isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER)) {
- canAddSubfolder = true;
- }
- }
- } else {
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- multicheck: while (it.hasNext()) {
- validMultipleDelete = true;
- Object obj = it.next();
- if (obj instanceof SingleResultNode)
- continue multicheck;
- else if (obj instanceof ParentNodeFolder) {
- Node cNode = ((ParentNodeFolder) obj).getNode();
- if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER))
- continue multicheck;
- else {
- validMultipleDelete = false;
- break multicheck;
- }
- } else {
- validMultipleDelete = false;
- break multicheck;
- }
- }
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while building condition for context menu",
- re);
- }
-
- // Effective Refresh
- CommandUtils.refreshCommand(menuManager, window,
- RefreshJcrResultTreeView.ID,
- RefreshJcrResultTreeView.DEFAULT_LABEL,
- RefreshJcrResultTreeView.DEFAULT_IMG_DESCRIPTOR, true);
-
- CommandUtils.refreshCommand(menuManager, window, DeleteItems.ID,
- DeleteItems.DEFAULT_LABEL, DeleteItems.DEFAULT_IMG_DESCRIPTOR,
- isUnderMyResult || isSingleResultNode || validMultipleDelete);
-
- CommandUtils.refreshCommand(menuManager, window, AddResultFolder.ID,
- AddResultFolder.DEFAULT_LABEL,
- ClientUiPlugin.getDefault().getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD),
- canAddSubfolder);
-
- CommandUtils.refreshCommand(menuManager, window, RenameResultFolder.ID,
- RenameResultFolder.DEFAULT_LABEL,
- RenameResultFolder.DEFAULT_IMG_DESCRIPTOR, canRenamefolder);
-
- // Command removed for the time being.
- CommandUtils.refreshCommand(menuManager, window, RenameResultNode.ID,
- RenameResultNode.DEFAULT_LABEL,
- RenameResultNode.DEFAULT_IMG_DESCRIPTOR, false);
-
- // Test to be removed
- // If you use this pattern, do not forget to call
- // menuManager.setRemoveAllWhenShown(true);
- // when creating the menuManager
-
- // menuManager.add(new Action("Test") {
- // public void run() {
- // log.debug("do something");
- // }
- // });
- }
-
- /* INNER CLASSES */
- class ViewDragListener implements DragSourceListener {
-
- public void dragStart(DragSourceEvent event) {
- // Check if the drag action should start.
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer
- .getSelection();
- boolean doIt = false;
-
- // FIXME clean this code.
- try {
- if (selection.size() == 1) {
- Object obj = selection.getFirstElement();
- if (obj instanceof ResultFolder) {
- Node tNode = ((ResultFolder) obj).getNode();
- if (tNode.getPrimaryNodeType().isNodeType(
- SlcTypes.SLC_RESULT_FOLDER)) {
- doIt = true;
- isResultFolder = true;
- }
- } else
- isResultFolder = false;
- } else
- isResultFolder = false;
-
- if (!isResultFolder) {
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- while (it.hasNext()) {
- Object obj = it.next();
- if (obj instanceof SingleResultNode) {
- Node tNode = ((SingleResultNode) obj).getNode();
- if (tNode.getPrimaryNodeType().isNodeType(
- SlcTypes.SLC_TEST_RESULT)) {
- doIt = true;
- }
- }
- }
- }
-
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while validating drag source", re);
- }
- event.doit = doIt;
- }
-
- public void dragSetData(DragSourceEvent event) {
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer
- .getSelection();
-
- try {
- // specific case of a result folder
- if (isResultFolder) {
- Object obj = selection.getFirstElement();
- event.data = ((ResultFolder) obj).getNode().getIdentifier();
- } else {
- @SuppressWarnings("rawtypes")
- Iterator it = selection.iterator();
- StringBuilder nodes = new StringBuilder();
- while (it.hasNext()) {
- Object obj = it.next();
- if (obj instanceof SingleResultNode) {
- Node tNode = ((SingleResultNode) obj).getNode();
- if (tNode.getPrimaryNodeType().isNodeType(
- SlcTypes.SLC_TEST_RESULT)) {
- nodes.append(tNode.getIdentifier()).append(";");
- }
- }
- }
- event.data = nodes.toString();
- }
- } catch (RepositoryException re) {
- throw new SlcException("unexpected error while setting data",
- re);
- }
- }
-
- public void dragFinished(DragSourceEvent event) {
- // refresh is done via observer
- }
- }
-
- // Implementation of the Drop Listener
- protected class ViewDropListener extends ViewerDropAdapter {
- private Node targetParentNode = null;
-
- public ViewDropListener(Viewer viewer) {
- super(viewer);
- }
-
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- boolean validDrop = false;
- try {
- // We can only drop under myResults
- Node tpNode = null;
- if (target instanceof SingleResultNode) {
- Node currNode = ((SingleResultNode) target).getNode();
- String pPath = currNode.getParent().getPath();
- if (pPath.startsWith(SlcJcrResultUtils
- .getMyResultsBasePath(session)))
- tpNode = currNode.getParent();
- } else if (target instanceof ResultFolder) {
- tpNode = ((ResultFolder) target).getNode();
- } else if (target instanceof ParentNodeFolder) {
- Node node = ((ParentNodeFolder) target).getNode();
- if (node.isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER))
- tpNode = ((ParentNodeFolder) target).getNode();
- }
-
- if (tpNode != null) {
- targetParentNode = tpNode;
- validDrop = true;
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while validating drop target", re);
- }
- return validDrop;
- }
-
- @Override
- public boolean performDrop(Object data) {
- // clear selection to prevent unwanted scrolling of the UI
- resultTreeViewer.setSelection(null);
- try {
- if (isResultFolder) {
- // Sanity check : we cannot move a folder to one of its sub
- // folder or neither move an object in the same parent
- // folder
- Node source = session.getNodeByIdentifier((String) data);
- if (targetParentNode.getPath().startsWith(source.getPath())
- || source.getParent().getPath()
- .equals(targetParentNode.getPath()))
- return false;
-
- // Move
- String sourcePath = source.getPath();
- String destPath = targetParentNode.getPath() + "/"
- + source.getName();
- session.move(sourcePath, destPath);
- // Update passed status of the parent source Node
- ResultParentUtils.updatePassedStatus(
- session.getNode(JcrUtils.parentPath(sourcePath)),
- true);
- // Node target = session.getNode(destPath);
- session.save();
- return true;
- }
-
- String[] datas = ((String) data).split(";");
- nodesToCopy: for (String id : datas) {
-
- Node source = session.getNodeByIdentifier(id);
- String name;
- if (source.hasProperty(Property.JCR_TITLE))
- name = source.getProperty(Property.JCR_TITLE)
- .getString();
- else if (source.hasProperty(SlcNames.SLC_TEST_CASE))
- name = source.getProperty(SlcNames.SLC_TEST_CASE)
- .getString();
- else
- name = source.getName();
-
- // Check if another copy of the same test instance already
- // exists at target
- NodeIterator ni = targetParentNode.getNodes();
- String slcUid = source.getProperty(SlcNames.SLC_UUID)
- .getString();
- while (ni.hasNext()) {
- Node curr = ni.nextNode();
- if (curr.hasProperty(SlcNames.SLC_UUID)
- && slcUid.equals(curr.getProperty(
- SlcNames.SLC_UUID).getString())) {
- MessageDialog
- .openWarning(
- PlatformUI.getWorkbench()
- .getDisplay()
- .getActiveShell(),
- "Duplicated instance.",
- "An instance of the same test case ("
- + name
- + ") exists at destination.\n "
- + "This item will not be neither copied nor moved.");
- continue nodesToCopy;
-
- }
- }
-
- Node target;
- boolean passedStatus = false;
- if (source.hasNode(SlcNames.SLC_AGGREGATED_STATUS))
- passedStatus = source
- .getNode(SlcNames.SLC_AGGREGATED_STATUS)
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean();
-
- boolean isActionUnderMyResult = source.getPath()
- .startsWith(
- SlcJcrResultUtils
- .getMyResultsBasePath(session));
-
- if (!isActionUnderMyResult) {// Copy
- target = targetParentNode.addNode(source.getName(),
- source.getPrimaryNodeType().getName());
- JcrUtils.copy(source, target);
- } else {// move
- String sourcePath = source.getPath();
- String destPath = targetParentNode.getPath() + "/"
- + name;
- session.move(sourcePath, destPath);
- // Update passed status of the parent source Node
- ResultParentUtils
- .updatePassedStatus(session.getNode(JcrUtils
- .parentPath(sourcePath)), true);
- target = session.getNode(destPath);
-
- }
- if (!target.isNodeType(NodeType.MIX_TITLE))
- target.addMixin(NodeType.MIX_TITLE);
- target.setProperty(Property.JCR_TITLE, name);
- ResultParentUtils.updatePassedStatus(target.getParent(),
- passedStatus);
- session.save();
- }
- } catch (RepositoryException re) {
- throw new SlcException(
- "unexpected error while copying dropped node", re);
-
- }
- return true;
- }
- }
-
- class MyResultsObserver extends AsyncUiEventListener {
-
- public MyResultsObserver(Display display) {
- super(display);
- }
-
- @Override
- protected Boolean willProcessInUiThread(List<Event> events)
- throws RepositoryException {
- // unfiltered for the time being
- return true;
- }
-
- protected void onEventInUiThread(List<Event> events)
- throws RepositoryException {
- List<Node> nodesToRefresh = new ArrayList<Node>();
-
- for (Event event : events) {
- String parPath = JcrUtils.parentPath(event.getPath());
- if (session.nodeExists(parPath)) {
- Node node = session.getNode(parPath);
- if (!nodesToRefresh.contains(node)) {
- nodesToRefresh.add(node);
- }
- }
- }
-
- // Update check nodes
- for (Node node : nodesToRefresh)
- jcrRefresh(node);
- refresh(null);
- }
- }
-
- class AllResultsObserver extends AsyncUiEventListener {
-
- public AllResultsObserver(Display display) {
- super(display);
- }
-
- @Override
- protected Boolean willProcessInUiThread(List<Event> events)
- throws RepositoryException {
- // unfiltered for the time being
- return true;
- }
-
- protected void onEventInUiThread(List<Event> events)
- throws RepositoryException {
- refresh(null);
- // if (lastSelectedSourceElementParent != null)
- // refresh(lastSelectedSourceElementParent);
- }
- }
-
- class PropertiesContentProvider implements IStructuredContentProvider {
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public Object[] getElements(Object inputElement) {
- try {
- if (inputElement instanceof Node) {
- Node node = (Node) inputElement;
- if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {
- List<Property> props = new ArrayList<Property>();
- if (node.hasProperty(SlcNames.SLC_TEST_CASE))
- props.add(node.getProperty(SlcNames.SLC_TEST_CASE));
- if (node.hasProperty(SlcNames.SLC_COMPLETED))
- props.add(node.getProperty(SlcNames.SLC_COMPLETED));
- if (node.hasNode(SlcNames.SLC_AGGREGATED_STATUS)) {
- Node status = node
- .getNode(SlcNames.SLC_AGGREGATED_STATUS);
- props.add(status.getProperty(SlcNames.SLC_SUCCESS));
- if (status.hasProperty(SlcNames.SLC_MESSAGE))
- props.add(status
- .getProperty(SlcNames.SLC_MESSAGE));
- if (status.hasProperty(SlcNames.SLC_ERROR_MESSAGE))
- props.add(status
- .getProperty(SlcNames.SLC_ERROR_MESSAGE));
- }
- return props.toArray();
- }
- }
- return new Object[] {};
-
- } catch (RepositoryException e) {
- throw new SlcException("Cannot get element for "
- + inputElement, e);
- }
- }
- }
-
- class MySelectionChangedListener implements ISelectionChangedListener {
-
- public void selectionChanged(SelectionChangedEvent event) {
- if (!event.getSelection().isEmpty()) {
- IStructuredSelection sel = (IStructuredSelection) event
- .getSelection();
- ResultParent firstItem = (ResultParent) sel.getFirstElement();
- if (firstItem instanceof SingleResultNode)
- propertiesViewer.setInput(((SingleResultNode) firstItem)
- .getNode());
- else
- propertiesViewer.setInput(null);
- // update cache for Drag & drop
- // lastSelectedTargetElement = firstItem;
- // lastSelectedSourceElement = firstItem;
- // lastSelectedSourceElementParent = (ResultParent) firstItem
- // .getParent();
- // String pPath = "";
- // try {
- //
- // if (firstItem instanceof ParentNodeFolder)
- // pPath = ((ParentNodeFolder) firstItem).getNode()
- // .getPath();
- // else if (firstItem instanceof SingleResultNode)
- // pPath = ((SingleResultNode) firstItem).getNode()
- // .getPath();
- // } catch (RepositoryException e) {
- // throw new SlcException(
- // "Unexpected error while checking parent UI tree", e);
- // }
- // if ((pPath.startsWith(SlcJcrResultUtils
- // .getMyResultsBasePath(session))))
- // isActionUnderMyResult = true;
- // else
- // isActionUnderMyResult = false;
- }
- }
- }
-
- class ViewDoubleClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- processDoubleClick(evt);
- }
-
- }
-
- /* DEPENDENCY INJECTION */
- public void dispose() {
- // JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);
- JcrUtils.logoutQuietly(session);
- super.dispose();
- }
-
- public void setRepository(Repository repository) {
- this.repository = repository;
- }
-}
+++ /dev/null
-package org.argeo.slc.client.ui.wizards;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.ClientUiPlugin;
-import org.argeo.slc.client.ui.SlcUiConstants;
-import org.argeo.slc.jcr.SlcJcrResultUtils;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.ISharedImages;
-
-public class ConfirmOverwriteWizard extends Wizard {
-
- // Define widget here to simplify getters
- private Button overwriteBtn, renameBtn;
- private Text newNameTxt;
- private Label newNameLbl;
-
- // business object
- private String sourceNodeName;
- private Node targetParentNode;
-
- private String newName;
- private String parentRelPath;
- private boolean overwrite;
-
- public ConfirmOverwriteWizard(String sourceNodeName, Node targetParentNode) {
- setWindowTitle("Confirm overwrite or define a new name");
- this.sourceNodeName = sourceNodeName;
- this.targetParentNode = targetParentNode;
- }
-
- @Override
- public void addPages() {
- try {
- addPage(new MyPage());
- } catch (Exception e) {
- throw new SlcException("Cannot add page to wizard ", e);
- }
- getShell().setImage(
- ClientUiPlugin.getDefault().getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_LCL_LINKTO_HELP)
- .createImage());
- }
-
- // Expose info to the calling view
- public boolean overwrite() {
- return overwrite;
- }
-
- public String newName() {
- return newName;
- }
-
- @Override
- public boolean performFinish() {
- boolean doFinish = false;
-
- if (canFinish()) {
- if (overwriteBtn.getSelection())
- doFinish = MessageDialog.openConfirm(Display.getDefault()
- .getActiveShell(), "CAUTION", "All data contained in ["
- + (parentRelPath != null ? parentRelPath : "")
- + "/"+ sourceNodeName
- + "] are about to be definitively destroyed. \n "
- + "Are you sure you want to proceed ?");
- else
- doFinish = true;
- // cache values
- }
- if (doFinish) {
- overwrite = overwriteBtn.getSelection();
- newName = newNameTxt.getText();
- }
- return doFinish;
- }
-
- class MyPage extends WizardPage implements ModifyListener {
-
- public MyPage() {
- super("");
- String msg = "An object with same name (" + sourceNodeName
- + ") already exists at chosen target path";
-
- // Add target rel path to the message
- Session session;
- String relPath;
- try {
- session = targetParentNode.getSession();
- relPath = targetParentNode.getPath();
- String basePath = SlcJcrResultUtils
- .getMyResultsBasePath(session);
- if (relPath.startsWith(basePath))
- relPath = relPath.substring(basePath.length());
- // FIXME currently add the default base label
- parentRelPath = SlcUiConstants.DEFAULT_MY_RESULTS_FOLDER_LABEL
- + relPath;
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while defining "
- + "target parent node rel path", e);
- }
- msg = msg + (parentRelPath == null ? "." : ": \n" + parentRelPath);
-
- // Set Title
- setTitle(msg);
- }
-
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- // choose between overwrite and rename
- overwriteBtn = new Button(composite, SWT.RADIO);
- overwriteBtn.setText("Overwrite");
- GridData gd = new GridData();
- gd.horizontalIndent = 30;
- gd.horizontalSpan = 2;
- overwriteBtn.setLayoutData(gd);
- overwriteBtn.setSelection(true);
-
- renameBtn = new Button(composite, SWT.RADIO);
- renameBtn.setText("Rename");
- renameBtn.setSelection(false);
- renameBtn.setText("Rename");
- gd = new GridData();
- gd.horizontalIndent = 30;
- gd.horizontalSpan = 2;
- renameBtn.setLayoutData(gd);
-
- newNameLbl = new Label(composite, SWT.LEAD);
- newNameLbl.setText("New name");
- newNameLbl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
- false));
- newNameLbl.setEnabled(false);
-
- newNameTxt = new Text(composite, SWT.LEAD | SWT.BORDER);
- newNameTxt.setText(sourceNodeName);
- newNameTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
- false));
- if (newNameTxt != null)
- newNameTxt.addModifyListener(this);
- newNameTxt.setEnabled(false);
-
- SelectionAdapter sa = new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- updateSelection(overwriteBtn.getSelection());
- }
- };
- overwriteBtn.addSelectionListener(sa);
- renameBtn.addSelectionListener(sa);
-
- // Compulsory
- setControl(composite);
- }
-
- private void updateSelection(boolean overwrite) {
- newNameLbl.setEnabled(!overwrite);
- newNameTxt.setEnabled(!overwrite);
- if (overwrite)
- setPageComplete(true);
- else
- checkComplete();
- }
-
- protected String getTechName() {
- return newNameTxt.getText();
- }
-
- public void modifyText(ModifyEvent event) {
- checkComplete();
- }
-
- private void checkComplete() {
- try {
-
- String newName = newNameTxt.getText();
- if (newName == null || "".equals(newName.trim())) {
- setMessage("Name cannot be blank or empty",
- WizardPage.ERROR);
- setPageComplete(false);
- } else if (targetParentNode.hasNode(newName)) {
- setMessage("An object with the same name already exists.",
- WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- } catch (RepositoryException e) {
- throw new SlcException("Unexpected error while checking "
- + "children node with same name", e);
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.demo.ant</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-#Wed Jan 06 20:27:20 CET 2010
-eclipse.preferences.version=1
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="main" class="org.argeo.slc.core.execution.DefaultExecutionFlow">\r
- <property name="executables">\r
- <list>\r
- <bean class="org.argeo.slc.ant.AntRun">\r
- <property name="buildFile" value="osgibundle:/ant/hello/build.xml" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean class="org.argeo.slc.ant.AntFlowGenerator">\r
- <property name="antFiles">\r
- <list>\r
- <value>osgibundle:/ant/hello/build.xml\r
- </value>\r
- </list>\r
- </property>\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <import resource="classpath:org/argeo/slc/core/execution/simple.xml" />
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <beans:import resource="classpath:org/argeo/slc/osgi/execution.xml" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<project default="hello">
- <target name="hello">
- <echo message="Hello World!" />
- </target>
-</project>
\ No newline at end of file
+++ /dev/null
-bin.includes = META-INF/
+++ /dev/null
-<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>
- <artifactId>lib</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>lib</relativePath>
- </parent>
- <artifactId>org.argeo.slc.demo.ant</artifactId>
- <name>SLC Demo Ant</name>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.demo.basic</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-#Fri Mar 13 13:44:23 CET 2009
-eclipse.preferences.version=1
-pluginProject.equinox=false
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="basic.001" parent="basic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="testData1" value-ref="basic.001.testData" />\r
- <entry key="testData2">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata101" />\r
- <property name="reached" value="tata@{testedComponentId}" />\r
- </bean>\r
- </entry>\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-\r
- <bean id="basic.001.testData" class="org.argeo.slc.runtime.test.BasicTestData"\r
- scope="execution">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata100" />\r
- <property name="reached" value="tata@{testedComponentId}" />\r
- </bean>\r
-\r
- <bean id="basic.001.testData2" class="org.argeo.slc.core.test.context.DefaultContextTestData">\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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
-\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean id="basic.002" parent="basic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="testData1">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="toto" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
- </entry>\r
- <entry key="testData2">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
- </entry>\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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/lang http://www.springframework.org/schema/lang/spring-lang-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-0.12.xsd">\r
-\r
- <bean id="basic.spec" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testedComponentId">\r
- <bean parent="specAttr.primitive" p:value="100" p:isParameter="true"\r
- p:type="integer" />\r
- </entry>\r
- <entry key="testData1">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- <entry key="testData2">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="basic.flowTemplate" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="basic.spec" />\r
- <property name="path" value="/test/basic" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo" scope="execution">\r
- <property name="message" value="From basic @{testedComponentId}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- <bean parent="basic.testRun">\r
- <property name="testDefinition" ref="basic.testDef" />\r
- <property name="testData">\r
- <bean parent="parameterRef">\r
- <constructor-arg value="testData1" />\r
- </bean>\r
- </property>\r
- </bean>\r
- <bean parent="basic.testRun">\r
- <property name="testDefinition" ref="basic.testDef" />\r
- <property name="testData" ref="ref1" />\r
- </bean>\r
-\r
- <bean class="org.argeo.slc.jcr.JcrMetadataWriter">\r
- <property name="metadata">\r
- <map>\r
- <entry key="metadata1" value="value1" />\r
- <entry key="slc:metadata2" value="value2" />\r
- </map>\r
- </property>\r
- <property name="baseNode">\r
- <bean factory-bean="basic.testResult" factory-method="getNode" />\r
- </property>\r
- <flow:variable />\r
- </bean>\r
-\r
- <!-- Attachments -->\r
- <bean parent="task.echo">\r
- <property name="message" value="DATA" />\r
- <property name="writeTo" ref="basic.writeTo" />\r
- </bean>\r
-\r
- <bean parent="task.uploadAttachments">\r
- <property name="attachmentUploader" ref="attachmentUploader" />\r
- <property name="attachment">\r
- <bean parent="taskArg.attachment">\r
- <property name="name" value="myAttachment.txt" />\r
- </bean>\r
- </property>\r
- <property name="resource" ref="basic.writeTo" />\r
- <property name="attachTo">\r
- <list>\r
- <ref bean="basic.testResult" />\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean parent="task.closeTestResult" scope="execution">\r
- <property name="testResult" ref="basic.testResult" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="ref1" parent="parameterRef" scope="prototype">\r
- <constructor-arg value="testData2" />\r
- </bean>\r
-\r
- <bean id="basic.testData" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="tata" />\r
- </bean>\r
-\r
- <bean id="basic.testDef" class="org.argeo.slc.runtime.test.BasicTestDefinition"\r
- scope="prototype" />\r
-\r
- <bean id="basic.testResult" class="org.argeo.slc.jcr.JcrTestResult"\r
- init-method="init" destroy-method="destroy">\r
- <flow:variable />\r
- <property name="resultType" value="slc:diffResult" />\r
- <property name="attributes">\r
- <map>\r
- <entry key="testCase" value="@{slcVar.flow.name}" />\r
- </map>\r
- </property>\r
- <property name="repository" ref="repository" />\r
- </bean>\r
-\r
- <!-- <bean id="basic.testResult" parent="slcDefault.test.basicTreeTestResult" -->\r
- <!-- scope="execution"> -->\r
- <!-- <property name="listeners" ref="resultListeners" /> -->\r
- <!-- <property name="attributes"> -->\r
- <!-- <map> -->\r
- <!-- <entry key="testedComponentId" value="@{testedComponentId}" /> -->\r
- <!-- </map> -->\r
- <!-- </property> -->\r
- <!-- <aop:scoped-proxy /> -->\r
- <!-- </bean> -->\r
-\r
- <bean id="basic.testRun" class="org.argeo.slc.runtime.test.SimpleTestRun"\r
- abstract="true">\r
- <property name="testResult" ref="basic.testResult" />\r
- </bean>\r
-\r
- <bean id="basic.writeTo" factory-bean="basic.resourcesManager"\r
- factory-method="getWritableResource" scope="execution">\r
- <constructor-arg value="subdir/writeTo" />\r
- <aop:scoped-proxy />\r
- </bean>\r
-\r
- <bean id="basic.resourcesManager" parent="slcTemplate.fileResources">\r
- <property name="executionContext" ref="executionContext" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="canonic.001" parent="canonic.flowTemplate">\r
- <description>Canonic 001</description>\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="1" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="canonic.002" parent="canonic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="2" />\r
- <entry key="displayWithoutControl" value="102" />\r
- <entry key="displayWithControl" value="202" />\r
- <entry key="hide" value="202" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="canonic-ns.001" parent="canonic-ns.flowTemplate">\r
- <description>Canonic 001</description>\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="1" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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-0.12.xsd">\r
-\r
- <flow:flow id="canonic-ns.002" parent="canonic-ns.flowTemplate">\r
- <flow:arg name="parameterAtInstantiation" value="2" />\r
- <flow:arg name="displayWithoutControl" value="102" />\r
- <flow:arg name="displayWithControl" value="202" />\r
- <flow:arg name="hide" value="202" />\r
- </flow:flow>\r
-</beans>\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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/lang http://www.springframework.org/schema/lang/spring-lang-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-0.12.xsd">\r
-\r
- <flow:spec id="canonic-ns.spec">\r
- <flow:primitive name="parameterAtInstantiation"\r
- isParameter="true" type="integer" />\r
- <flow:primitive name="displayWithoutControl" value="100"\r
- isParameter="true" type="integer" isFrozen="true" />\r
- <flow:primitive name="displayWithControl" value="200"\r
- isParameter="true" type="integer" />\r
- <flow:primitive name="hide" value="300" isParameter="true"\r
- type="integer" isHidden="true" />\r
- <flow:ref name="refWithValue" targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- isParameter="true" ref="testDataNok" />\r
- <flow:ref name="refWithoutValue" targetClass="org.argeo.slc.runtime.test.BasicTestData" />\r
- <flow:ref name="refWithoutValueFrozen" targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- isParameter="true" isFrozen="true">\r
- <flow:value>\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="tata" />\r
- </bean>\r
- </flow:value>\r
- </flow:ref>\r
- </flow:spec>\r
-\r
- <flow:flow id="canonic-ns.flowTemplate" abstract="true"\r
- spec="canonic-ns.spec">\r
- <bean parent="task.echo"\r
- p:message="Canonical: displayWithControl=@{displayWithControl}, displayWithoutControl=@{displayWithoutControl}, hide=@{hide}"\r
- scope="execution">\r
- <aop:scoped-proxy />\r
- </bean>\r
- </flow:flow>\r
-\r
- <bean id="testDataOk" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="tata" />\r
- </bean>\r
-\r
- <bean id="testDataNok" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="canonic.spec" parent="slcTemplate.simpleSpec">\r
- <description>Covers various combinations of specs</description>\r
- <property name="attributes">\r
- <map>\r
- <entry key="parameterAtInstantiation">\r
- <bean parent="specAttr.primitive" p:isParameter="true" p:type="integer" />\r
- </entry>\r
- <entry key="displayWithoutControl">\r
- <bean parent="specAttr.primitive" p:value="100" p:isParameter="false"\r
- p:isFrozen="true" p:type="integer" />\r
- </entry>\r
- <entry key="displayWithControl">\r
- <bean parent="specAttr.primitive" p:value="200" p:isParameter="false"\r
- p:isFrozen="false" p:type="integer" />\r
- </entry>\r
- <entry key="hide">\r
- <bean parent="specAttr.primitive" p:value="300" p:isParameter="true"\r
- p:isFrozen="false" p:isHidden="true" p:type="integer" />\r
- </entry>\r
- <entry key="refWithValue">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:value-ref="testDataNok" p:isParameter="true" p:isFrozen="false" />\r
- </entry>\r
- <entry key="refWithoutValue">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="false" p:isFrozen="false" />\r
- </entry>\r
- <entry key="refWithoutValueFrozen">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true">\r
- <property name="value">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="tata" />\r
- </bean>\r
- </property>\r
- </bean>\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="canonic.flowTemplate" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="canonic.spec" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"\r
- p:message="Canonical: displayWithControl=@{displayWithControl}, displayWithoutControl=@{displayWithoutControl}, hide=@{hide}"\r
- scope="execution">\r
- <aop:scoped-proxy />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="testDataOk" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="tata" />\r
- </bean>\r
-\r
- <bean id="testDataNok" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <import resource="classpath:org/argeo/slc/core/execution/spring.xml" />
-
- <import resource="classpath:/org/argeo/slc/core/test/spring.xml" />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <bean id="main" parent="slcTemplate.simpleFlow">\r
- <description>The Main Flow</description>\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="660" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <ref local="echo1" />\r
- <ref bean="basic.001" />\r
- <ref bean="basic.001" />\r
- <ref bean="basic.002" />\r
- <ref bean="canonic.001" />\r
- <ref bean="canonic.002" />\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="noArg" parent="slcTemplate.simpleFlow">\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="No arg!" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="echo1" parent="task.echo" scope="execution">\r
- <property name="message" value="From main! @{testKey}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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-0.12.xsd">\r
-\r
- <!-- Flow definition is simplified thanks to the 'flow:flow' element -->\r
- <flow:flow name="/namespace/flow" >\r
- <bean p:message="TEST in flow" class="org.argeo.slc.core.execution.tasks.Echo" />\r
- <ref bean="referencedRunnable" />\r
- </flow:flow>\r
-\r
- <bean id="referencedRunnable" p:message="TEST in referenced Runnable"\r
- class="org.argeo.slc.core.execution.tasks.Echo" />\r
-\r
- <!--\r
- Standalone beans implementing Runnable can be exposed as flows via the\r
- 'flow:as-flow' attribute\r
- -->\r
- <bean id="standaloneRunnable" flow:as-flow="implicitFlow"\r
- p:message="TEST in implicit flow" class="org.argeo.slc.core.execution.tasks.Echo" />\r
-\r
- <!-- Specs definition is also simplified -->\r
- <flow:spec id="namespaceSpec">\r
- <flow:primitive name="primitive" value="100"\r
- isParameter="true" type="integer" />\r
- </flow:spec>\r
-\r
- <flow:flow name="/namespace/flowSpec" spec="namespaceSpec">\r
- <bean p:message="TEST in flow @{primitive}" class="org.argeo.slc.core.execution.tasks.Echo"\r
- scope="execution">\r
- <aop:scoped-proxy />\r
- </bean>\r
- <ref bean="referencedRunnable" />\r
- </flow:flow>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <beans:import resource="classpath:org/argeo/slc/osgi/execution.xml" />\r
-\r
- <reference id="attachmentUploader"\r
- interface="org.argeo.slc.core.attachment.AttachmentUploader"\r
- cardinality="0..1" />\r
-\r
- <!-- REFERENCES -->\r
- <reference id="repository" interface="javax.jcr.Repository"\r
- filter="(cn=slc)" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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-0.12.xsd">\r
-\r
- <!-- Basic echo, should work on all OSs -->\r
- <flow:flow name="os/systemCall">\r
- <bean p:cmd="echo Hello World!" class="org.argeo.slc.core.execution.tasks.SystemCall" />\r
- </flow:flow>\r
-\r
- <!-- Must disable requiretty in sudoers file -->\r
- <flow:flow name="os/sudo">\r
- <bean p:cmd="sudo id" class="org.argeo.slc.core.execution.tasks.SystemCall">\r
- <property name="environmentVariables">\r
- <map>\r
- <entry key="SUDO_ASKPASS" value="/usr/libexec/openssh/gnome-ssh-askpass" />\r
- </map>\r
- </property>\r
- </bean>\r
- </flow:flow>\r
-\r
- <!-- SSH -->\r
- <flow:flow name="os/ssh">\r
- <bean p:cmd="ls /etc" class="org.argeo.slc.core.execution.tasks.SystemCall">\r
- <property name="executor" ref="sshExecutor" />\r
- </bean>\r
- </flow:flow>\r
-\r
- <bean name="sshExecutor" class="org.argeo.slc.jsch.JschExecutor">\r
- <property name="sshTarget">\r
- <bean p:host="localhost" p:port="22" p:user="${user.name}"\r
- p:localPrivateKey="${user.home}/.ssh/id_rsa" class="org.argeo.slc.jsch.SshTarget">\r
- <property name="userInfo">\r
- <bean class="org.argeo.slc.jsch.SwingUserInfo" />\r
- </property>\r
- </bean>\r
- </property>\r
- </bean>\r
-\r
-\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-bin.includes = .settings/,\
- .project,\
- META-INF/,\
- conf/,\
- pom.xml,\
- .svn/
+++ /dev/null
-<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>
- <artifactId>lib</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>lib</relativePath>
- </parent>
- <artifactId>org.argeo.slc.demo.basic</artifactId>
- <name>SLC Demo Basic</name>
-<!-- <build> -->
-<!-- <plugins> -->
-<!-- <plugin> -->
-<!-- <groupId>org.apache.felix</groupId> -->
-<!-- <artifactId>maven-bundle-plugin</artifactId> -->
-<!-- <configuration> -->
-<!-- <instructions> -->
-<!-- <SLC-ExecutionModule>default</SLC-ExecutionModule> -->
-<!-- <Import-Package> -->
-<!-- *, -->
-<!-- org.argeo.slc.core.structure.tree, -->
-
-<!-- net.sf.cglib.core, -->
-<!-- net.sf.cglib.proxy, -->
-<!-- net.sf.cglib.reflect, -->
-<!-- org.aopalliance.aop, -->
-<!-- org.argeo.slc.core.execution, -->
-<!-- org.argeo.slc.core.execution.tasks, -->
-<!-- org.argeo.slc.execution, -->
-<!-- org.argeo.slc.osgi, -->
-<!-- org.springframework.aop, -->
-<!-- org.springframework.aop.framework, -->
-<!-- org.springframework.aop.scope, -->
-<!-- org.springframework.beans.factory.config, -->
-<!-- org.springframework.core.io, -->
-<!-- </Import-Package> -->
-<!-- </instructions> -->
-<!-- </configuration> -->
-<!-- </plugin> -->
-<!-- </plugins> -->
-<!-- </build> -->
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.demo.minimal</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-#Wed Jan 06 20:27:49 CET 2010
-eclipse.preferences.version=1
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <import resource="classpath:org/argeo/slc/core/execution/simple.xml" />
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\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"\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
- >\r
-\r
- <!-- Hello world without namespace (for reference, do not use) -->\r
- <bean name="HelloWorld/Raw" class="org.argeo.slc.core.execution.DefaultExecutionFlow">\r
- <description>Print Hello World!</description>\r
- <property name="executables">\r
- <list>\r
- <bean p:message="Hello World!" class="org.argeo.slc.core.execution.tasks.Echo" />\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean name="HelloWorld/RawWithVar" class="org.argeo.slc.core.execution.DefaultExecutionFlow">\r
- <description>Print Hello World! with variable</description>\r
- <constructor-arg>\r
- <bean class="org.argeo.slc.core.execution.DefaultExecutionSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean p:value="777"\r
- class="org.argeo.slc.primitive.PrimitiveSpecAttribute" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <bean p:message="Hello World! @{testKey}" class="org.argeo.slc.core.execution.tasks.Echo"\r
- scope="execution">\r
- <aop:scoped-proxy proxy-target-class="false" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans xmlns:flow="http://www.argeo.org/schema/slc-flow" 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
- xsi:schemaLocation="\r
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
- http://www.argeo.org/schema/slc-flow http://www.argeo.org/schema/slc-flow-1.2.xsd">\r
-\r
- <!-- Hello world -->\r
- <flow:flow name="hello">\r
- <description>Print Hello World!</description>\r
- <bean p:message="Hello World!" class="org.argeo.slc.core.execution.tasks.Echo" />\r
- </flow:flow>\r
-\r
-\r
- <flow:flow name="HelloWorld/WithVar">\r
- <description>Print Hello World! with variable</description>\r
- <flow:spec>\r
- <flow:primitive name="testKey" value="777" />\r
- </flow:spec>\r
- <bean p:message="Hello World! @{testKey}" class="org.argeo.slc.core.execution.tasks.Echo">\r
- <flow:variable proxy-target-class="false" />\r
- </bean>\r
- </flow:flow>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <beans:import resource="classpath:org/argeo/slc/osgi/execution.xml" />\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-#Import-Package: org.argeo.slc.runtime,\
-#*
\ No newline at end of file
+++ /dev/null
-bin.includes = META-INF/
+++ /dev/null
-<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>
- <artifactId>lib</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>lib</relativePath>
- </parent>
- <artifactId>org.argeo.slc.demo.minimal</artifactId>
- <name>SLC Demo Minimal</name>
-</project>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>>>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
+++ /dev/null
-/target/
-/.slc/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.launcher</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-Main-Class: org.argeo.slc.cli.SlcMain
\ No newline at end of file
+++ /dev/null
-source.. = src/main/java/,\
- src/main/resources/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.launcher</artifactId>
- <packaging>jar</packaging>
- <name>SLC Launcher</name>
- <build>
- <plugins>
- <!-- <plugin> -->
- <!-- <groupId>org.apache.maven.plugins</groupId> -->
- <!-- <artifactId>maven-assembly-plugin</artifactId> -->
- <!-- <configuration> -->
- <!-- <descriptors> -->
- <!-- <descriptor>assembly/base.xml</descriptor> -->
- <!-- </descriptors> -->
- <!-- </configuration> -->
- <!-- <executions> -->
- <!-- <execution> -->
- <!-- <id>assembly-base</id> -->
- <!-- <phase>package</phase> -->
- <!-- <goals> -->
- <!-- <goal>single</goal> -->
- <!-- </goals> -->
- <!-- </execution> -->
- <!-- </executions> -->
- <!-- </plugin> -->
- <!-- <plugin> -->
- <!-- <groupId>org.apache.felix</groupId> -->
- <!-- <artifactId>maven-bundle-plugin</artifactId> -->
- <!-- <configuration> -->
- <!-- <instructions> -->
- <!-- <Main-Class>org.argeo.slc.cli.SlcMain</Main-Class> -->
- <!-- </instructions> -->
- <!-- </configuration> -->
- <!-- </plugin> -->
- <!-- <plugin> -->
- <!-- <artifactId>maven-resources-plugin</artifactId> -->
- <!-- <executions> -->
- <!-- <execution> -->
- <!-- <phase>validate</phase> -->
- <!-- <goals> -->
- <!-- <goal>copy-resources</goal> -->
- <!-- </goals> -->
- <!-- <configuration> -->
- <!-- <outputDirectory>${basedir}/target/base</outputDirectory> -->
- <!-- <resources> -->
- <!-- <resource> -->
- <!-- <directory>base</directory> -->
- <!-- <filtering>true</filtering> -->
- <!-- </resource> -->
- <!-- </resources> -->
- <!-- </configuration> -->
- <!-- </execution> -->
- <!-- </executions> -->
- <!-- </plugin> -->
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.init</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.cli;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.UUID;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-
-import org.argeo.init.osgi.OsgiBoot;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.launch.Framework;
-import org.osgi.framework.launch.FrameworkFactory;
-
-/** Configures an SLC runtime and runs a process. */
-public class SlcMain implements PrivilegedAction<String> {
- public final static String NIX = "NIX";
- public final static String WINDOWS = "WINDOWS";
- public final static String SOLARIS = "SOLARIS";
-
- public final static String os;
- public final static String slcDirName = ".slc";
- final static File homeDir = new File(System.getProperty("user.home"));
-
- static {
- String osName = System.getProperty("os.name");
- if (osName.startsWith("Win"))
- os = WINDOWS;
- else if (osName.startsWith("Solaris"))
- os = SOLARIS;
- else
- os = NIX;
- }
-
- private Long timeout = 30 * 1000l;
- private final String[] args;
- private final File confDir;
- private final File dataDir;
- private final File modulesDir;
-
- private final List<String> bundlesToStart = new ArrayList<String>();
-
- public SlcMain(String[] args, File confDir, File dataDir, File modulesDir) {
- this.args = args;
- this.confDir = confDir;
- this.dataDir = dataDir;
- this.modulesDir = modulesDir;
-
- bundlesToStart.add("org.eclipse.equinox.cm");
- bundlesToStart.add("org.argeo.cms");
- bundlesToStart.add("org.eclipse.gemini.blueprint.extender");
- bundlesToStart.add("org.argeo.slc.agent");
- bundlesToStart.add("org.argeo.slc.agent.jcr");
-
- // bundlesToStart.add("org.springframework.osgi.extender");
- // bundlesToStart.add("org.argeo.node.repo.jackrabbit");
- // bundlesToStart.add("org.argeo.security.dao.os");
- // bundlesToStart.add("org.argeo.slc.node.jackrabbit");
- // bundlesToStart.add("org.argeo.slc.agent");
- // bundlesToStart.add("org.argeo.slc.agent.jcr");
- // if (args.length == 0)
- // bundlesToStart.add("org.argeo.slc.support.equinox");
- // bundlesToStart.add("org.argeo.slc.agent.cli");
- }
-
- public String run() {
- long begin = System.currentTimeMillis();
-
- Framework framework = null;
- try {
- info("## Date : " + new Date());
- info("## Data : " + dataDir.getCanonicalPath());
-
- // Start Equinox
- ServiceLoader<FrameworkFactory> ff = ServiceLoader.load(FrameworkFactory.class);
- FrameworkFactory frameworkFactory = ff.iterator().next();
- Map<String, String> configuration = new HashMap<String, String>();
- configuration.put("osgi.configuration.area", confDir.getCanonicalPath());
- configuration.put("osgi.instance.area", dataDir.getCanonicalPath());
- // Do clean
- configuration.put("osgi.clean", "true");
- if (args.length == 0) {
- configuration.put("osgi.console", "");
- }
-
- // Spring configs currently require System properties
- System.getProperties().putAll(configuration);
-
- framework = frameworkFactory.newFramework(configuration);
- framework.start();
- BundleContext bundleContext = framework.getBundleContext();
-
- // OSGi bootstrap
- OsgiBoot osgiBoot = new OsgiBoot(bundleContext);
-
- // working copy modules
- if (modulesDir.exists())
- osgiBoot.installUrls(osgiBoot.getBundlesUrls(modulesDir.getCanonicalPath() + ";in=*;ex=.gitignore"));
-
- // system modules
- if (System.getProperty(OsgiBoot.PROP_ARGEO_OSGI_BUNDLES) != null)
- osgiBoot.installUrls(osgiBoot.getBundlesUrls(System.getProperty(OsgiBoot.PROP_ARGEO_OSGI_BUNDLES)));
- else
- osgiBoot.installUrls(osgiBoot.getBundlesUrls(System.getProperty("user.home") + "/.slc/modules/;in=**"));
-
- // Start runtime
- osgiBoot.startBundles(bundlesToStart);
-
- // Find SLC Agent
- ServiceReference sr = null;
- while (sr == null) {
- sr = bundleContext.getServiceReference("org.argeo.slc.execution.SlcAgentCli");
- if (System.currentTimeMillis() - begin > timeout)
- throw new RuntimeException("Cannot find SLC agent CLI");
- Thread.sleep(100);
- }
- Object agentCli = bundleContext.getService(sr);
-
- // Initialization completed
- long duration = System.currentTimeMillis() - begin;
- info("[[ Initialized in " + (duration / 1000) + "s " + (duration % 1000) + "ms ]]");
-
- if (args.length == 0)
- return null;// console mode
-
- // Subject.doAs(Subject.getSubject(AccessController.getContext()),
- // new AgentCliCall(agentCli));
- Class<?>[] parameterTypes = { String[].class };
- Method method = agentCli.getClass().getMethod("process", parameterTypes);
- Object[] methodArgs = { args };
- Object ret = method.invoke(agentCli, methodArgs);
-
- // Shutdown OSGi runtime
- framework.stop();
- framework.waitForStop(60 * 1000);
-
- return ret.toString();
- } catch (Exception e) {
- // Shutdown OSGi runtime
- if (framework != null)
- try {
- framework.stop();
- framework.waitForStop(15 * 1000);
- } catch (Exception silent) {
- }
- throw new RuntimeException("Cannot run SLC command line", e);
- } finally {
-
- }
- }
-
- public static void main(String[] args) {
- try {
- // Prepare directories
- File executionDir = new File(System.getProperty("user.dir"));
- File slcDir;
- Boolean isTransient = false;
- if (isTransient) {
- File tempDir = new File(System.getProperty("java.io.tmpdir") + "/" + System.getProperty("user.name"));
- slcDir = new File(tempDir, "slc-" + UUID.randomUUID().toString());
- slcDir.mkdirs();
- System.setProperty("argeo.node.repo.configuration", "osgibundle:repository-memory.xml");
- } else {
- slcDir = findSlcDir(executionDir);
- if (slcDir == null) {
- slcDir = new File(executionDir, slcDirName);
- slcDir.mkdirs();
- info("## Creating an SLC node at " + slcDir + " ...");
- }
- }
-
- File dataDir = new File(slcDir, "data");
- if (!dataDir.exists())
- dataDir.mkdirs();
-
- File confDir = new File(slcDir, "conf");
- if (!confDir.exists())
- confDir.mkdirs();
-
- File modulesDir = new File(slcDir, "modules");
-
- // JAAS
- // File jaasFile = new File(confDir, "jaas.config");
- // if (!jaasFile.exists())
- // copyResource("/org/argeo/slc/cli/jaas.config", jaasFile);
- // System.setProperty("java.security.auth.login.config",
- // jaasFile.getCanonicalPath());
-
- // log4j
- File log4jFile = new File(confDir, "log4j.properties");
- if (!log4jFile.exists())
- copyResource("/org/argeo/slc/cli/log4j.properties", log4jFile);
- System.setProperty("log4j.configuration", "file://" + log4jFile.getCanonicalPath());
- // Run as a privileged action
- // LoginContext lc = new LoginContext(os);
- // lc.login();
- //
- // Subject subject =
- // Subject.getSubject(AccessController.getContext());
- // Subject.doAs(subject, new SlcMain(args, confDir, dataDir,
- // modulesDir));
- SlcMain slcMain = new SlcMain(args, confDir, dataDir, modulesDir);
- slcMain.run();
- if (args.length != 0)
- System.exit(0);
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- /**
- * Recursively look in parent directories for a directory named
- * {@link #slcDirName}
- */
- protected static File findSlcDir(File currentDir) {
- File slcDir = new File(currentDir, slcDirName);
- // covers the use case of running from the home directory
- if (slcDir.exists() && slcDir.isDirectory())
- return slcDir;
- File parentDir = currentDir.getParentFile();
- if (parentDir == null)
- return null;
- try {
- // ~/.slc reserved for agent
- if (parentDir.getCanonicalPath().equals(homeDir.getCanonicalPath()))
- return null;
- } catch (IOException e) {
- throw new RuntimeException("Cannot check home directory", e);
- }
- return findSlcDir(parentDir);
- }
-
- protected static void copyResource(String resource, File targetFile) {
- InputStream input = null;
- FileOutputStream output = null;
- try {
- input = SlcMain.class.getResourceAsStream(resource);
- output = new FileOutputStream(targetFile);
- byte[] buf = new byte[8192];
- while (true) {
- int length = input.read(buf);
- if (length < 0)
- break;
- output.write(buf, 0, length);
- }
- } catch (Exception e) {
- throw new RuntimeException("Cannot write " + resource + " file to " + targetFile, e);
- } finally {
- try {
- input.close();
- } catch (Exception ignore) {
- }
- try {
- output.close();
- } catch (Exception ignore) {
- }
- }
-
- }
-
- protected static void info(Object msg) {
- System.out.println(msg);
- }
-
- protected static void err(Object msg) {
- System.err.println(msg);
- }
-
- protected static void debug(Object msg) {
- System.out.println(msg);
- }
-
-}
-
-// private String bundlesToInstall = System.getProperty("user.home")
-// +
-// "/dev/src/slc/dep/org.argeo.slc.dep.minimal/target/dependency;in=*.jar,"
-// + System.getProperty("user.home")
-// + "/dev/src/slc/demo/modules;in=*;ex=pom.xml;ex=.svn";
-
-// ServiceTracker agentTracker = new ServiceTracker(bundleContext,
-// "org.argeo.slc.execution.SlcAgentCli", null);
-// agentTracker.open();
-// final Object agentCli = agentTracker.waitForService(30 * 1000);
-// if (agentCli == null)
-// throw new RuntimeException("Cannot find SLC agent CLI");
-
-// protected class AgentCliCall implements PrivilegedAction<String> {
-// private final Object agentCli;
-//
-// public AgentCliCall(Object agentCli) {
-// super();
-// this.agentCli = agentCli;
-// }
-//
-// public String run() {
-// try {
-// Class<?>[] parameterTypes = { String[].class };
-// Method method = agentCli.getClass().getMethod("process",
-// parameterTypes);
-// Object[] methodArgs = { args };
-// Object ret = method.invoke(agentCli, methodArgs);
-// return ret.toString();
-// } catch (Exception e) {
-// throw new RuntimeException("Cannot run "
-// + Arrays.toString(args) + " on " + agentCli, e);
-// }
-// }
-//
-// }
+++ /dev/null
-NIX {
- com.sun.security.auth.module.UnixLoginModule required;
-};
-
-WINDOWS {
- com.sun.security.auth.module.NTLoginModule required;
-};
+++ /dev/null
-log4j.rootLogger=WARN, console
-#log4j.rootLogger=DEBUG, development
-
-## Levels
-log4j.logger.org.argeo=INFO
-
-log4j.logger.org.apache.jackrabbit.core.query.lucene=ERROR
-log4j.logger.org.apache.jackrabbit.core.config.ConfigurationErrorHandler=ERROR
-log4j.logger.org.apache.jackrabbit.core.util.db.DbUtility=FATAL
-
-## Appenders
-# default appender
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss,SSS} %m%n
-
-# development appender
-log4j.appender.development=org.apache.log4j.ConsoleAppender
-log4j.appender.development.layout=org.apache.log4j.PatternLayout
-log4j.appender.development.layout.ConversionPattern=%d{HH:mm:ss,SSS} %5p %m [%16.16t] %c%n
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.server.repo</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-#Sun Feb 06 14:17:19 CET 2011
-eclipse.preferences.version=1
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <!-- JCR repositories -->\r
- <!-- <bean id="javaRepository" parent="template.jcrRepository"> -->\r
- <!-- <property name="homeDirectory" value="${slc.repo.jcr.reposBase}/java" \r
- /> -->\r
- <!-- <property name="configuration" value="${slc.repo.jcr.configuration.java}" \r
- /> -->\r
- <!-- </bean> -->\r
- <!-- <bean id="distRepository" parent="template.jcrRepository"> -->\r
- <!-- <property name="homeDirectory" value="${slc.repo.jcr.reposBase}/dist" \r
- /> -->\r
- <!-- <property name="configuration" value="${slc.repo.jcr.configuration.dist}" \r
- /> -->\r
- <!-- </bean> -->\r
- <!-- <bean id="rpmRepository" parent="template.jcrRepository"> -->\r
- <!-- <property name="homeDirectory" value="${slc.repo.jcr.reposBase}/rpm" \r
- /> -->\r
- <!-- <property name="configuration" value="${slc.repo.jcr.configuration.rpm}" \r
- /> -->\r
- <!-- </bean> -->\r
- <!-- <bean id="docsRepository" parent="template.jcrRepository"> -->\r
- <!-- <property name="homeDirectory" value="${slc.repo.jcr.reposBase}/docs" \r
- /> -->\r
- <!-- <property name="configuration" value="${slc.repo.jcr.configuration.docs}" \r
- /> -->\r
- <!-- </bean> -->\r
-\r
- <!-- JCR authorizations -->\r
- <bean parent="template.jcrAuthorizations">\r
- <property name="repository" ref="javaRepository" />\r
- </bean>\r
- <bean parent="template.jcrAuthorizations">\r
- <property name="repository" ref="distRepository" />\r
- </bean>\r
- <bean parent="template.jcrAuthorizations">\r
- <property name="repository" ref="rpmRepository" />\r
- </bean>\r
- <bean parent="template.jcrAuthorizations">\r
- <property name="repository" ref="docsRepository" />\r
- </bean>\r
-\r
- <!-- Templates -->\r
- <!-- <bean id="template.jcrRepository" abstract="true" -->\r
- <!-- class="org.argeo.jackrabbit.JackrabbitContainer" init-method="init" -->\r
- <!-- destroy-method="destroy"> -->\r
- <!-- <property name="variables" value="osgibundle:/repo.properties" /> -->\r
- <!-- <property name="cndFiles"> -->\r
- <!-- <list> -->\r
- <!-- <value>/org/argeo/jcr/argeo.cnd</value> -->\r
- <!-- <value>/org/argeo/slc/jcr/slc.cnd</value> -->\r
- <!-- <value>/org/argeo/slc/repo/repo.cnd</value> -->\r
- <!-- </list> -->\r
- <!-- </property> -->\r
- <!-- <property name="bundleContext" ref="bundleContext" /> -->\r
- <!-- <property name="forceCndImport" value="${slc.repo.jcr.forceCndImport}" \r
- /> -->\r
- <!-- </bean> -->\r
-\r
- <bean id="template.jcrAuthorizations" abstract="true"\r
- class="org.argeo.jcr.JcrAuthorizations" init-method="run">\r
- <property name="principalPrivileges">\r
- <map>\r
- <entry key="jcr:all" value="cn=org.argeo.slc.user,ou=roles,ou=node" />\r
- </map>\r
- </property>\r
- <property name="workspace" value="*" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<beans:beans xmlns="http://www.springframework.org/schema/osgi"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"\r
- xmlns:security="http://www.springframework.org/schema/security"\r
- xsi:schemaLocation="http://www.springframework.org/schema/osgi \r
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd\r
- http://www.springframework.org/schema/beans \r
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">\r
-\r
- <!-- REFERENCES -->\r
- <reference id="userAdmin" interface="org.osgi.service.useradmin.UserAdmin" />\r
- <reference id="userTransaction" interface="org.argeo.osgi.transaction.WorkTransaction" />\r
-\r
-<!-- <set id="defaultRpmRepositories" cardinality="0..N" -->\r
-<!-- interface="org.argeo.slc.rpmfactory.RpmRepository" /> -->\r
-\r
- <reference id="javaRepository" interface="javax.jcr.Repository"\r
- filter="(cn=java)" />\r
- <reference id="distRepository" interface="javax.jcr.Repository"\r
- filter="(cn=dist)" />\r
- <reference id="rpmRepository" interface="javax.jcr.Repository"\r
- filter="(cn=rpm)" />\r
- <reference id="docsRepository" interface="javax.jcr.Repository"\r
- filter="(cn=docs)" />\r
-\r
- <!-- SERVICES -->\r
- <service ref="slcRepoManager" interface="org.argeo.slc.repo.SlcRepoManager" />\r
-\r
-<!-- <service ref="mavenProxyService" interface="org.argeo.slc.repo.MavenProxyService" /> -->\r
-<!-- <service ref="rpmProxyService" interface="org.argeo.slc.rpmfactory.RpmProxyService" /> -->\r
-\r
- <!-- LABEL -->\r
- <beans:bean class="org.argeo.cms.spring.osgi.OsgiModuleLabel">\r
- <beans:property name="bundleContext" ref="bundleContext" />\r
- </beans:bean>\r
-\r
- <!-- ROLES -->\r
- <beans:bean id="ROLE_SLC"\r
- class="org.argeo.cms.spring.SimpleRoleRegistration" init-method="run">\r
- <beans:property name="role" value="org.argeo.slc.user" />\r
- <beans:property name="userAdmin" ref="userAdmin" />\r
- <beans:property name="userTransaction" ref="userTransaction" />\r
- </beans:bean>\r
-\r
- <beans:bean\r
- class="org.argeo.cms.spring.AuthenticatedApplicationContextInitialization">\r
- </beans:bean>\r
-</beans:beans>\r
-\r
-<!-- <reference id="mavenRepositorySystem" interface="org.sonatype.aether.RepositorySystem" -->\r
-<!-- filter="(aether.repositorySystemType=maven)" /> -->\r
-<!-- <reference id="mavenRepositorySystemSession" interface="org.sonatype.aether.RepositorySystemSession" -->\r
-<!-- filter="(aether.repositorySystemType=maven)" /> -->\r
-\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:util="http://www.springframework.org/schema/util"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
- ">
-
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
- <property name="locations">
- <value>osgibundle:repo.properties</value>
- </property>
- </bean>
-
- <bean id="slcRepoManager" class="org.argeo.slc.repo.core.SlcRepoManagerImpl"
- init-method="init" destroy-method="destroy">
- <property name="javaRepoManager" ref="javaRepoManager" />
- </bean>
-
- <!-- Java -->
- <bean id="javaRepoManager" class="org.argeo.slc.repo.core.JavaRepoManagerImpl"
- init-method="init" destroy-method="destroy" depends-on="ROLE_SLC">
- <property name="nodeIndexers">
- <list>
- <bean class="org.argeo.slc.repo.ModularDistributionIndexer" />
- <bean class="org.argeo.slc.repo.JarFileIndexer" />
- <bean class="org.argeo.slc.repo.ArtifactIndexer" />
- <bean class="org.argeo.slc.repo.PdeSourcesIndexer" />
- </list>
- </property>
- <property name="jcrRepository" ref="javaRepository" />
- </bean>
-
- <!-- <bean id="mavenProxyService" class="org.argeo.slc.repo.maven.MavenProxyServiceImpl" -->
- <!-- init-method="init" destroy-method="destroy" depends-on="ROLE_SLC"> -->
- <!-- <property name="jcrRepository" ref="javaRepository" /> -->
- <!-- <property name="proxyWorkspace" value="${slc.repo.jcr.proxyWorkspace}"
- /> -->
- <!-- <property name="defaultRepositories" ref="defaultMavenRepositories"
- /> -->
- <!-- </bean> -->
-
- <!-- RPM -->
-<!-- <bean id="rpmRepoManager" class="org.argeo.slc.repo.core.RpmRepoManagerImpl" -->
-<!-- init-method="init" destroy-method="destroy" depends-on="ROLE_SLC"> -->
-<!-- <property name="nodeIndexers"> -->
-<!-- <list> -->
-<!-- <bean class="org.argeo.slc.rpmfactory.core.RpmIndexer" /> -->
-<!-- </list> -->
-<!-- </property> -->
-<!-- <property name="jcrRepository" ref="rpmRepository" /> -->
-<!-- </bean> -->
-
- <!-- <bean id="rpmProxyService" class="org.argeo.slc.rpmfactory.core.RpmProxyServiceImpl" -->
- <!-- init-method="init" destroy-method="destroy" depends-on="ROLE_SLC"> -->
- <!-- <property name="jcrRepository" ref="rpmRepository" /> -->
- <!-- <property name="proxyWorkspace" value="${slc.repo.jcr.proxyWorkspace}"
- /> -->
- <!-- <property name="defaultRepositories" ref="defaultRpmRepositories" /> -->
- <!-- </bean> -->
-
-</beans>
\ No newline at end of file
+++ /dev/null
-Import-Package: org.argeo.jcr,\
-org.argeo.security.jackrabbit,\
-org.argeo.slc.jcr,\
-org.argeo.slc.repo,\
-org.h2;resolution:=optional,\
-org.postgresql;resolution:=optional,\
-org.osgi.*;version=0.0.0,\
-*
+++ /dev/null
-bin.includes = META-INF/,\
- repo.properties,\
- repository-h2.xml
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.server.repo</artifactId>
- <name>SLC Repo</name>
-</project>
\ No newline at end of file
+++ /dev/null
-slc.repo.jcr.reposBase=${osgi.instance.area}/repos
-slc.repo.jcr.forceCndImport=true
-slc.repo.jcr.proxyWorkspace=proxy
-
-slc.repo.jcr.configuration.java=osgibundle:repository-localfs.xml
-slc.repo.jcr.configuration.dist=osgibundle:repository-localfs.xml
-slc.repo.jcr.configuration.rpm=osgibundle:repository-localfs.xml
-slc.repo.jcr.configuration.docs=osgibundle:repository-localfs.xml
-argeo.node.repo.defaultWorkspace=main
-argeo.node.repo.bundleCacheMB=8
-argeo.node.repo.extractorPoolSize=0
-argeo.node.repo.searchCacheSize=1000
-argeo.node.repo.maxVolatileIndexSize=1048576
-
-slc.repo.jcr.dbuser=sa
-slc.repo.jcr.dbpassword=
-slc.repo.jcr.maxPoolSize=10
-
-# Postgres
-slc.repo.jcr.dburl.java=jdbc:postgresql://localhost/slc_repo_java
-slc.repo.jcr.dburl.dist=jdbc:postgresql://localhost/slc_repo_dist
-slc.repo.jcr.dburl.rpm=jdbc:postgresql://localhost/slc_repo_rpm
-slc.repo.jcr.dburl.docs=jdbc:postgresql://localhost/slc_repo_docs
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src"/>
- <classpathentry kind="src" path="ext/test"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-/bin/
-/target/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.spring</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-http\://www.argeo.org/schema/slc-flow=org.argeo.slc.core.execution.xml.FlowNamespaceHandler
\ No newline at end of file
+++ /dev/null
-http\://www.argeo.org/schema/slc-flow.xsd=org/argeo/slc/core/execution/xml/slc-flow-1.2.xsd
-http\://www.argeo.org/schema/slc-flow-1.2.xsd=org/argeo/slc/core/execution/xml/slc-flow-1.2.xsd
-http\://www.argeo.org/schema/slc-flow-0.12.xsd=org/argeo/slc/core/execution/xml/slc-flow-0.12.xsd
+++ /dev/null
-Import-Package: javax.jcr.nodetype,\
-javax.jcr.security,\
-aQute.bnd.osgi,\
-org.apache.tools.ant.*;resolution:="optional",\
-junit.framework;resolution:="optional",\
-org.osgi.*;version=0.0.0,\
-org.argeo.cms.auth,\
-*
-
-Export-Package: org.argeo.slc.core.test,\
-*
\ No newline at end of file
+++ /dev/null
-additional.bundles = org.springframework.context,\
- org.slf4j.api,\
- org.springframework.aop,\
- org.springframework.aspects,\
- org.springframework.beans,\
- org.springframework.context.support,\
- org.springframework.core,\
- org.springframework.expression,\
- org.springframework.instrument,\
- org.aopalliance
-bin.includes = META-INF/,.
-source.. = src/,\
- ext/test/
+++ /dev/null
-# 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
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.core.test.context.AbstractInternalSpringTestCase;
-import org.springframework.core.io.Resource;
-
-public class DefaultResourceSetTest extends AbstractInternalSpringTestCase {
- private final static CmsLog log = CmsLog
- .getLog(DefaultResourceSetTest.class);
-
- public void testListResources() {
- DefaultResourceSet rrs = getBean("relativeResourceSet");
- Map<String, Resource> res = rrs.listResources();
- for (String relativePath : res.keySet())
- log.debug(relativePath + "=" + res.get(relativePath));
- assertEquals(2, res.size());
- }
-
- @Override
- protected String getApplicationContextLocation() {
- return inPackage("relativeResourceSet.xml");
- }
-
-}
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean id="relativeResourceSet" class="org.argeo.slc.core.deploy.DefaultResourceSet">\r
- <property name="base" value="classpath:/org/argeo/slc/core/deploy/data" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import junit.framework.TestCase;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.runtime.test.SimpleTestResult;
-import org.argeo.slc.test.TestResultPart;
-import org.argeo.slc.test.TestStatus;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-public abstract class AbstractExecutionFlowTestCase extends TestCase {
-
- protected final CmsLog log = CmsLog.getLog(getClass());
-
- protected void logException(Throwable ex) {
- log.info("Got Exception of class " + ex.getClass().toString()
- + " with message '" + ex.getMessage() + "'.");
- }
-
- protected void validateTestResult(SimpleTestResult testResult) {
- validateTestResult(testResult, TestStatus.PASSED);
- }
-
- protected void validateTestResult(SimpleTestResult testResult,
- int expectedStatus) {
- for (TestResultPart part : testResult.getParts()) {
- if (part.getStatus() != expectedStatus) {
- fail("Error found in TestResult: " + part.getMessage());
- }
- }
- }
-
- protected ConfigurableApplicationContext createApplicationContext(
- String applicationContextSuffix) {
- ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
- inPackage(applicationContextSuffix));
- // applicationContext.start();
- return applicationContext;
- }
-
- protected void configureAndExecuteSlcFlow(String applicationContextSuffix,
- String beanName) {
- ConfigurableApplicationContext applicationContext = createApplicationContext(applicationContextSuffix);
- ExecutionContext executionContext = (ExecutionContext) applicationContext
- .getBean("executionContext");
- ExecutionFlow executionFlow = (ExecutionFlow) applicationContext
- .getBean(beanName);
- if (executionFlow instanceof DefaultExecutionFlow)
- ((DefaultExecutionFlow) executionFlow)
- .setExecutionContext(executionContext);
- try {
- executionContext.beforeFlow(executionFlow);
- executionFlow.run();
- } finally {
- executionContext.afterFlow(executionFlow);
- }
- applicationContext.close();
- }
-
- protected String inPackage(String suffix) {
- String prefix = getClass().getPackage().getName().replace('.', '/');
- return prefix + '/' + suffix;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.runtime.test.SimpleTestResult;
-import org.argeo.slc.test.TestStatus;
-import org.springframework.beans.factory.BeanCreationException;
-import org.springframework.context.ConfigurableApplicationContext;
-
-public class BasicExecutionFlowTest extends AbstractExecutionFlowTestCase {
- // TO TEST
- // - post-processing for @{} replacement in beans with complex properties
- // - bean of scope other than execution are not resolved at execution
-
- // public void testMyTest() throws Exception {
- // ConfigurableApplicationContext applicationContext =
- // createApplicationContext("test.xml");
- // log.info("Start Execution");
- // ((ExecutionFlow) applicationContext.getBean("flow1")).execute();
- // applicationContext.close();
- // }
-
- public void XXXtestSpecOverriding() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("specOverriding.xml");
- ((ExecutionFlow) applicationContext.getBean("flow2")).run();
- SimpleTestResult res = (SimpleTestResult) applicationContext
- .getBean("myTestResult");
- validateTestResult(res);
- }
-
- public void testMultipleFlows() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("multipleFlow.xml");
- ((ExecutionFlow) applicationContext.getBean("flow1")).run();
- SimpleTestResult res = (SimpleTestResult) applicationContext
- .getBean("myTestResult");
- validateTestResult(res);
- res.getParts().clear();
- ((ExecutionFlow) applicationContext.getBean("flow2")).run();
- validateTestResult(res, TestStatus.FAILED);
- applicationContext.close();
- }
-
- /**
- * Test placeholder resolution in a context without scope execution or proxy
- * and with cascading flows (the flow A contains the flow B)
- *
- * @throws Exception
- */
- public void testPlaceHolders() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("placeHolders.cascading.xml");
- ((ExecutionFlow) applicationContext.getBean("flowA")).run();
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("myTestResult"));
- applicationContext.close();
- }
-
- /**
- * Test placeholder resolution in a context without scope execution or proxy
- * and with cascading flows (the flow A contains the flow B) setting
- * execution values (should have no effect)
- *
- * @throws Exception
- */
- public void testPlaceHoldersWithExecutionValues() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("placeHolders.cascading.xml");
-
- ExecutionContext executionContext = (ExecutionContext) applicationContext
- .getBean("executionContext");
- Map<String, String> executionParameters = new HashMap<String, String>();
- executionParameters.put("p1", "e1");
- executionParameters.put("p2", "e2");
- executionParameters.put("p3", "e3");
- executionParameters.put("p4", "e4");
- executionParameters.put("p5", "e5");
- executionParameters.put("p6", "e6");
- executionParameters.put("p7", "e7");
- executionParameters.put("p8", "e8");
- addVariables(executionContext, executionParameters);
-
- ((ExecutionFlow) applicationContext.getBean("flowA")).run();
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("myTestResult"));
- applicationContext.close();
- }
-
- public void XXXtestPlaceHoldersExec() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("placeHolders.cascading.exec.xml");
-
- ExecutionContext executionContext = (ExecutionContext) applicationContext
- .getBean("executionContext");
- Map<String, String> executionParameters = new HashMap<String, String>();
- executionParameters.put("p1", "e1");
- executionParameters.put("p2", "e2");
- executionParameters.put("p3", "e3");
- executionParameters.put("p4", "e4");
- executionParameters.put("p5", "e5");
- executionParameters.put("p6", "e6");
- addVariables(executionContext, executionParameters);
-
- ((ExecutionFlow) applicationContext.getBean("flowA")).run();
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("myTestResult"));
- applicationContext.close();
- }
-
- public void testCanonicFlowParameters() throws Exception {
- configureAndExecuteSlcFlow("canonic-001.xml", "canonic.001");
- }
-
- public void testCanonicDefaultValues() throws Exception {
- configureAndExecuteSlcFlow("canonic-002.xml", "canonic.002");
- }
-
- public void testCanonicMissingValues() throws Exception {
- try {
- configureAndExecuteSlcFlow("canonic-003.error.xml", "canonic.003");
- fail("Parameter not set - should be rejected.");
- } catch (BeanCreationException e) {
- // exception expected
- logException(e);
- }
- }
-
- public void testCanonicUnknownParameter() throws Exception {
- try {
- configureAndExecuteSlcFlow("canonic-004.error.xml", "canonic.004");
- fail("Unknown parameter set - should be rejected.");
- } catch (BeanCreationException e) {
- // exception expected
- logException(e);
- }
- }
-
- public void testListSetMap() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("listSetMap.xml");
- ExecutionFlow executionFlow = (ExecutionFlow) applicationContext
- .getBean("myFlow");
- executionFlow.run();
-
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("myTestResult"));
-
- // BasicTestData res = (BasicTestData)
- // applicationContext.getBean("cascadingComplex.testData");
- // log.info("res=" + res.getReached().toString());
-
- applicationContext.close();
- }
-
- public void testListSetMapMultipleFlows() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("listSetMapMultipleFlow.xml");
- ((ExecutionFlow) applicationContext.getBean("flow1")).run();
- SimpleTestResult res = (SimpleTestResult) applicationContext
- .getBean("myTestResult");
- validateTestResult(res);
- res.getParts().clear();
- ((ExecutionFlow) applicationContext.getBean("flow2")).run();
- validateTestResult(res, TestStatus.FAILED);
- applicationContext.close();
- }
-
- protected void addVariables(ExecutionContext executionContext,
- Map<String, String> vars) {
- for (String key : vars.keySet())
- executionContext.setVariable(key, vars.get(key));
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.net.URI;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-public class DefaultAgentCliTest extends TestCase {
- public void testArgsToUris() {
- String[] args = { "org.argeo.slc.demo.minimal", "HelloWorld/WithVar",
- "--testKey", "555" };
- List<URI> uris = DefaultAgentCli.asURIs(args);
- assertEquals(1, uris.size());
- assertEquals(
- "flow:/org.argeo.slc.demo.minimal/HelloWorld/WithVar?testKey=555",
- uris.get(0).toString());
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.InitializingBean;
-
-public class ExceptionIfInitCalledTwice implements Runnable, InitializingBean {
- private final static CmsLog log = CmsLog
- .getLog(ExceptionIfInitCalledTwice.class);
-
- private Boolean calledOnce = false;
-
- public void run() {
- log.info(getClass().getSimpleName() + " ran properly");
- }
-
- public void afterPropertiesSet() throws Exception {
- log.info(getClass().getSimpleName() + " init method called");
-
- if (calledOnce)
- throw new SlcException(getClass().getSimpleName()
- + "init method called twice.");
- else
- calledOnce = true;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-
-public class FileExecutionResourcesSpringTest extends
- AbstractExecutionFlowTestCase {
- private String basePath = FileExecutionResources.DEFAULT_EXECUTION_RESOURCES_TMP_PATH;
-
- public void testSimple() throws Exception {
- File file = getFile("subdir/writeTo");
- try {
- assertFalse(file.exists());
- configureAndExecuteSlcFlow("executionResources.xml",
- "executionResources.simple");
- assertTrue(file.exists());
- } finally {
- file.deleteOnExit();
- }
- }
-
- public void testPlaceholderPass() throws Exception {
- File file = getFile("subdir/60");
- try {
- assertFalse(file.exists());
- configureAndExecuteSlcFlow("executionResources.xml",
- "executionResources.placeholderPass");
- assertTrue(file.exists());
- } finally {
- file.deleteOnExit();
- }
- }
-
- /**
- * Test that it generate the wrong file because of issue when using
- * execution placeholder in contructor-arg
- */
- public void testPlaceholderFail() throws Exception {
- File file = getFile("subdir/@{var}");
- try {
- assertFalse(file.exists());
- configureAndExecuteSlcFlow("executionResources.xml",
- "executionResources.placeholderFail");
- assertTrue(file.exists());
- } finally {
- file.deleteOnExit();
- }
- }
-
- protected File getFile(String relativePath) {
- return new File(basePath + File.separator
- + relativePath.replace('/', File.separatorChar));
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.io.FileUtils;
-import org.argeo.slc.execution.ExecutionContext;
-import org.springframework.core.io.Resource;
-
-public class FileExecutionResourcesTest extends TestCase {
- public void testGetWritableFile() throws Exception {
- FileExecutionResources executionResources = new FileExecutionResources();
- ExecutionContext executionContext = new MapExecutionContext();
- executionResources.setExecutionContext(executionContext);
-
- String expected = "TEST";
- String reached = "";
- try {
- // Resource
- Resource resource = executionResources
- .getWritableResource("subdir1/textRes.txt");
- assertTrue(resource.getFile().getParentFile().exists());
- assertFalse(resource.getFile().exists());
- FileUtils.writeStringToFile(resource.getFile(), expected);
- reached = FileUtils.readFileToString(resource.getFile());
- assertEquals(expected, reached);
-
- // File
- File file = executionResources.getFile("subdir2/textFile.txt");
- assertFalse(file.getParentFile().exists());
- assertFalse(file.exists());
- FileUtils.writeStringToFile(file, expected);
- reached = FileUtils.readFileToString(file);
- assertEquals(expected, reached);
- } finally {
- if (executionResources.getBaseDir() != null
- && executionResources.getBaseDir().exists())
- FileUtils.deleteDirectory(executionResources.getBaseDir());
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.runtime.test.SimpleTestResult;
-import org.argeo.slc.test.TestStatus;
-import org.springframework.context.ConfigurableApplicationContext;
-
-public class ParameterRefTest extends AbstractExecutionFlowTestCase {
- public void test001() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("parameterRef.xml");
- ((ExecutionFlow) applicationContext.getBean("parameterRef.001")).run();
-
- SimpleTestResult res = (SimpleTestResult) applicationContext
- .getBean("parameterRef.testResult");
- assertEquals(res.getParts().get(0).getStatus(), TestStatus.PASSED);
- assertEquals(res.getParts().get(1).getStatus(), TestStatus.FAILED);
-
- applicationContext.close();
- }
-
-}
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="executionModule_1" class="org.argeo.slc.core.execution.SimpleSpringExecutionModule" >\r
- <property name="executionContext">\r
- <ref bean="executionContext" />\r
- </property> \r
- <property name="name" value="dummyname" />\r
- <property name="version" value="dummyversion" />\r
- </bean>\r
- \r
- <bean id="main" parent="slcTemplate.simpleFlow">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="660" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <ref local="echo1" />\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="echo1" parent="task.echo" scope="execution">\r
- <property name="message"\r
- value="From main! @{testKey}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="canonic.xml" />\r
-\r
- <bean id="canonic.001" parent="canonic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="1" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="canonic.xml" />\r
-\r
- <bean id="canonic.002" parent="canonic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="2" />\r
- <entry key="displayWithoutControl" value="102" />\r
- <entry key="displayWithControl" value="202" />\r
- <entry key="hide" value="202" />\r
- <entry key="notParameterAtInstantiation" value="202" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="canonic.xml" />\r
-\r
- <bean id="canonic.003" parent="canonic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <!-- missing parameter -->\r
- <entry key="displayWithoutControl" value="102" />\r
- <entry key="displayWithControl" value="202" />\r
- <entry key="hide" value="202" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="canonic.xml" />\r
-\r
- <bean id="canonic.004" parent="canonic.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="2" />\r
- <entry key="displayWithoutControl" value="102" />\r
- <entry key="displayWithControl" value="202" />\r
- <entry key="hide" value="202" />\r
- <entry key="unknownParameter" value="1" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="imports.xml" />\r
-\r
- <bean id="canonic.spec" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="parameterAtInstantiation">\r
- <bean parent="specAttr.primitive" p:isParameter="true" p:type="integer" />\r
- </entry>\r
- <entry key="displayWithoutControl">\r
- <bean parent="specAttr.primitive" p:value="100" p:isParameter="true"\r
- p:isFrozen="true" p:type="integer" />\r
- </entry>\r
- <entry key="displayWithControl">\r
- <bean parent="specAttr.primitive" p:value="200" p:isParameter="true"\r
- p:isFrozen="false" p:type="integer" />\r
- </entry>\r
- <entry key="hide">\r
- <bean parent="specAttr.primitive" p:value="300" p:isParameter="true"\r
- p:isFrozen="false" p:isHidden="true" p:type="integer" />\r
- </entry> \r
- <entry key="notParameterAtInstantiation">\r
- <bean parent="specAttr.primitive" p:value="400" p:isParameter="false"\r
- p:isFrozen="false" p:isHidden="false" p:type="integer" />\r
- </entry> \r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="canonic.flowTemplate" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="canonic.spec" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"\r
- p:message="Canonical: displayWithControl=@{displayWithControl}, displayWithoutControl=@{displayWithoutControl}, hide=@{hide}">\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="imports.xml" />\r
-\r
- <bean id="executionResources.spec" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="var">\r
- <bean parent="specAttr.primitive" p:isParameter="false"\r
- p:type="integer" p:value="60" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="executionResources.placeholderPass" parent="slcTemplate.simpleFlow">\r
- <constructor-arg ref="executionResources.spec" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="DATA" />\r
- <property name="writeTo">\r
- <bean parent="slcTemplate.resourcesFactoryBean" scope="execution">\r
- <property name="executionResources" ref="executionResources" />\r
- <property name="relativePath" value="subdir/@{var}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="executionResources.placeholderFail" parent="slcTemplate.simpleFlow">\r
- <constructor-arg ref="executionResources.spec" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="DATA" />\r
- <property name="writeTo">\r
- <bean factory-bean="executionResources" factory-method="getWritableResource"\r
- scope="execution">\r
- <constructor-arg value="subdir/@{var}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="executionResources.simple" parent="slcTemplate.simpleFlow">\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="DATA" />\r
- <property name="writeTo">\r
- <bean factory-bean="executionResources" factory-method="getWritableResource"\r
- scope="execution">\r
- <constructor-arg value="subdir/writeTo" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="executionResources" parent="slcTemplate.fileResources">\r
- <property name="executionContext" ref="executionContext" />\r
- <property name="withExecutionSubdirectory" value="false" />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<!-- Copyright (C) 2007-2012 Mathieu Baudier 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. -->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <import resource="classpath:org/argeo/slc/core/execution/spring.xml" />
- <import resource="classpath:/org/argeo/slc/core/test/spring.xml" />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="basic.testDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
-\r
- <bean id="myFlow" parent="slcTemplate.simpleFlow">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="myValue" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <ref local="echo1" />\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingMap.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleList.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingList.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleSet.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingSet.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingListMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingSetMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingComplex.testData" />\r
- </bean> \r
- \r
- </list>\r
- </property>\r
- </bean>\r
-\r
-\r
- <bean id="simpleMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <map>\r
- <entry key="key1" value="myValue_myValue" />\r
- </map>\r
- </property>\r
- <property name="reached">\r
- <map>\r
- <entry key="key1" value="@{testKey}_@{testKey}" />\r
- </map>\r
- </property>\r
- </bean>\r
- \r
- <bean id="cascadingMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <map>\r
- <entry key="key3">\r
- <map>\r
- <entry key="key2">\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map>\r
- </entry>\r
- <entry key="key2bis" value="myValue" />\r
- </map>\r
- </entry>\r
- </map>\r
- </property>\r
- <property name="reached">\r
- <map>\r
- <entry key="key3">\r
- <map>\r
- <entry key="key2">\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map>\r
- </entry>\r
- <entry key="key2bis" value="@{testKey}" />\r
- </map>\r
- </entry>\r
- </map>\r
- </property>\r
- </bean> \r
- \r
- <bean id="simpleList.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value> \r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingList.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- <value>myValue</value>\r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </list>\r
- <value>@{testKey}</value>\r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="simpleSet.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingSet.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </set>\r
- <value>myValue</value>\r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </set>\r
- <value>@{testKey}</value>\r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingListMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingSetMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingComplex.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- <list>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- <set>\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- <list>\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- <value>myValue</value>\r
- </list> \r
- </set>\r
- <value>myValue</value>\r
- </set> \r
- </list> \r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </set> \r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- <list>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- <set>\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- <list>\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </list>\r
- <value>@{testKey}</value>\r
- </list> \r
- </set>\r
- <value>@{testKey}</value>\r
- </set> \r
- </list> \r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </set> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="basic.testDef" class="org.argeo.slc.runtime.test.BasicTestDefinition">\r
- </bean> \r
-\r
-\r
- <bean id="echo1" parent="task.echo" scope="prototype">\r
- <property name="message"\r
- value="testKey=@{testKey}" />\r
- </bean>\r
- \r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="basic.testDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
-\r
- <bean id="abstractFlow" parent="slcTemplate.simpleFlow" abstract="true">\r
- <property name="executables">\r
- <list>\r
- <ref local="echo1" />\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingMap.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleList.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingList.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="simpleSet.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingSet.testData" />\r
- </bean> \r
- \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingListMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingSetMap.testData" />\r
- </bean> \r
- <bean parent="myTestRunTemplate">\r
- <property name="testData" ref="cascadingComplex.testData" />\r
- </bean> \r
- \r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flow1" parent="abstractFlow" scope="prototype">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="myValue" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- </bean> \r
-\r
- <bean id="flow2" parent="abstractFlow" scope="prototype">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="myValue2" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- </bean> \r
-\r
-\r
- <bean id="simpleMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <map>\r
- <entry key="key1" value="myValue_myValue" />\r
- </map>\r
- </property>\r
- <property name="reached">\r
- <map>\r
- <entry key="key1" value="@{testKey}_@{testKey}" />\r
- </map>\r
- </property>\r
- </bean>\r
- \r
- <bean id="cascadingMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <map>\r
- <entry key="key3">\r
- <map>\r
- <entry key="key2">\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map>\r
- </entry>\r
- <entry key="key2bis" value="myValue" />\r
- </map>\r
- </entry>\r
- </map>\r
- </property>\r
- <property name="reached">\r
- <map>\r
- <entry key="key3">\r
- <map>\r
- <entry key="key2">\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map>\r
- </entry>\r
- <entry key="key2bis" value="@{testKey}" />\r
- </map>\r
- </entry>\r
- </map>\r
- </property>\r
- </bean> \r
- \r
- <bean id="simpleList.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value> \r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingList.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- <value>myValue</value>\r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </list>\r
- <value>@{testKey}</value>\r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="simpleSet.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingSet.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </set>\r
- <value>myValue</value>\r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </set>\r
- <value>@{testKey}</value>\r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingListMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <list>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </list>\r
- </property>\r
- <property name="reached">\r
- <list>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </list>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingSetMap.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="cascadingComplex.testData" class="org.argeo.slc.runtime.test.BasicTestData" scope="prototype">\r
- <property name="expected">\r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- <list>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- <set>\r
- <set>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- <list>\r
- <list>\r
- <value>myValue</value>\r
- <value>_myValue_</value>\r
- </list>\r
- <value>myValue</value>\r
- </list> \r
- </set>\r
- <value>myValue</value>\r
- </set> \r
- </list> \r
- <set>\r
- <map>\r
- <entry key="key1" value="myValue" />\r
- </map> \r
- </set> \r
- </set>\r
- </property>\r
- <property name="reached">\r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- <list>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- <set>\r
- <set>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- <list>\r
- <list>\r
- <value>@{testKey}</value>\r
- <value>_@{testKey}_</value>\r
- </list>\r
- <value>@{testKey}</value>\r
- </list> \r
- </set>\r
- <value>@{testKey}</value>\r
- </set> \r
- </list> \r
- <set>\r
- <map>\r
- <entry key="key1" value="@{testKey}" />\r
- </map> \r
- </set> \r
- </set>\r
- </property>\r
- </bean> \r
- \r
- <bean id="basic.testDef" class="org.argeo.slc.runtime.test.BasicTestDefinition">\r
- </bean> \r
-\r
-\r
- <bean id="echo1" parent="task.echo" scope="prototype">\r
- <property name="message"\r
- value="testKey=@{testKey}" />\r
- </bean>\r
- \r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="minimal" parent="slcTemplate.simpleFlow">\r
- <property name="executionSpec">\r
- <bean parent="slcTemplate.simpleSpec">\r
-<!-- <property name="attributes">\r
- <map>\r
- <entry key="testKey">\r
- <bean parent="specAttr.primitive" p:value="660" />\r
- </entry>\r
- </map>\r
- </property> -->\r
- </bean>\r
- </property>\r
- <property name="executables">\r
- <list>\r
- <ref local="echo1" />\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="echo1" parent="task.echo" scope="execution">\r
- <property name="message"\r
- value="From minimal" />\r
- <aop:scoped-proxy />\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="myTestDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="myTestDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
-\r
- <bean id="fileDiff.spec" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="fileName">\r
- <bean parent="specAttr.primitive" p:isParameter="true" p:type="string"\r
- p:isFrozen="true" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
-\r
- <bean id="fileDiff.flowTemplate" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <property name="path" value="/fileDiff/testcases" />\r
- <constructor-arg ref="fileDiff.spec" />\r
- <property name="executables">\r
- <list> \r
- <bean parent="task.echo">\r
- <property name="message" value="fileName=@{fileName}" />\r
- </bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="file1" />\r
- <property name="reached" value="@{fileName}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
- \r
- <bean id="echo" parent="task.echo" scope="prototype">\r
- <property name="message" value="fileName=@{fileName}" />\r
- </bean> \r
- \r
- <bean id="flow1" parent="fileDiff.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="fileName" value="file1" />\r
- </map>\r
- </constructor-arg>\r
- </bean> \r
-\r
- <bean id="flow2" parent="fileDiff.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="fileName" value="file2" />\r
- </map>\r
- </constructor-arg>\r
- </bean> \r
- \r
- \r
- <!-- \r
- <bean id="flow1" parent="slcTemplate.simpleFlow">\r
- <property name="path" value="/fileDiff/testcases" />\r
- <constructor-arg ref="fileDiff.spec" />\r
- <constructor-arg>\r
- <map>\r
- <entry key="fileName" value="file1" />\r
- </map>\r
- </constructor-arg> \r
- <property name="executables">\r
- <list> \r
- <bean parent="task.echo" scope="execution">\r
- <property name="message" value="fileName=@{fileName}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flow2" parent="slcTemplate.simpleFlow">\r
- <property name="path" value="/fileDiff/testcases" />\r
- <constructor-arg ref="fileDiff.spec" />\r
- <constructor-arg>\r
- <map>\r
- <entry key="fileName" value="file2" />\r
- </map>\r
- </constructor-arg> \r
- <property name="executables">\r
- <list> \r
- <bean parent="task.echo" scope="execution">\r
- <property name="message" value="fileName=@{fileName}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
- -->\r
-<!-- \r
- <bean id="main" parent="slcTemplate.simpleFlow">\r
- <property name="executables">\r
- <list> \r
- <ref bean="flow1"/> \r
- <ref bean="flow2"/> \r
- </list>\r
- </property>\r
- </bean>\r
- -->\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="imports.xml" />\r
-\r
- <!-- DEFINITIONS -->\r
- <bean id="parameterRef.spec" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="exceptionIfInitCalledTwice">\r
- <bean parent="specAttr.ref"\r
- p:targetClass="org.argeo.slc.core.execution.ExceptionIfInitCalledTwice"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- <entry key="testData1">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- <entry key="testData2">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- <entry key="testedComponentId">\r
- <bean parent="specAttr.primitive" p:value="100" p:isParameter="true"\r
- p:type="integer" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="parameterRef.flowTemplate" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="parameterRef.spec" />\r
- <property name="executables">\r
- <list>\r
- <!-- Primitive -->\r
- <bean parent="task.echo" scope="execution">\r
- <property name="message" value="testedComponentId=@{testedComponentId}" />\r
- </bean>\r
-\r
- <!-- Exception if init called twice -->\r
- <bean parent="parameterRef">\r
- <constructor-arg value="exceptionIfInitCalledTwice" />\r
- </bean>\r
- <bean parent="parameterRef">\r
- <property name="name" value="exceptionIfInitCalledTwice" />\r
- </bean>\r
-\r
- <!-- Basic tests -->\r
- <bean parent="parameterRef.testRun">\r
- <property name="testData">\r
- <bean parent="parameterRef">\r
- <constructor-arg value="testData1" />\r
- </bean>\r
- </property>\r
- </bean>\r
- <bean parent="parameterRef.testRun">\r
- <property name="testData" ref="ref1" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <!-- TEST CASES -->\r
- <bean id="parameterRef.001" parent="parameterRef.flowTemplate">\r
- <constructor-arg>\r
- <map>\r
- <entry key="exceptionIfInitCalledTwice">\r
- <bean class="org.argeo.slc.core.execution.ExceptionIfInitCalledTwice" />\r
- </entry>\r
- <entry key="testData1">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="toto" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
- </entry>\r
- <entry key="testData2">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="tata" />\r
- <property name="reached" value="toto" />\r
- </bean>\r
- </entry>\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-\r
- <!-- UTILITIES -->\r
-\r
- <bean id="ref1" parent="parameterRef">\r
- <constructor-arg value="testData2" />\r
- </bean>\r
-\r
- <bean id="parameterRef.testResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="parameterRef.testRun" class="org.argeo.slc.runtime.test.SimpleTestRun"\r
- abstract="true">\r
- <property name="testResult" ref="parameterRef.testResult" />\r
- <property name="testDefinition">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
- </property>\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="myTestDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="echo1" parent="task.echo">\r
- <property name="message" value="From minimal" />\r
- </bean>\r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="myTestDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
-\r
- <!-- \r
- The Flow A contains the flow B as executable.\r
- \r
- Parameters\r
- p1: flow A: default - flow B: - \r
- p2: flow A: set - flow B: - \r
- p3: flow A: default - flow B: default \r
- p4: flow A: set - flow B: default\r
- p5: flow A: default - flow B: set \r
- p6: flow A: set - flow B: set\r
- p7: flow A: - - flow B: default\r
- p8: flow A: - - flow B: set\r
- \r
- \r
- -->\r
-\r
- <bean id="flowA" parent="slcTemplate.simpleFlow">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="p1"><bean parent="specAttr.primitive" p:value="da1" /></entry>\r
- <entry key="p2"><bean parent="specAttr.primitive" p:value="da2" /></entry> \r
- <entry key="p3"><bean parent="specAttr.primitive" p:value="da3" /></entry> \r
- <entry key="p4"><bean parent="specAttr.primitive" p:value="da4" /></entry> \r
- <entry key="p5"><bean parent="specAttr.primitive" p:value="da5" /></entry> \r
- <entry key="p6"><bean parent="specAttr.primitive" p:value="da6" /></entry> \r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <constructor-arg> \r
- <map>\r
- <entry key="p2" value="va2"/>\r
- <entry key="p4" value="va4"/>\r
- <entry key="p6" value="va6"/>\r
- </map>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"><property name="message" value="p1=@{p1}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da1" />\r
- <property name="reached" value="@{p1}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- <bean parent="task.echo"><property name="message" value="p2=@{p2}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va2" />\r
- <property name="reached" value="@{p2}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p3=@{p3}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da3" />\r
- <property name="reached" value="@{p3}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p4=@{p4}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va4" />\r
- <property name="reached" value="@{p4}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p5=@{p5}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da5" />\r
- <property name="reached" value="@{p5}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p6=@{p6}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va6" />\r
- <property name="reached" value="@{p6}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <ref bean="flowB"/> \r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flowB" parent="slcTemplate.simpleFlow" scope="prototype">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="p3"><bean parent="specAttr.primitive" p:value="db3" /></entry> \r
- <entry key="p4"><bean parent="specAttr.primitive" p:value="db4" /></entry>\r
- <entry key="p5"><bean parent="specAttr.primitive" p:value="db5" /></entry> \r
- <entry key="p6"><bean parent="specAttr.primitive" p:value="db6" /></entry>\r
- <entry key="p7"><bean parent="specAttr.primitive" p:value="db7" /></entry> \r
- <entry key="p8"><bean parent="specAttr.primitive" p:value="db8" /></entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <constructor-arg> \r
- <map>\r
- <entry key="p3" value="vb3"/>\r
- <entry key="p4" value="vb4"/>\r
- <entry key="p7" value="vb7"/>\r
- </map>\r
- </constructor-arg> \r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"><property name="message" value="p1=@{p1}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da1" />\r
- <property name="reached" value="@{p1}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- <bean parent="task.echo"><property name="message" value="p2=@{p2}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va2" />\r
- <property name="reached" value="@{p2}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p3=@{p3}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da3" />\r
- <property name="reached" value="@{p3}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p4=@{p4}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va4" />\r
- <property name="reached" value="@{p4}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p5=@{p5}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da5" />\r
- <property name="reached" value="@{p5}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p6=@{p6}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va6" />\r
- <property name="reached" value="@{p6}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p7=@{p7}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="vb7" />\r
- <property name="reached" value="@{p7}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p8=@{p8}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="db8" />\r
- <property name="reached" value="@{p8}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- \r
- <!-- test in scope execution -->\r
- <bean parent="task.echo" scope="execution"><property name="message" value="p1=@{p1}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e1" />\r
- <property name="reached" value="@{p1}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean>\r
- <bean parent="task.echo" scope="execution"><property name="message" value="p2=@{p2}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e2" />\r
- <property name="reached" value="@{p2}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo" scope="execution"><property name="message" value="p3=@{p3}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e3" />\r
- <property name="reached" value="@{p3}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo" scope="execution"><property name="message" value="p4=@{p4}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e4" />\r
- <property name="reached" value="@{p4}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo" scope="execution"><property name="message" value="p5=@{p5}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e5" />\r
- <property name="reached" value="@{p5}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo" scope="execution"><property name="message" value="p6=@{p6}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="e6" />\r
- <property name="reached" value="@{p6}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean>\r
- \r
- <!-- \r
- p7 and p8 are not in the spec of FlowA and therefore can not be overridden\r
- at the execution\r
- -->\r
- <bean parent="task.echo" scope="execution"><property name="message" value="p7=@{p7}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="vb7" />\r
- <property name="reached" value="@{p7}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo" scope="execution"><property name="message" value="p8=@{p8}" /><aop:scoped-proxy /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <property name="expected" value="db8" />\r
- <property name="reached" value="@{p8}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property> \r
- </bean> \r
- \r
- </list>\r
- </property>\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="myTestDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="echo1" parent="task.echo">\r
- <property name="message" value="From minimal" />\r
- </bean>\r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="myTestDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
-\r
- <!-- \r
- The Flow A contains the flow B as executable.\r
- \r
- Parameters\r
- p1: flow A: default - flow B: - \r
- p2: flow A: set - flow B: - \r
- p3: flow A: default - flow B: default \r
- p4: flow A: set - flow B: default\r
- p5: flow A: default - flow B: set \r
- p6: flow A: set - flow B: set\r
- p7: flow A: - - flow B: default\r
- p8: flow A: - - flow B: set\r
- \r
- \r
- -->\r
-\r
- <bean id="flowA" parent="slcTemplate.simpleFlow">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="p1"><bean parent="specAttr.primitive" p:value="da1" /></entry>\r
- <entry key="p2"><bean parent="specAttr.primitive" p:value="da2" /></entry> \r
- <entry key="p3"><bean parent="specAttr.primitive" p:value="da3" /></entry> \r
- <entry key="p4"><bean parent="specAttr.primitive" p:value="da4" /></entry> \r
- <entry key="p5"><bean parent="specAttr.primitive" p:value="da5" /></entry> \r
- <entry key="p6"><bean parent="specAttr.primitive" p:value="da6" /></entry> \r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <constructor-arg> \r
- <map>\r
- <entry key="p2" value="va2"/>\r
- <entry key="p4" value="va4"/>\r
- <entry key="p6" value="va6"/>\r
- </map>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"><property name="message" value="p1=@{p1}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da1" />\r
- <property name="reached" value="@{p1}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- <bean parent="task.echo"><property name="message" value="p2=@{p2}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va2" />\r
- <property name="reached" value="@{p2}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p3=@{p3}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da3" />\r
- <property name="reached" value="@{p3}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p4=@{p4}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va4" />\r
- <property name="reached" value="@{p4}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p5=@{p5}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da5" />\r
- <property name="reached" value="@{p5}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p6=@{p6}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va6" />\r
- <property name="reached" value="@{p6}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <ref bean="flowB"/> \r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flowB" parent="slcTemplate.simpleFlow" scope="prototype">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="p3"><bean parent="specAttr.primitive" p:value="db3" /></entry> \r
- <entry key="p4"><bean parent="specAttr.primitive" p:value="db4" /></entry>\r
- <entry key="p5"><bean parent="specAttr.primitive" p:value="db5" /></entry> \r
- <entry key="p6"><bean parent="specAttr.primitive" p:value="db6" /></entry>\r
- <entry key="p7"><bean parent="specAttr.primitive" p:value="db7" /></entry> \r
- <entry key="p8"><bean parent="specAttr.primitive" p:value="db8" /></entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <constructor-arg> \r
- <map>\r
- <entry key="p3" value="vb3"/>\r
- <entry key="p4" value="vb4"/>\r
- <entry key="p7" value="vb7"/>\r
- </map>\r
- </constructor-arg> \r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo"><property name="message" value="p1=@{p1}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da1" />\r
- <property name="reached" value="@{p1}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- <bean parent="task.echo"><property name="message" value="p2=@{p2}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va2" />\r
- <property name="reached" value="@{p2}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p3=@{p3}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da3" />\r
- <property name="reached" value="@{p3}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p4=@{p4}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va4" />\r
- <property name="reached" value="@{p4}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p5=@{p5}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="da5" />\r
- <property name="reached" value="@{p5}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p6=@{p6}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="va6" />\r
- <property name="reached" value="@{p6}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p7=@{p7}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="vb7" />\r
- <property name="reached" value="@{p7}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- <bean parent="task.echo"><property name="message" value="p8=@{p8}" /></bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="db8" />\r
- <property name="reached" value="@{p8}" />\r
- </bean>\r
- </property> \r
- </bean> \r
- </list>\r
- </property>\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="imports.xml" /> \r
- \r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="myTestDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="myTestDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
- \r
- <bean id="spec1" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testedComponentId">\r
- <bean parent="specAttr.primitive" p:isParameter="true"\r
- p:type="integer" />\r
- </entry>\r
- <entry key="testData1">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flowTemplate1" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="spec1" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo" scope="execution">\r
- <property name="message" value="From basic @{testedComponentId}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean parent="parameterRef">\r
- <constructor-arg value="testData1" />\r
- </bean>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flow1" parent="flowTemplate1" scope="prototype">\r
- <constructor-arg>\r
- <map>\r
- <entry key="testedComponentId" value="200" />\r
- <entry key="testData1">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <aop:scoped-proxy/>\r
- <property name="expected" value="tata101" />\r
- <property name="reached" value="tata@{testedComponentId}" />\r
- </bean>\r
- </entry>\r
- </map> \r
- </constructor-arg>\r
- </bean>\r
-\r
- <bean id="spec2" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testData1">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flowTemplate2" parent="slcTemplate.simpleFlow" abstract="true">\r
- <constructor-arg ref="spec2" />\r
- <property name="executables">\r
- <list>\r
- <ref bean="flow1"/>\r
- </list>\r
- </property>\r
- </bean>\r
- \r
- <bean id="flow2" parent="flowTemplate2">\r
- <constructor-arg>\r
- <map>\r
- <entry key="testData1">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected" value="tata100" />\r
- <property name="reached" value="tata100" />\r
- </bean>\r
- </entry>\r
- </map> \r
- </constructor-arg>\r
- </bean> \r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.core.execution.AbstractExecutionFlowTestCase;
-
-public class SystemCallTest extends AbstractExecutionFlowTestCase {
- private final static CmsLog log = CmsLog.getLog(SystemCallTest.class);
-
- private final String defFile = "systemCall.xml";
-
- public void testSystemCallSimple() throws Exception {
- if (isOsSupported())
- configureAndExecuteSlcFlow(defFile, "systemCallSimple");
- }
-
- public void testSystemCallList() throws Exception {
- if (isOsSupported())
- configureAndExecuteSlcFlow(defFile, "systemCallList");
- }
-
- public void testSystemCallOsSpecific() throws Exception {
- if (isOsSupported())
- configureAndExecuteSlcFlow(defFile, "systemCallOsSpecific");
- }
-
- public void testSystemCallWithVar() throws Exception {
- if (isOsSupported())
- configureAndExecuteSlcFlow(defFile, "systemCallWithVar");
- }
-
- protected boolean isOsSupported() {
- String osName = System.getProperty("os.name");
- final Boolean ret;
- if (osName.contains("Windows"))
- ret = false;
- else
- ret = true;
-
- if (ret == false)
- log.warn("Skip test because OS '" + osName + "' is not supported.");
- return ret;
- }
-}
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:aop="http://www.springframework.org/schema/aop"\r
- xsi:schemaLocation="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
-\r
- <import resource="../imports.xml" />\r
-\r
- <bean id="systemCallSimple" parent="slcTemplate.simpleFlow">\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="os.name=${os.name}" />\r
- </bean>\r
- <bean parent="task.systemCall">\r
- <property name="cmd" value="echo Hello World" />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="systemCallList" parent="slcTemplate.simpleFlow">\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.systemCall">\r
- <property name="command">\r
- <list>\r
- <value>echo</value>\r
- <value>Hello</value>\r
- <value>World</value>\r
- </list>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="systemCallOsSpecific" parent="slcTemplate.simpleFlow">\r
- <!-- Direct call to dir under Windows isnot working -->\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.systemCall">\r
- <property name="cmd" value="dir" />\r
- <property name="execDir" value="../.." />\r
- <property name="osCmds">\r
- <map>\r
- <entry key="Linux" value="ls" />\r
- <entry key="Mac OS X" value="ls" />\r
- </map>\r
- </property>\r
- </bean>\r
- <bean parent="task.systemCall">\r
- <property name="command">\r
- <list>\r
- <value>dir</value>\r
- </list>\r
- </property>\r
- <property name="osCommands">\r
- <map>\r
- <entry key="Linux">\r
- <list>\r
- <value>ls</value>\r
- </list>\r
- </entry>\r
- <entry key="Mac OS X">\r
- <list>\r
- <value>ls</value>\r
- </list>\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="systemCallWithVar" parent="slcTemplate.simpleFlow">\r
- <constructor-arg>\r
- <bean parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="var">\r
- <bean parent="specAttr.primitive" p:value="660" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
- </constructor-arg>\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.systemCall" scope="execution">\r
- <property name="cmd" value="echo var=@{var}" />\r
- <aop:scoped-proxy />\r
- </bean>\r
- </list>\r
- </property>\r
- </bean>\r
-\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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"\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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">\r
-\r
- <import resource="imports.xml" /> \r
-\r
- <bean id="myTestResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="myTestDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="myTestRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="myTestDef" />\r
- <property name="testResult" ref="myTestResult"/>\r
- </bean> \r
- \r
- <bean id="spec1" parent="slcTemplate.simpleSpec">\r
- <property name="attributes">\r
- <map>\r
- <entry key="testedComponentId">\r
- <bean parent="specAttr.primitive" p:isParameter="true"\r
- p:type="integer" />\r
- </entry>\r
- <entry key="testData1">\r
- <bean parent="specAttr.ref" p:targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- p:isParameter="true" p:isFrozen="true" />\r
- </entry>\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flowTemplate1" parent="slcTemplate.simpleFlow"\r
- abstract="true">\r
- <constructor-arg ref="spec1" />\r
- <property name="executables">\r
- <list>\r
- <bean parent="task.echo">\r
- <property name="message" value="From basic @{testedComponentId}" />\r
- </bean>\r
- <bean parent="myTestRunTemplate">\r
- <property name="testData">\r
- <bean parent="parameterRef">\r
- <constructor-arg value="testData1" />\r
- </bean>\r
- </property>\r
- </bean>\r
- <bean parent="task.echo">\r
- <property name="message"><value>From basic @{testedComponentId}</value></property>\r
- </bean> \r
- <bean parent="task.echo">\r
- <property name="message"><value>testData1='@{testData1}'</value></property>\r
- </bean> \r
- </list>\r
- </property>\r
- </bean>\r
-\r
- <bean id="flow1" parent="flowTemplate1" scope="prototype">\r
- <constructor-arg>\r
- <map>\r
- <entry key="testedComponentId" value="200" />\r
- <entry key="testData1">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData" scope="execution">\r
- <aop:scoped-proxy/>\r
- <property name="expected" value="tata101" />\r
- <property name="reached" value="tata@{testedComponentId}" />\r
- </bean>\r
- </entry>\r
- </map> \r
- </constructor-arg>\r
- </bean>\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.argeo.slc.core.execution.AbstractExecutionFlowTestCase;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.runtime.test.SimpleTestResult;
-import org.springframework.context.ConfigurableApplicationContext;
-
-public abstract class FlowNamespaceTest extends AbstractExecutionFlowTestCase {
- public void XXXtestCanonical() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("canonic-ns.xml");
- ((ExecutionFlow) applicationContext.getBean("canonic-ns.001")).run();
- ((ExecutionFlow) applicationContext.getBean("canonic-ns.002")).run();
- }
-
- public void XXXtestAdvanced() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("advanced.xml");
- ((ExecutionFlow) applicationContext.getBean("flow1")).run();
- ((ExecutionFlow) applicationContext.getBean("flow2")).run();
- ((ExecutionFlow) applicationContext.getBean("flow3")).run();
-
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("testResult"));
- }
-
- public void XXXtestAdvancedExecution() throws Exception {
- ConfigurableApplicationContext applicationContext = createApplicationContext("advanced.xml");
-
- ExecutionContext executionContext = (ExecutionContext) applicationContext
- .getBean("executionContext");
- executionContext.setVariable("param2", 4);
-
- ((ExecutionFlow) applicationContext.getBean("flow4")).run();
-
- validateTestResult((SimpleTestResult) applicationContext
- .getBean("testResult"));
- }
-
- // These tests causes pb when using Spring 3
-
- // public void testContainers() throws Exception {
- // ConfigurableApplicationContext applicationContext =
- // createApplicationContext("containers.xml");
- // ((ExecutionFlow) applicationContext.getBean("test.list.flow1")).run();
- // ((ExecutionFlow) applicationContext.getBean("test.list.flow2")).run();
- //
- // validateTestResult((SimpleTestResult) applicationContext
- // .getBean("testResult"));
- // }
-}
+++ /dev/null
-<?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
-<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: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/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd\r
- http://www.argeo.org/schema/slc-flow http://www.argeo.org/schema/slc-flow-0.12.xsd">\r
-\r
- <import resource="classpath:org/argeo/slc/core/execution/spring.xml" />\r
- <import resource="classpath:/org/argeo/slc/core/test/spring.xml" />\r
-\r
- <bean id="testResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="testDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="testRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="testDef" />\r
- <property name="testResult" ref="testResult"/>\r
- </bean> \r
-\r
- <flow:spec id="advanced.spec">\r
- <description>spec description</description>\r
- <flow:primitive name="param1" isParameter="true"\r
- type="integer" />\r
- <flow:primitive name="param2" isParameter="true"\r
- type="integer" /> \r
- </flow:spec>\r
-\r
-\r
- <flow:flow id="advanced.flowTemplate" abstract="true" spec="advanced.spec"\r
- path="/path">\r
- <description>flow description</description>\r
- <bean parent="task.echo">\r
- <property name="message" value="Advanced: param1=@{param1}, param2=@{param2}" />\r
- <flow:variable/>\r
- </bean> \r
- <flow:flow>\r
- <bean parent="task.echo" p:message="Flow in Flow - param1=@{param1}, param2=@{param2} [Not variable]" />\r
- </flow:flow>\r
- \r
- <bean parent="testRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <flow:variable/>\r
- <property name="expected" value="@{param1}" />\r
- <property name="reached" value="@{param2}" />\r
- </bean>\r
- </property> \r
- </bean>\r
- \r
- </flow:flow>\r
-\r
- <flow:flow id="advanced.flowTemplate2" abstract="true" spec="advanced.spec"\r
- path="/path">\r
- <bean parent="task.echo" p:message="Advanced2: param1=@{param1}, param2=@{param2}">\r
- <flow:variable/>\r
- </bean>\r
- <flow:flow parent="advanced.flowTemplate">\r
- <flow:arg name="param1" value="@{param1}"/>\r
- <flow:arg name="param2">\r
- <!-- flow:param in flow:arg -->\r
- <flow:param name="param2" />\r
- </flow:arg>\r
- </flow:flow>\r
- </flow:flow>\r
-\r
- \r
- <flow:flow id="flow1" parent="advanced.flowTemplate">\r
- <flow:arg name="param1" value="1" />\r
- <flow:arg name="param2" value="1" />\r
- </flow:flow>\r
- \r
- <flow:flow id="flow2">\r
- <flow:flow parent="advanced.flowTemplate">\r
- <flow:arg name="param1" value="2" />\r
- <flow:arg name="param2" value="2" />\r
- </flow:flow>\r
- </flow:flow>\r
-\r
- <flow:flow id="flow3" parent="advanced.flowTemplate2">\r
- <flow:arg name="param1" value="3" />\r
- <flow:arg name="param2" value="3" />\r
- </flow:flow>\r
- \r
- <flow:flow id="flow4" parent="advanced.flowTemplate">\r
- <description>Would fail if param 2 is not changed at execution</description>\r
- <flow:arg name="param1" value="4" />\r
- <flow:arg name="param2" value="3" />\r
- </flow:flow> \r
-\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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: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.argeo.org/schema/slc-flow http://www.argeo.org/schema/slc-flow-0.12.xsd">\r
-\r
- <bean id="canonic-ns.001" parent="canonic-ns.flowTemplate">\r
- <description>Canonic 001</description>\r
- <constructor-arg>\r
- <map>\r
- <entry key="parameterAtInstantiation" value="1" />\r
- </map>\r
- </constructor-arg>\r
- </bean>\r
-</beans>\r
+++ /dev/null
-<?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
-<beans:beans xmlns="http://www.argeo.org/schema/slc-flow"\r
- xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:p="http://www.springframework.org/schema/p"\r
- xsi:schemaLocation="\r
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
- http://www.argeo.org/schema/slc-flow http://www.argeo.org/schema/slc-flow-0.12.xsd">\r
-\r
- <flow id="canonic-ns.002" parent="canonic-ns.flowTemplate">\r
- <arg name="parameterAtInstantiation" value="2" />\r
- <arg name="displayWithoutControl" value="102" />\r
- <arg name="displayWithControl" value="202" />\r
- <arg name="hide" value="202" />\r
- <arg name="refWithoutValue">\r
- <beans:bean id="testDataOk" p:expected="tata" p:reached="tata"\r
- class="org.argeo.slc.runtime.test.BasicTestData" />\r
- </arg>\r
- </flow>\r
-</beans:beans>\r
+++ /dev/null
-<?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
-<beans:beans xmlns="http://www.argeo.org/schema/slc-flow"\r
- xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"\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-0.12.xsd">\r
-\r
- <beans:import resource="classpath:org/argeo/slc/core/execution/spring.xml" />\r
- <beans:import resource="classpath:/org/argeo/slc/core/test/spring.xml" />\r
-\r
- <beans:import resource="canonic-ns-001.xml" />\r
- <beans:import resource="canonic-ns-002.xml" />\r
- <beans:import resource="tests.xml" />\r
-\r
- <!--\r
- Specifications definition is greatly simplified by the flow namespace\r
- -->\r
- <spec id="canonic-ns.spec">\r
- <primitive name="parameterAtInstantiation" isParameter="true"\r
- type="integer" />\r
- <primitive name="displayWithoutControl" value="100"\r
- isParameter="true" type="integer" isFrozen="true" />\r
- <primitive name="displayWithControl" value="200"\r
- isParameter="true" type="integer" />\r
- <primitive name="hide" value="300" isParameter="true" type="integer"\r
- isHidden="true" />\r
- <ref name="refWithValue" targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- isParameter="true" ref="testDataNok" />\r
- <ref name="refWithoutValue" targetClass="org.argeo.slc.runtime.test.BasicTestData" />\r
- <ref name="refWithoutValueFrozen" targetClass="org.argeo.slc.runtime.test.BasicTestData"\r
- isParameter="true" isFrozen="true">\r
- <value>\r
- <beans:bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <beans:property name="expected" value="tata" />\r
- <beans:property name="reached" value="tata" />\r
- </beans:bean>\r
- </value>\r
- </ref>\r
- </spec>\r
-\r
- <flow id="canonic-ns.flowTemplate" abstract="true" spec="canonic-ns.spec"\r
- path="/path">\r
- <beans:bean parent="task.echo"\r
- p:message="Canonical: displayWithControl=@{displayWithControl}, displayWithoutControl=@{displayWithoutControl}, hide=@{hide}"\r
- scope="execution">\r
- <aop:scoped-proxy />\r
- </beans:bean>\r
- <beans:ref bean="testRun" />\r
- </flow>\r
-\r
- <beans:bean id="testDataOk" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <beans:property name="expected" value="tata" />\r
- <beans:property name="reached" value="tata" />\r
- </beans:bean>\r
-\r
- <beans:bean id="testDataNok" class="org.argeo.slc.runtime.test.BasicTestData">\r
- <aop:scoped-proxy />\r
- <beans:property name="expected" value="tata" />\r
- <beans:property name="reached" value="toto" />\r
- </beans:bean>\r
-</beans:beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<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:flow="http://www.argeo.org/schema/slc-flow" xmlns:aop="http://www.springframework.org/schema/aop"\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/lang http://www.springframework.org/schema/lang/spring-lang-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-0.12.xsd">\r
-\r
- <import resource="classpath:org/argeo/slc/core/execution/spring.xml" />\r
- <import resource="classpath:/org/argeo/slc/core/test/spring.xml" />\r
-\r
- <bean id="testResult" class="org.argeo.slc.runtime.test.SimpleTestResult" />\r
-\r
- <bean id="testDef" class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
-\r
- <bean id="testRunTemplate" class="org.argeo.slc.runtime.test.SimpleTestRun" abstract="true">\r
- <property name="testDefinition" ref="testDef" />\r
- <property name="testResult" ref="testResult"/>\r
- </bean> \r
-\r
- <flow:spec id="test.list.spec">\r
- <flow:ref name="list1" targetClass="java.util.List">\r
- <flow:value>\r
- <!-- a list element can be used directly as default value-->\r
- <list>\r
- <value>val1</value>\r
- </list>\r
- </flow:value>\r
- </flow:ref>\r
- <flow:ref name="list2" targetClass="java.util.List" />\r
- <!-- following parameters are not used in flow -->\r
- <flow:ref name="dummyMap" targetClass="java.util.Map">\r
- <flow:value>\r
- <map></map>\r
- </flow:value>\r
- </flow:ref>\r
- <flow:ref name="dummySet" targetClass="java.util.Set">\r
- <flow:value>\r
- <set></set>\r
- </flow:value>\r
- </flow:ref>\r
- <flow:ref name="dummyProperties" targetClass="java.util.Properties">\r
- <flow:value>\r
- <props></props>\r
- </flow:value>\r
- </flow:ref>\r
- \r
- </flow:spec>\r
-\r
-\r
- <flow:flow id="test.list.flowTemplate" abstract="true" spec="test.list.spec"\r
- path="/path">\r
- <bean parent="task.echo">\r
- <property name="message" value="list1=@{list1}, list2=@{list2}" />\r
- <flow:variable/>\r
- </bean> \r
-\r
- <bean parent="testRunTemplate">\r
- <property name="testData">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestData">\r
- <property name="expected">\r
- <flow:param name="list1"/>\r
- </property>\r
- <property name="reached">\r
- <flow:param name="list2"/>\r
- </property>\r
- </bean>\r
- </property> \r
- </bean>\r
- \r
- </flow:flow>\r
-\r
- <flow:flow id="test.list.flow1" parent="test.list.flowTemplate">\r
- <flow:arg name="list1">\r
- <list>\r
- <value>val1</value>\r
- <value>val2</value> \r
- </list>\r
- </flow:arg>\r
- <flow:arg name="list2">\r
- <list>\r
- <value>val1</value>\r
- <value>val2</value> \r
- </list>\r
- </flow:arg>\r
- \r
- <!-- not used in flow (just to test that the syntax is accepted): -->\r
- <flow:arg name="dummyMap">\r
- <map></map>\r
- </flow:arg>\r
- <flow:arg name="dummySet">\r
- <set></set>\r
- </flow:arg>\r
- <flow:arg name="dummyProperties">\r
- <props></props>\r
- </flow:arg> \r
- \r
- </flow:flow>\r
- \r
- <flow:flow id="test.list.flow2" parent="test.list.flowTemplate">\r
- <description>use default value for parameter "list1"</description>\r
- <flow:arg name="list2">\r
- <list>\r
- <value>val1</value>\r
- </list>\r
- </flow:arg>\r
- </flow:flow>\r
-\r
-\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:flow="http://www.argeo.org/schema/slc-flow"\r
- xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"\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-0.12.xsd">\r
-\r
- <bean id="testRun" class="org.argeo.slc.runtime.test.SimpleTestRun">\r
- <property name="testDefinition">\r
- <bean class="org.argeo.slc.runtime.test.BasicTestDefinition" />\r
- </property>\r
- <property name="testData">\r
- <flow:param name="refWithValue" />\r
- </property>\r
- <!-- <property name="testData">-->\r
- <!-- <bean parent="parameterRef">-->\r
- <!-- <constructor-arg value="refWithValue" />-->\r
- <!-- </bean>-->\r
- <!-- </property>-->\r
- <property name="testResult">\r
- <bean parent="slcDefault.test.basicSimpleTestResult" scope="execution">\r
- <property name="attributes">\r
- <map>\r
- <entry key="displayWithControl" value="@{displayWithControl}" />\r
- </map>\r
- </property>\r
- <aop:scoped-proxy />\r
- </bean>\r
- </property>\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.test.context;
-
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.BeanFactoryUtils;
-import org.springframework.beans.factory.ListableBeanFactory;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-/** Helper for tests using a Spring application context. */
-public abstract class AbstractInternalSpringTestCase extends TestCase {
- protected final CmsLog log = CmsLog.getLog(getClass());
- private ConfigurableApplicationContext context;
-
- /**
- * Gets (and create if necessary) the application context to use. Default
- * implementation uses a class path xml application context and calls
- * {@link #getApplicationContextLocation()}.
- */
- protected ConfigurableApplicationContext getContext() {
- if (context == null) {
- context = new ClassPathXmlApplicationContext(
- getApplicationContextLocation());
- }
- return context;
- }
-
- /** Returns a bean from the underlying context */
- @SuppressWarnings(value = { "unchecked" })
- protected <T> T getBean(String beanId) {
- return (T) getContext().getBean(beanId);
- }
-
- protected <T> T getBean(Class<? extends T> clss) {
- T bean = loadSingleFromContext(getContext(), clss);
- if (bean == null) {
- throw new SlcException("Cannot retrieve a unique bean of type "
- + clss);
- } else {
- return bean;
- }
- }
-
- /**
- * Th location of the application to load. The default implementation
- * returns <i>applicationContext.xml</i> found in the same package as the
- * test.
- */
- protected String getApplicationContextLocation() {
- return inPackage("applicationContext.xml");
- }
-
- /**
- * Prefixes the package of the class after converting the '.' to '/' in
- * order to have a resource path.
- */
- protected String inPackage(String suffix) {
- String prefix = getClass().getPackage().getName().replace('.', '/');
- return prefix + '/' + suffix;
- }
-
- @SuppressWarnings(value = { "unchecked" })
- protected <T> T loadSingleFromContext(ListableBeanFactory context,
- Class<T> clss) {
- Map<String, T> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, clss, false, false);
- if (beans.size() == 1) {
- return beans.values().iterator().next();
- } else if (beans.size() > 1) {
- if (log.isDebugEnabled()) {
- log
- .debug(("Found more that on bean for type " + clss
- + ": " + beans.keySet()));
- }
- return null;
- } else {
- return null;
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.test.context;
-
-import java.util.List;
-
-import org.argeo.slc.runtime.test.ContextUtils;
-import org.argeo.slc.runtime.test.SimpleTestResult;
-import org.argeo.slc.test.TestResultPart;
-import org.argeo.slc.test.TestStatus;
-import org.argeo.slc.test.context.ContextAware;
-
-public class ContextTest extends AbstractInternalSpringTestCase {
-
- public void testComplexContext() {
- SimpleTestResult testResult = new SimpleTestResult();
- ContextUtils.compareReachedExpected(
- (ContextAware) getBean("context.c1"), testResult);
- ContextUtils.compareReachedExpected(
- (ContextAware) getBean("context.c2"), testResult);
- ContextUtils.compareReachedExpected(
- (ContextAware) getBean("context.c3"), testResult);
-
- List<TestResultPart> parts = testResult.getParts();
- assertEquals(6, parts.size());
- assertEquals(TestStatus.PASSED, parts.get(0).getStatus());
- assertEquals(TestStatus.PASSED, parts.get(1).getStatus());
- assertEquals(TestStatus.PASSED, parts.get(2).getStatus());
- assertEquals(TestStatus.FAILED, parts.get(3).getStatus());
- assertEquals(TestStatus.PASSED, parts.get(4).getStatus());
- assertEquals(TestStatus.PASSED, parts.get(5).getStatus());
- }
-}
+++ /dev/null
-<?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
-<beans xmlns="http://www.springframework.org/schema/beans"\r
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">\r
-\r
- <bean id="parentContext.pc1" parent="parentContext.template">\r
- <property name="values">\r
- <map>\r
- <entry key="rootvar" value="text" />\r
- </map>\r
- </property>\r
- <property name="expectedValues">\r
- <map>\r
- <entry key="reference" value="20" />\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="context.c1" parent="context.template">\r
- <property name="parentContext" ref="parentContext.pc1" />\r
- <property name="values">\r
- <map>\r
- <entry key="reference" value="20" />\r
- <entry key="any" value="999" />\r
- <entry key="skipped" value="999" />\r
- </map>\r
- </property>\r
- <property name="expectedValues">\r
- <map>\r
- <entry key="reference" value="21" />\r
- <entry key="any" value="*" />\r
- <entry key="skipped" value="!" />\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="context.c2" parent="context.template">\r
- <property name="parentContext" ref="parentContext.pc1" />\r
- <property name="values">\r
- <map>\r
- <entry key="var" value="37" />\r
- <entry key="bad" value="56" />\r
- </map>\r
- </property>\r
- <property name="expectedValues">\r
- <map>\r
- <entry key="var" value="37" />\r
- <entry key="bad" value="57" />\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="parentContext.pc2" parent="parentContext.template">\r
- <property name="parentContext" ref="parentContext.pc1" />\r
- <property name="expectedValues">\r
- <map>\r
- <entry key="reference" value="40" />\r
- </map>\r
- </property>\r
- </bean>\r
-\r
- <bean id="context.c3" parent="context.template">\r
- <property name="parentContext" ref="parentContext.pc2" />\r
- <property name="values">\r
- <map>\r
- <entry key="reference" value="41" />\r
- <entry key="rootvar" value="textX" />\r
- </map>\r
- </property>\r
- <property name="expectedValues">\r
- <map>\r
- <entry key="reference" value="40" />\r
- <entry key="rootvar" value="text" />\r
- </map>\r
- </property>\r
- </bean>\r
-\r
-\r
- <bean id="parentContext.template"\r
- class="org.argeo.slc.core.test.context.SimpleParentContextAware"\r
- abstract="true">\r
- </bean>\r
-\r
- <bean id="context.template"\r
- class="org.argeo.slc.core.test.context.SimpleContextAware"\r
- abstract="true">\r
- </bean>\r
-</beans>
\ No newline at end of file
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.spring</artifactId>
- <name>SLC Spring Runtime</name>
- <dependencies>
- <!-- Commons -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.cms.jcr</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- <!-- Commons -->
- <dependency>
- <groupId>org.argeo.commons</groupId>
- <artifactId>org.argeo.init</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- SLC -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.api</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.jcr</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.repo</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
-
- <!-- Spring -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.expression</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.io</artifactId>
- </dependency>
-
- <!-- Ant -->
- <dependency>
- <groupId>org.argeo.tp.apache.ant</groupId>
- <artifactId>org.apache.ant</artifactId>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.ant;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.slc.core.execution.AbstractExecutionFlowGenerator;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.core.io.Resource;
-
-public class AntFlowGenerator extends AbstractExecutionFlowGenerator {
- private List<Resource> antFiles = new ArrayList<Resource>();
-
- protected Map<String, BeanDefinition> createExecutionFlowDefinitions(
- ConfigurableListableBeanFactory beanFactory) {
- Map<String, BeanDefinition> definitions = new HashMap<String, BeanDefinition>();
-
- for (Resource antFile : antFiles) {
- AntRun antRun = new AntRun();
- antRun.setBuildFile(antFile);
-
- List<Runnable> executables = new ArrayList<Runnable>();
- executables.add(antRun);
- definitions.put("ant." + antFile.getFilename(),
- createDefaultFlowDefinition(executables));
- }
- return definitions;
- }
-
- public void setAntFiles(List<Resource> antFiles) {
- this.antFiles = antFiles;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.ant;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import org.apache.tools.ant.BuildEvent;
-import org.apache.tools.ant.BuildListener;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.ProjectHelper;
-import org.apache.tools.ant.helper.ProjectHelper2;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-
-public class AntRun implements Runnable {
- private final static CmsLog log = CmsLog.getLog(AntRun.class);
-
- private Resource buildFile;
- private File baseDir;
-
- private List<String> targets = new ArrayList<String>();
- private Map<Object, Object> properties = new HashMap<Object, Object>();
-
- public void run() {
- Project project = new Project();
-
- try {
- String path = buildFile.getURL().getPath();
- project.setUserProperty("ant.file", path);
- project.setBaseDir(extractBaseDir(path));
-
- project.init();
- ProjectHelper projectHelper = new ProjectHelper2();
- project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE,
- projectHelper);
- projectHelper.parse(project, buildFile.getURL());
- } catch (Exception e) {
- throw new SlcException("Could not parse " + buildFile, e);
- }
-
- if (properties != null) {
- for (Map.Entry<Object, Object> entry : properties.entrySet()) {
- project.setUserProperty(entry.getKey().toString(), entry
- .getValue().toString());
- }
- }
-
- project.fireBuildStarted();
- Throwable exception = null;
- try {
- project.addBuildListener(new LoggingListener());
- if (targets.size() == 0) {
- project.executeTarget(project.getDefaultTarget());
- } else {
- project.executeTargets(new Vector<String>(targets));
- }
- } catch (Throwable e) {
- exception = e;
- throw new SlcException("Could not run Ant script " + buildFile, e);
- } finally {
- project.fireBuildFinished(exception);
- }
- }
-
- private File extractBaseDir(String path) {
- if(this.baseDir!=null)
- return this.baseDir;
-
- String baseDir = null;
- if (path.length() > 1) {
- int indx = path.lastIndexOf('/', path.length() - 1);
- if (indx == -1 || indx == 0) {
- baseDir = "/";
- } else {
- baseDir = path.substring(0, indx) + "/";
- }
- } else {
- baseDir = "/";
- }
- File file = new File(baseDir);
- if (file.exists()) {
- return file;
- } else {
- return new File(System.getProperty("user.dir"));
- }
- }
-
- public void setBuildFile(Resource buildFile) {
- this.buildFile = buildFile;
- }
-
- public void setTargets(List<String> targets) {
- this.targets = targets;
- }
-
- public void setProperties(Map<Object, Object> properties) {
- this.properties = properties;
- }
-
- public void setBaseDir(File baseDir) {
- this.baseDir = baseDir;
- }
-
- protected static class LoggingListener implements BuildListener {
-
- public void buildFinished(BuildEvent event) {
- if (log.isDebugEnabled())
- log.debug("Ant build finished: " + event);
- }
-
- public void buildStarted(BuildEvent event) {
- if (log.isDebugEnabled())
- log.debug("Ant build started: " + event);
- }
-
- public void messageLogged(BuildEvent event) {
- if (event.getPriority() == Project.MSG_DEBUG) {
- if (log.isTraceEnabled())
- log.trace(event.getMessage());
- } else if (event.getPriority() == Project.MSG_VERBOSE) {
- if (log.isDebugEnabled())
- log.debug(event.getMessage());
- } else if (event.getPriority() == Project.MSG_INFO) {
- log.info(event.getMessage());
-
- } else if (event.getPriority() == Project.MSG_WARN) {
- log.warn(event.getMessage());
-
- } else if (event.getPriority() == Project.MSG_ERR) {
- log.error(event.getMessage());
- } else {
- log.error(event.getMessage());
- }
- }
-
- public void targetFinished(BuildEvent event) {
- if (log.isTraceEnabled())
- log.debug("Target finished: " + event.getTarget());
- }
-
- public void targetStarted(BuildEvent event) {
- if (log.isTraceEnabled())
- log.debug("Target started: " + event.getTarget());
- }
-
- public void taskFinished(BuildEvent event) {
- }
-
- public void taskStarted(BuildEvent event) {
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.core.attachment;
-
-import org.argeo.slc.attachment.Attachment;
-import org.springframework.core.io.Resource;
-
-public interface AttachmentUploader {
- public void upload(Attachment attachment, Resource resource);
-}
+++ /dev/null
-package org.argeo.slc.core.attachment;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.attachment.Attachment;
-import org.argeo.slc.attachment.AttachmentsStorage;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.core.io.Resource;
-
-public class FileAttachmentsStorage implements AttachmentsStorage,
- AttachmentUploader, InitializingBean {
- private final static CmsLog log = CmsLog
- .getLog(FileAttachmentsStorage.class);
-
- private File attachmentsDirectory;
-
- private String attachmentsTocFileName = "attachmentsToc.csv";
-
- private DateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
- private DateFormat dateFormatTime = new SimpleDateFormat("HH:mm:ss");
-
- public void afterPropertiesSet() {
- if (attachmentsDirectory == null) {
-
- String osgiInstanceArea = System.getProperty("osgi.instance.area");
- if (osgiInstanceArea != null) {
- if (osgiInstanceArea.startsWith("file:"))
- osgiInstanceArea = osgiInstanceArea.substring("file:"
- .length());
- attachmentsDirectory = new File(osgiInstanceArea
- + File.separator + "slcAttachments");
- }
-
- if (attachmentsDirectory == null) {
- String tempDir = System.getProperty("java.io.tmpdir");
- attachmentsDirectory = new File(tempDir + File.separator
- + "slcAttachments");
- }
- }
- if (!attachmentsDirectory.exists())
- attachmentsDirectory.mkdirs();
- if (log.isDebugEnabled())
- log.debug("File attachment storage initialized in directory "
- + attachmentsDirectory);
- }
-
- public void retrieveAttachment(Attachment attachment,
- OutputStream outputStream) {
- File file = getFile(attachment);
- InputStream in = null;
- try {
- byte[] buffer = new byte[1024 * 1024];
- in = new FileInputStream(file);
- int read = -1;
- while ((read = in.read(buffer)) >= 0) {
- outputStream.write(buffer, 0, read);
- }
- if (log.isTraceEnabled())
- log.trace("Read " + attachment + " from " + file);
- } catch (IOException e) {
- throw new SlcException("Cannot write attachment " + attachment
- + " to " + file, e);
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
-
- public void storeAttachment(Attachment attachment, InputStream inputStream) {
- File file = getFile(attachment);
- FileOutputStream out = null;
- try {
- byte[] buffer = new byte[1024 * 1024];
- out = new FileOutputStream(file);
- int read = -1;
- while ((read = inputStream.read(buffer)) >= 0) {
- out.write(buffer, 0, read);
- }
- if (log.isTraceEnabled())
- log.trace("Wrote " + attachment + " to " + file);
- updateAttachmentToc(attachment, file);
- } catch (IOException e) {
- throw new SlcException("Cannot write attachment " + attachment
- + " to " + file, e);
- } finally {
- IOUtils.closeQuietly(out);
- }
-
- }
-
- public void upload(Attachment attachment, Resource resource) {
- try {
- storeAttachment(attachment, resource.getInputStream());
- } catch (IOException e) {
- throw new SlcException("Cannot upload attachment " + attachment, e);
- }
- }
-
- /** For monitoring purposes only */
- protected void updateAttachmentToc(Attachment attachment, File file) {
- Date date = new Date(file.lastModified());
- FileWriter writer = null;
- try {
- writer = new FileWriter(attachmentsDirectory + File.separator
- + attachmentsTocFileName, true);
- writer.append(dateFormatDay.format(date));
- writer.append(',');
- writer.append(dateFormatTime.format(date));
- writer.append(',');
- writer.append(attachment.getUuid());
- writer.append(',');
- writer.append(attachment.getName());
- writer.append(',');
- writer.append(attachment.getContentType());
- writer.append(',');
- writer.append(Long.toString(file.length()));
- writer.append(',');
- writer.append(file.getCanonicalPath());
- writer.append('\n');
- } catch (IOException e) {
- log.warn("Could not update attachments TOC for " + attachment
- + " and file " + file, e);
- } finally {
- IOUtils.closeQuietly(writer);
- }
-
- }
-
- protected File getFile(Attachment attachment) {
- File file = new File(attachmentsDirectory + File.separator
- + attachment.getUuid());
- return file;
- }
-
- public void setAttachmentsDirectory(File attachmentsDirectory) {
- this.attachmentsDirectory = attachmentsDirectory;
- }
-
- public void setAttachmentsTocFileName(String attachmentsTocFileName) {
- this.attachmentsTocFileName = attachmentsTocFileName;
- }
-
- public void setDateFormatDay(DateFormat dateFormatDay) {
- this.dateFormatDay = dateFormatDay;
- }
-
- public void setDateFormatTime(DateFormat dateFormatTime) {
- this.dateFormatTime = dateFormatTime;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.attachment;
-
-import java.io.Serializable;
-import java.util.UUID;
-
-import org.argeo.slc.attachment.Attachment;
-
-public class SimpleAttachment implements Attachment, Serializable {
- private static final long serialVersionUID = 6615155908800610606L;
- private String uuid = UUID.randomUUID().toString();
- private String name;
- private String contentType = "";
-
- public SimpleAttachment() {
- }
-
- public SimpleAttachment(String uuid, String name, String contentType) {
- super();
- this.uuid = uuid;
- this.name = name;
- this.contentType = contentType;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getContentType() {
- return contentType;
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- public String toString() {
- return "Attachment #" + uuid + "(" + name + ", " + contentType + ")";
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof Attachment) {
- Attachment attachment = (Attachment) obj;
- if (uuid != null && attachment.getUuid() != null)
- return uuid.equals(attachment.getUuid());
-
- if (name != null && attachment.getName() != null)
- return name.equals(attachment.getName());
-
- return hashCode() == attachment.hashCode();
- }
- return false;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.build;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.StreamReadable;
-import org.argeo.slc.build.Distribution;
-import org.springframework.core.io.Resource;
-
-/** A software distribution archive accessible via a {@link Resource}. */
-public class ResourceDistribution implements Distribution, StreamReadable {
- private Resource resource;
-
- public ResourceDistribution() {
- }
-
- public ResourceDistribution(Resource location) {
- this.resource = location;
- }
-
- public String getDistributionId() {
- return resource.toString();
- }
-
- public Resource getResource() {
- return resource;
- }
-
- public void setResource(Resource resource) {
- this.resource = resource;
- }
-
- public InputStream getInputStream() {
- try {
- return resource.getInputStream();
- } catch (IOException e) {
- throw new SlcException("Cannot get input stream", e);
- }
- }
-
- @Override
- public String toString() {
- return resource.toString();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.build;
-
-import java.util.StringTokenizer;
-
-/**
- * <p>
- * An implementation of the distribution id using the standard
- * Major.Minor.Release notation. And additional arbitrary string can also be
- * added.
- * </p>
- *
- * <p>
- * <b>Examples:</b><br>
- * 0.2.6<br>
- * 2.4.12.RC1
- * </p>
- */
-public class VersionDistributionId {
-
- private Integer major;
- private Integer minor;
- private Integer release;
- private String additional;
-
- /** Parse the provided string in order to set the various components. */
- public void setVersionString(String str) {
- StringTokenizer st = new StringTokenizer(str, ".");
- if (st.hasMoreTokens())
- major = Integer.parseInt(st.nextToken());
- if (st.hasMoreTokens())
- minor = Integer.parseInt(st.nextToken());
- if (st.hasMoreTokens())
- release = Integer.parseInt(st.nextToken());
- if (st.hasMoreTokens())
- additional = st.nextToken();
- }
-
- public Integer getMajor() {
- return major;
- }
-
- public void setMajor(Integer major) {
- this.major = major;
- }
-
- public Integer getMinor() {
- return minor;
- }
-
- public void setMinor(Integer minor) {
- this.minor = minor;
- }
-
- public Integer getRelease() {
- return release;
- }
-
- public void setRelease(Integer release) {
- this.release = release;
- }
-
- public String getAdditional() {
- return additional;
- }
-
- public void setAdditional(String additional) {
- this.additional = additional;
- }
-
- @Override
- public boolean equals(Object obj) {
- // TODO Auto-generated method stub
- return super.equals(obj);
- }
-
- @Override
- public String toString() {
- return major + "." + minor + "." + release
- + (additional != null ? "." + additional : "");
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.build;
-
-import org.argeo.slc.NameVersion;
-import org.springframework.core.io.Resource;
-
-/**
- * The distribution of a software package (jar, zip, RPM, etc.) which is
- * versioned. The archive itself is accessible via a {@link Resource}.
- */
-public class VersionedResourceDistribution extends ResourceDistribution
- implements NameVersion {
- private String name;
- private String version;
-
- public VersionedResourceDistribution() {
- super();
- }
-
- public VersionedResourceDistribution(NameVersion nameVersion,
- Resource resource) {
- this(nameVersion.getName(), nameVersion.getVersion(), resource);
- }
-
- public VersionedResourceDistribution(String name, String version,
- Resource resource) {
- super(resource);
- this.name = name;
- this.version = version;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
-}
+++ /dev/null
-<html>\r
-<head></head>\r
-<body>\r
-SLC Build: building of software systems.\r
-</body>\r
-</html>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.TreeMap;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.context.ResourceLoaderAware;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.ResourceLoader;
-import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
-import org.springframework.core.io.support.ResourcePatternResolver;
-import org.springframework.util.AntPathMatcher;
-import org.springframework.util.PathMatcher;
-
-public class DefaultResourceSet implements ResourceLoaderAware,
- InitializingBean, ResourceSet {
- private final static CmsLog log = CmsLog.getLog(DefaultResourceSet.class);
- public final static String DEFAULT_EXCLUDES = "**/.svn/**";
-
- private String base;
- private String include;
- private List<String> includes = new ArrayList<String>();
- private String exclude;
- private List<String> excludes = new ArrayList<String>();
- private Boolean useDefaultExcludes = true;
- private ResourcePatternResolver resourcePatternResolver;
- private PathMatcher excludePathMatcher = new AntPathMatcher();
-
- private ResourceLoader resourceLoader;
-
- /** List the resources, identified by their relative path. */
- public Map<String, Resource> listResources() {
- try {
- Map<String, Resource> res = new TreeMap<String, Resource>();
- if (base == null)
- return res;
- String baseResUrl = getResourceLoaderToUse().getResource(base)
- .getURL().toString();
- for (String includePattern : includes)
- processInclude(res, includePattern, baseResUrl);
- return res;
- } catch (IOException e) {
- throw new SlcException("Cannot list resource from " + base, e);
- }
- }
-
- protected void processInclude(Map<String, Resource> res, String include,
- String baseResUrl) throws IOException {
- String pattern = base + "/" + include;
- if (log.isTraceEnabled())
- log.trace("Look for resources with pattern '" + pattern
- + "' in base url " + baseResUrl);
- Resource[] resources = resourcePatternResolver.getResources(pattern);
- resources: for (Resource resource : resources) {
- String url = resource.getURL().toString();
- String relPath = url.substring(baseResUrl.length());
-
- // skip dir
- if (relPath.charAt(relPath.length() - 1) == '/') {
- if (log.isTraceEnabled())
- log.trace("Skip directory " + relPath + "=" + resource);
- continue resources;
- }
-
- // make sure there is not starting '/'
- if (relPath.charAt(0) == '/')
- relPath = relPath.substring(1);
-
- // skip excludes
- for (String exclude : excludes)
- if (excludePathMatcher.match(exclude, relPath)) {
- if (log.isTraceEnabled())
- log.trace("Exclude " + relPath + "=" + resource);
- continue resources;
- }
-
- // check if already exists
- if (res.containsKey(relPath))
- log.warn(relPath + " already matched by " + res.get(relPath)
- + ", " + resource + " will override it.");
-
- // store the marched resource
- res.put(relPath, resource);
- if (log.isTraceEnabled())
- log.trace(relPath + "=" + resource);
- }
-
- }
-
- public void afterPropertiesSet() throws Exception {
- if (resourcePatternResolver == null)
- resourcePatternResolver = new PathMatchingResourcePatternResolver(
- getResourceLoaderToUse());
- if (include != null)
- addCommaSeparatedToList(include, includes);
- if (exclude != null)
- addCommaSeparatedToList(exclude, excludes);
-
- if (includes.size() == 0)
- includes.add("**");
-
- if (useDefaultExcludes)
- addCommaSeparatedToList(DEFAULT_EXCLUDES, excludes);
- }
-
- private void addCommaSeparatedToList(String str, List<String> lst) {
- StringTokenizer st = new StringTokenizer(str, ",");
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (!lst.contains(token))
- lst.add(token);
- }
- }
-
- public void setResourceLoader(ResourceLoader resourceLoader) {
- this.resourceLoader = resourceLoader;
- }
-
- /**
- * Can be overridden in order to provide the proper resource loader used to
- * resolve resources.
- */
- public ResourceLoader getResourceLoaderToUse() {
- return resourceLoader;
- }
-
- public void setBase(String base) {
- this.base = base;
- }
-
- public void setInclude(String include) {
- this.include = include;
- }
-
- public void setIncludes(List<String> includes) {
- this.includes = includes;
- }
-
- public void setExclude(String exclude) {
- this.exclude = exclude;
- }
-
- public void setExcludes(List<String> excludes) {
- this.excludes = excludes;
- }
-
- public void setUseDefaultExcludes(Boolean useDefaultExcludes) {
- this.useDefaultExcludes = useDefaultExcludes;
- }
-
- public void setExcludePathMatcher(PathMatcher excludePathMatcher) {
- this.excludePathMatcher = excludePathMatcher;
- }
-
- public void setResourcePatternResolver(
- ResourcePatternResolver resourcePatternResolver) {
- this.resourcePatternResolver = resourcePatternResolver;
- }
-
- public ResourcePatternResolver getResourcePatternResolver() {
- return resourcePatternResolver;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-import org.springframework.util.DigestUtils;
-
-/** Add Spring capabilities to {@link DigestUtils} */
-public class DigestCheck extends DigestUtils {
- public static String digest(String algorithm, Resource resource) {
- try {
- File file = resource.getFile();
- return org.argeo.util.DigestUtils.digest(algorithm, file);
- } catch (IOException e) {
- try {
- return org.argeo.util.DigestUtils.digest(algorithm,
- resource.getInputStream());
- } catch (IOException e1) {
- throw new SlcException("Cannot digest " + resource
- + " with algorithm " + algorithm, e);
- }
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Map;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-
-public class LocalFilesDeployment implements Runnable {
- private String targetBase = "";
- private ResourceSet resourceSet;
-
- public LocalFilesDeployment() {
- }
-
- public LocalFilesDeployment(ResourceSet resourceSet) {
- this.resourceSet = resourceSet;
- }
-
- public void run() {
- Map<String, Resource> resources = resourceSet.listResources();
- for (String relPath : resources.keySet()) {
- File targetFile = new File(targetBase + File.separator + relPath);
- File parentDir = targetFile.getParentFile();
- if (!parentDir.exists())
- parentDir.mkdirs();
-
- Resource resource = resources.get(relPath);
-
- InputStream in = null;
- OutputStream out = null;
- try {
- in = resource.getInputStream();
- out = FileUtils.openOutputStream(targetFile);
- IOUtils.copy(in, out);
- } catch (IOException e) {
- throw new SlcException("Cannot extract " + resource + " to "
- + targetFile, e);
- } finally {
- IOUtils.closeQuietly(in);
- IOUtils.closeQuietly(out);
- }
- }
- }
-
- public void setTargetBase(String targetBase) {
- this.targetBase = targetBase;
- }
-
- public void setResourceSet(ResourceSet resourceSet) {
- this.resourceSet = resourceSet;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.core.io.Resource;
-
-public class MultiResourceSet implements ResourceSet {
- private List<ResourceSet> resourceSets = new ArrayList<ResourceSet>();
-
- public Map<String, Resource> listResources() {
- Map<String, Resource> res = new HashMap<String, Resource>();
- for (ResourceSet resourceSet : resourceSets) {
- res.putAll(resourceSet.listResources());
- }
- return res;
- }
-
- /** Last listed override previous for the same relative paths. */
- public void setResourceSets(List<ResourceSet> resourceSets) {
- this.resourceSets = resourceSets;
- }
-
- public List<ResourceSet> getResourceSets() {
- return resourceSets;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.util.Map;
-
-import org.springframework.core.io.Resource;
-
-public interface ResourceSet {
- /**
- * List the resources, identified by their relative path. Relative paths
- * must NOT start with a '/'.
- */
- public Map<String, Resource> listResources();
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.io.File;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.InstalledExecutables;
-import org.argeo.slc.deploy.TargetData;
-
-public class SimpleExecutables implements InstalledExecutables {
- private final static CmsLog log = CmsLog.getLog(SimpleExecutables.class);
-
- private String baseDir;
- private Map<String, String> paths = new TreeMap<String, String>();
-
- private Distribution distribution;
-
- public String getExecutablePath(String key) {
- String path = paths.get(key);
- if (path == null) {
- if (log.isDebugEnabled())
- log.debug("No executable path found for key " + key
- + ", using the key as executable name.");
- path = key;
- }
-
- if (baseDir != null)
- path = baseDir + File.separator + path;
- return path;
- }
-
- public String getDeployedSystemId() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public DeploymentData getDeploymentData() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Distribution getDistribution() {
- return distribution;
- }
-
- public TargetData getTargetData() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public String getBaseDir() {
- return baseDir;
- }
-
- public void setBaseDir(String baseDir) {
- this.baseDir = baseDir;
- }
-
- public Map<String, String> getPaths() {
- return paths;
- }
-
- public void setPaths(Map<String, String> paths) {
- this.paths = paths;
- }
-
- public void setDistribution(Distribution distribution) {
- this.distribution = distribution;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.deploy;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.commons.io.FileUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.deploy.VersioningDriver;
-
-/**
- * Synchronizes an URL to a local directory, taking into account versioning
- * information if possible.
- */
-public class VersionedDirSync implements Runnable {
- private final static CmsLog log = CmsLog.getLog(VersionedDirSync.class);
-
- private VersioningDriver versioningDriver;
- private File dir;
- private String url;
- private Boolean clean = false;
-
- private Boolean changed = null;
-
- public void run() {
- changed = null;
- if (clean) {
- try {
- log.info("Clean " + dir);
- FileUtils.deleteDirectory(dir);
- } catch (IOException e) {
- throw new SlcException("Cannot delete checkout directory "
- + dir, e);
- }
- dir.mkdirs();
- }
- log.info("Checkout " + url + " to " + dir);
- changed = versioningDriver.checkout(url, dir, true);
- if (log.isDebugEnabled())
- log.debug("Synchronized " + url + " to " + dir);
- }
-
- public void setVersioningDriver(VersioningDriver versioningDriver) {
- this.versioningDriver = versioningDriver;
- }
-
- public void setDir(File dir) {
- this.dir = dir;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- /** Delete before checkout */
- public void setClean(Boolean clean) {
- this.clean = clean;
- }
-
- /** Whether last call has changed the directory */
- public Boolean getChanged() {
- if (changed == null)
- throw new SlcException("Sync has not run");
- return changed;
- }
-
-}
+++ /dev/null
-<html>\r
-<head></head>\r
-<body>\r
-SLC Deploy: deployment of software systems.\r
-</body>\r
-</html>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.MutablePropertyValues;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-import org.springframework.beans.factory.support.GenericBeanDefinition;
-import org.springframework.core.Ordered;
-import org.springframework.core.PriorityOrdered;
-
-public abstract class AbstractExecutionFlowGenerator implements
- BeanFactoryPostProcessor, PriorityOrdered {
- private final CmsLog log = CmsLog.getLog(getClass());
-
- protected abstract Map<String, BeanDefinition> createExecutionFlowDefinitions(
- ConfigurableListableBeanFactory beanFactory);
-
- public void postProcessBeanFactory(
- ConfigurableListableBeanFactory beanFactory) throws BeansException {
- if (!(beanFactory instanceof BeanDefinitionRegistry)) {
- throw new SlcException("Can only work on "
- + BeanDefinitionRegistry.class);
- }
-
- Map<String, BeanDefinition> definitions = createExecutionFlowDefinitions(beanFactory);
-
- for (String beanName : definitions.keySet()) {
- if (log.isTraceEnabled())
- log.debug("Registering execution flow " + beanName);
- ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(
- beanName, definitions.get(beanName));
- }
- }
-
- protected GenericBeanDefinition createDefaultFlowDefinition(
- List<Runnable> executables) {
- GenericBeanDefinition bd = new GenericBeanDefinition();
- bd.setBeanClass(DefaultExecutionFlow.class);
-
- MutablePropertyValues mpv = new MutablePropertyValues();
- mpv.addPropertyValue("executables", executables);
-
- bd.setPropertyValues(mpv);
- return bd;
- }
-
- public int getOrder() {
- return Ordered.HIGHEST_PRECEDENCE;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.slc.execution.ExecutionModule;
-
-@Deprecated
-public abstract class AbstractSpringExecutionModule implements ExecutionModule
- {
-/*
- protected ApplicationContext applicationContext;
-
- protected ExecutionContext executionContext;
-
- protected ExecutionFlowDescriptorConverter descriptorConverter = new DefaultDescriptorConverter();
-
- public ExecutionModuleDescriptor getDescriptor() {
- ExecutionModuleDescriptor md = new ExecutionModuleDescriptor();
- md.setName(getName());
- md.setVersion(getVersion());
-
- Map<String, ExecutionFlow> executionFlows = listFlows();
- for (String name : executionFlows.keySet()) {
- ExecutionFlow executionFlow = executionFlows.get(name);
-
- Assert.notNull(executionFlow.getName());
- Assert.state(name.equals(executionFlow.getName()));
-
- ExecutionSpec executionSpec = executionFlow.getExecutionSpec();
- Assert.notNull(executionSpec);
- Assert.notNull(executionSpec.getName());
-
- Map<String, Object> values = new TreeMap<String, Object>();
- for (String key : executionSpec.getAttributes().keySet()) {
- ExecutionSpecAttribute attribute = executionSpec
- .getAttributes().get(key);
-
- if (executionFlow.isSetAsParameter(key)) {
- Object value = executionFlow.getParameter(key);
- if (attribute instanceof PrimitiveSpecAttribute) {
- PrimitiveValue primitiveValue = new PrimitiveValue();
- primitiveValue
- .setType(((PrimitiveSpecAttribute) attribute)
- .getType());
- primitiveValue.setValue(value);
- values.put(key, primitiveValue);
- } else if (attribute instanceof RefSpecAttribute) {
- RefValue refValue = new RefValue();
- if (value instanceof ScopedObject) {
- refValue.setLabel("RUNTIME "
- + value.getClass().getName());
- } else {
- refValue.setLabel("STATIC "
- + value.getClass().getName());
- }
- values.put(key, refValue);
- } else if (attribute instanceof ResourceSpecAttribute) {
- PrimitiveValue primitiveValue = new PrimitiveValue();
- primitiveValue
- .setType(((ResourceSpecAttribute) attribute)
- .getType());
- primitiveValue.setValue(value);
- values.put(key, primitiveValue);
- } else {
- throw new SlcException("Unkown spec attribute type "
- + attribute.getClass());
- }
- }
-
- }
-
- ExecutionFlowDescriptor efd = new ExecutionFlowDescriptor(name,
- values, executionSpec);
- if (executionFlow.getPath() != null)
- efd.setPath(executionFlow.getPath());
-
- // Add execution spec if necessary
- if (!md.getExecutionSpecs().contains(executionSpec))
- md.getExecutionSpecs().add(executionSpec);
-
- // Add execution flow
- md.getExecutionFlows().add(efd);
- }
-
- return md;
- }
-
- protected Map<String, ExecutionFlow> listFlows() {
- GenericBeanFactoryAccessor accessor = new GenericBeanFactoryAccessor(
- applicationContext);
- Map<String, ExecutionFlow> executionFlows = accessor
- .getBeansOfType(ExecutionFlow.class);
- return executionFlows;
- }
-
- public void execute(ExecutionFlowDescriptor executionFlowDescriptor) {
- if (descriptorConverter != null)
- executionContext.addVariables(descriptorConverter
- .convertValues(executionFlowDescriptor));
- ExecutionFlow flow = (ExecutionFlow) applicationContext.getBean(
- executionFlowDescriptor.getName(), ExecutionFlow.class);
- flow.run();
- }
-
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.applicationContext = applicationContext;
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- public void setDescriptorConverter(
- ExecutionFlowDescriptorConverter descriptorConverter) {
- this.descriptorConverter = descriptorConverter;
- }*/
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-/** Implements the base methods of an SLC agent. */
-@Deprecated
-public class DefaultAgent extends org.argeo.slc.runtime.DefaultAgent {
-
- public DefaultAgent() {
- super();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-/**
- * Authenticates thread and executes synchronously a command line execution.
- * Reference implementation of args to URIs algorithm.
- */
-@Deprecated
-public class DefaultAgentCli extends org.argeo.slc.runtime.DefaultAgentCli {
-
- public DefaultAgentCli() {
- super();
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.Map;
-
-import org.argeo.slc.execution.ExecutionSpec;
-import org.springframework.beans.factory.BeanNameAware;
-import org.springframework.beans.factory.InitializingBean;
-
-/** Default implementation of an execution flow. */
-@Deprecated
-public class DefaultExecutionFlow extends org.argeo.slc.runtime.DefaultExecutionFlow
- implements InitializingBean, BeanNameAware {
- public DefaultExecutionFlow() {
- super();
- }
-
- public DefaultExecutionFlow(ExecutionSpec executionSpec, Map<String, Object> parameters) {
- super(executionSpec, parameters);
- }
-
- public DefaultExecutionFlow(ExecutionSpec executionSpec) {
- super(executionSpec);
- }
-
- public void afterPropertiesSet() throws Exception {
- init();
- }
-
- public void setBeanName(String name) {
- setName(name);
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.TreeSet;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionFlowDescriptor;
-import org.argeo.slc.execution.ExecutionFlowDescriptorConverter;
-import org.argeo.slc.execution.ExecutionModuleDescriptor;
-import org.argeo.slc.execution.ExecutionSpec;
-import org.argeo.slc.execution.ExecutionSpecAttribute;
-import org.argeo.slc.execution.FlowConfigurationException;
-import org.argeo.slc.execution.RefSpecAttribute;
-import org.argeo.slc.execution.RefValue;
-import org.argeo.slc.primitive.PrimitiveSpecAttribute;
-import org.argeo.slc.primitive.PrimitiveUtils;
-import org.argeo.slc.primitive.PrimitiveValue;
-import org.springframework.aop.scope.ScopedObject;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.util.StringUtils;
-
-/**
- * Performs conversion in both direction between data exchanged with the agent
- * and the data in the application context.
- */
-public class DefaultExecutionFlowDescriptorConverter implements
- ExecutionFlowDescriptorConverter, ApplicationContextAware {
- public final static String REF_VALUE_TYPE_BEAN_NAME = "beanName";
-
- /** Workaround for https://www.spartadn.com/bugzilla/show_bug.cgi?id=206 */
- private final static String REF_VALUE_INTERNAL = "[internal]";
-
- private final static CmsLog log = CmsLog
- .getLog(DefaultExecutionFlowDescriptorConverter.class);
-
- private ApplicationContext applicationContext;
-
- @SuppressWarnings("unused")
- public Map<String, Object> convertValues(
- ExecutionFlowDescriptor executionFlowDescriptor) {
- Map<String, Object> values = executionFlowDescriptor.getValues();
- Map<String, Object> convertedValues = new HashMap<String, Object>();
- ExecutionSpec executionSpec = executionFlowDescriptor
- .getExecutionSpec();
-
- if (executionSpec == null && log.isTraceEnabled())
- log.warn("Execution spec is null for " + executionFlowDescriptor);
-
- if (values != null && executionSpec != null) {
- values: for (String key : values.keySet()) {
- ExecutionSpecAttribute attribute = executionSpec
- .getAttributes().get(key);
-
- if (attribute == null)
- throw new FlowConfigurationException(
- "No spec attribute defined for '" + key + "'");
-
- if (attribute.getIsConstant())
- continue values;
-
- Object value = values.get(key);
- if (value instanceof PrimitiveValue) {
- PrimitiveValue primitiveValue = (PrimitiveValue) value;
- // TODO: check class <=> type
- convertedValues.put(key, primitiveValue.getValue());
- } else if (value instanceof RefValue) {
- RefValue refValue = (RefValue) value;
- String type = refValue.getType();
- if (REF_VALUE_TYPE_BEAN_NAME.equals(type)) {
- // FIXME: UI should send all information about spec
- // - targetClass
- // - name
- // String executionSpecName = executionSpec.getName();
- // ExecutionSpec localSpec = (ExecutionSpec)
- // applicationContext
- // .getBean(executionSpecName);
- // RefSpecAttribute localAttr = (RefSpecAttribute)
- // localSpec
- // .getAttributes().get(key);
- // Class<?> targetClass = localAttr.getTargetClass();
- //
- // String primitiveType = PrimitiveUtils
- // .classAsType(targetClass);
- String primitiveType = null;
- if (primitiveType != null) {
- // not active
- String ref = refValue.getRef();
- Object obj = PrimitiveUtils.convert(primitiveType,
- ref);
- convertedValues.put(key, obj);
- } else {
- String ref = refValue.getRef();
- if (ref != null && !ref.equals(REF_VALUE_INTERNAL)) {
- Object obj = null;
- if (applicationContext.containsBean(ref)) {
- obj = applicationContext.getBean(ref);
- } else {
- // FIXME: hack in order to pass primitive
- obj = ref;
- }
- convertedValues.put(key, obj);
- } else {
- log.warn("Cannot interpret " + refValue);
- }
- }
- } else if (PrimitiveUtils.typeAsClass(type) != null) {
- String ref = refValue.getRef();
- Object obj = PrimitiveUtils.convert(type, ref);
- convertedValues.put(key, obj);
- } else {
- throw new FlowConfigurationException(
- "Ref value type not supported: "
- + refValue.getType());
- }
- } else {
- // default is to take the value as is
- convertedValues.put(key, value);
- }
- }
- }
- return convertedValues;
- }
-
- public void addFlowsToDescriptor(ExecutionModuleDescriptor md,
- Map<String, ExecutionFlow> executionFlows) {
- SortedSet<ExecutionFlowDescriptor> set = new TreeSet<ExecutionFlowDescriptor>(
- new ExecutionFlowDescriptorComparator());
- for (String name : executionFlows.keySet()) {
- ExecutionFlow executionFlow = executionFlows.get(name);
-
- ExecutionFlowDescriptor efd = getExecutionFlowDescriptor(executionFlow);
- ExecutionSpec executionSpec = efd.getExecutionSpec();
-
- // Add execution spec if necessary
- if (!md.getExecutionSpecs().contains(executionSpec))
- md.getExecutionSpecs().add(executionSpec);
-
- // Add execution flow
- set.add(efd);
- // md.getExecutionFlows().add(efd);
- }
- md.getExecutionFlows().addAll(set);
- }
-
- public ExecutionFlowDescriptor getExecutionFlowDescriptor(
- ExecutionFlow executionFlow) {
- if (executionFlow.getName() == null)
- throw new FlowConfigurationException("Flow name is null: "
- + executionFlow);
- String name = executionFlow.getName();
-
- ExecutionSpec executionSpec = executionFlow.getExecutionSpec();
- if (executionSpec == null)
- throw new FlowConfigurationException("Execution spec is null: "
- + executionFlow);
- if (executionSpec.getName() == null)
- throw new FlowConfigurationException(
- "Execution spec name is null: " + executionSpec);
-
- Map<String, Object> values = new TreeMap<String, Object>();
- for (String key : executionSpec.getAttributes().keySet()) {
- ExecutionSpecAttribute attribute = executionSpec.getAttributes()
- .get(key);
-
- if (attribute instanceof PrimitiveSpecAttribute) {
- if (executionFlow.isSetAsParameter(key)) {
- Object value = executionFlow.getParameter(key);
- PrimitiveValue primitiveValue = new PrimitiveValue();
- primitiveValue.setType(((PrimitiveSpecAttribute) attribute)
- .getType());
- primitiveValue.setValue(value);
- values.put(key, primitiveValue);
- } else {
- // no need to add a primitive value if it is not set,
- // all necessary information is in the spec
- }
- } else if (attribute instanceof RefSpecAttribute) {
- if (attribute.getIsConstant()) {
- values.put(key, new RefValue(REF_VALUE_INTERNAL));
- } else
- values.put(
- key,
- buildRefValue((RefSpecAttribute) attribute,
- executionFlow, key));
- } else {
- throw new FlowConfigurationException(
- "Unkown spec attribute type " + attribute.getClass());
- }
-
- }
-
- ExecutionFlowDescriptor efd = new ExecutionFlowDescriptor(name, null,
- values, executionSpec);
- // Takes description from spring
- BeanFactory bf = getBeanFactory();
- if (bf != null) {
- BeanDefinition bd = getBeanFactory().getBeanDefinition(name);
- efd.setDescription(bd.getDescription());
- }
- return efd;
- }
-
- protected RefValue buildRefValue(RefSpecAttribute rsa,
- ExecutionFlow executionFlow, String key) {
- RefValue refValue = new RefValue();
- // FIXME: UI should be able to deal with other types
- refValue.setType(REF_VALUE_TYPE_BEAN_NAME);
- Class<?> targetClass = rsa.getTargetClass();
- String primitiveType = PrimitiveUtils.classAsType(targetClass);
- if (primitiveType != null) {
- if (executionFlow.isSetAsParameter(key)) {
- Object value = executionFlow.getParameter(key);
- refValue.setRef(value.toString());
- }
- refValue.setType(primitiveType);
- return refValue;
- } else {
-
- if (executionFlow.isSetAsParameter(key)) {
- String ref = null;
- Object value = executionFlow.getParameter(key);
- if (applicationContext == null) {
- log.warn("No application context declared, cannot scan ref value.");
- ref = value.toString();
- } else {
-
- // look for a ref to the value
- Map<String, ?> beans = getBeanFactory()
- .getBeansOfType(targetClass, false, false);
- // TODO: also check scoped beans
- beans: for (String beanName : beans.keySet()) {
- Object obj = beans.get(beanName);
- if (value instanceof ScopedObject) {
- // don't call methods of the target of the scope
- if (obj instanceof ScopedObject)
- if (value == obj) {
- ref = beanName;
- break beans;
- }
- } else {
- if (obj.equals(value)) {
- ref = beanName;
- break beans;
- }
- }
- }
- }
- if (ref == null) {
- if (log.isTraceEnabled())
- log.trace("Cannot define reference for ref spec attribute "
- + key
- + " in "
- + executionFlow
- + " ("
- + rsa
- + ")."
- + " If it is an inner bean consider put it frozen.");
- ref = REF_VALUE_INTERNAL;
- } else {
- if (log.isTraceEnabled())
- log.trace(ref
- + " is the reference for ref spec attribute "
- + key + " in " + executionFlow + " (" + rsa
- + ")");
- }
- refValue.setRef(ref);
- }
- return refValue;
- }
- }
-
- /** @return can be null */
- private ConfigurableListableBeanFactory getBeanFactory() {
- if (applicationContext == null)
- return null;
- return ((ConfigurableApplicationContext) applicationContext)
- .getBeanFactory();
- }
-
- /** Must be use within the execution application context */
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.applicationContext = applicationContext;
- }
-
- private static class ExecutionFlowDescriptorComparator implements
- Comparator<ExecutionFlowDescriptor> {
- @SuppressWarnings("deprecation")
- public int compare(ExecutionFlowDescriptor o1,
- ExecutionFlowDescriptor o2) {
- // TODO: write unit tests for this
-
- String name1 = o1.getName();
- String name2 = o2.getName();
-
- String path1 = o1.getPath();
- String path2 = o2.getPath();
-
- // Check whether name include path
- int lastIndex1 = name1.lastIndexOf('/');
- // log.debug(name1+", "+lastIndex1);
- if (!StringUtils.hasText(path1) && lastIndex1 >= 0) {
- path1 = name1.substring(0, lastIndex1);
- name1 = name1.substring(lastIndex1 + 1);
- }
-
- int lastIndex2 = name2.lastIndexOf('/');
- if (!StringUtils.hasText(path2) && lastIndex2 >= 0) {
- path2 = name2.substring(0, lastIndex2);
- name2 = name2.substring(lastIndex2 + 1);
- }
-
- // Perform the actual comparison
- if (StringUtils.hasText(path1) && StringUtils.hasText(path2)) {
- if (path1.equals(path2))
- return name1.compareTo(name2);
- else if (path1.startsWith(path2))
- return -1;
- else if (path2.startsWith(path1))
- return 1;
- else
- return path1.compareTo(path2);
- } else if (!StringUtils.hasText(path1)
- && StringUtils.hasText(path2)) {
- return 1;
- } else if (StringUtils.hasText(path1)
- && !StringUtils.hasText(path2)) {
- return -1;
- } else if (!StringUtils.hasText(path1)
- && !StringUtils.hasText(path2)) {
- return name1.compareTo(name2);
- } else {
- return 0;
- }
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.execution.ExecutionSpecAttribute;
-import org.argeo.slc.execution.RefSpecAttribute;
-import org.argeo.slc.execution.RefValueChoice;
-import org.springframework.beans.factory.BeanNameAware;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.context.ConfigurableApplicationContext;
-
-/** Spring based implementation of execution specifications. */
-@Deprecated
-public class DefaultExecutionSpec extends org.argeo.slc.runtime.DefaultExecutionSpec
- implements BeanNameAware, ApplicationContextAware, InitializingBean {
- private static final long serialVersionUID = 5159882223926926539L;
- private final static CmsLog log = CmsLog.getLog(DefaultExecutionSpec.class);
- private transient ApplicationContext applicationContext;
-
- public DefaultExecutionSpec() {
- super();
- }
-
- public void setBeanName(String name) {
- setName(name);
- }
-
- private ConfigurableListableBeanFactory getBeanFactory() {
- return ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
- }
-
- public void setApplicationContext(ApplicationContext applicationContext) {
- this.applicationContext = applicationContext;
- }
-
- public void afterPropertiesSet() throws Exception {
- if (getDescription() == null) {
- try {
- setDescription(getBeanFactory().getBeanDefinition(getName()).getDescription());
- } catch (NoSuchBeanDefinitionException e) {
- // silent
- }
- }
-
- for (String key : getAttributes().keySet()) {
- ExecutionSpecAttribute attr = getAttributes().get(key);
- if (attr instanceof RefSpecAttribute) {
- RefSpecAttribute rsa = (RefSpecAttribute) attr;
- if (rsa.getChoices() == null) {
- List<RefValueChoice> choices = buildRefValueChoices(rsa);
- rsa.setChoices(choices);
- }
- if (log.isTraceEnabled())
- log.debug("Spec attr " + key + " has " + rsa.getChoices().size() + " choices");
- }
- }
- }
-
- /**
- * Generates a list of ref value choices based on the bean available in the
- * application context.
- */
- protected List<RefValueChoice> buildRefValueChoices(RefSpecAttribute rsa) {
- List<RefValueChoice> choices = new ArrayList<RefValueChoice>();
- if (applicationContext == null) {
- log.warn("No application context declared," + " cannot scan ref value choices.");
- return choices;
- }
-
- beanNames: for (String beanName : getBeanFactory().getBeanNamesForType(rsa.getTargetClass(), true, false)) {
-
- // Since Spring 3, systemProperties is implicitly defined but has no
- // bean definition
- if (beanName.equals("systemProperties"))
- continue beanNames;
-
- BeanDefinition bd = getBeanFactory().getBeanDefinition(beanName);
- RefValueChoice choice = new RefValueChoice();
- choice.setName(beanName);
- choice.setDescription(bd.getDescription());
- if (log.isTraceEnabled())
- log.debug("Found choice " + beanName + " for " + rsa);
-
- choices.add(choice);
-
- }
- return choices;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionStack;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Pointcut;
-
-@Aspect
-/** Aspect intercepting calls on execution flows and contexts. */
-public class ExecutionAspect {
- private final static CmsLog log = CmsLog.getLog(ExecutionAspect.class);
-
- private ExecutionStack executionStack;
- private ExecutionContext executionContext;
-
- @Around("flowExecution()")
- public void aroundFlow(ProceedingJoinPoint pjp) throws Throwable {
- // IMPORTANT: Make sure that the execution context is called before the
- // execution stack
- executionContext.getUuid();
-
- ExecutionFlow executionFlow = (ExecutionFlow) pjp.getTarget();
- executionStack.enterFlow(executionFlow);
- executionContext.setVariable(ExecutionContext.VAR_FLOW_ID,
- executionStack.getCurrentStackLevelUuid());
- executionContext.setVariable(ExecutionContext.VAR_FLOW_NAME,
- executionFlow.getName());
-
- logStackEvent("=> ", executionFlow);
- try {
- // Actually execute the flow
- pjp.proceed();
- } finally {
- logStackEvent("<= ", executionFlow);
- executionStack.leaveFlow(executionFlow);
- }
- }
-
- @Around("getVariable()")
- public Object aroundGetVariable(ProceedingJoinPoint pjp) throws Throwable {
- Object obj = pjp.proceed();
- // if the variable was not found, look in the stack starting at the
- // upper flows
- if (obj == null) {
- String key = pjp.getArgs()[0].toString();
- obj = executionStack.findLocalVariable(key);
- }
- return obj;
- }
-
- @Pointcut("execution(void org.argeo.slc.execution.ExecutionFlow.run())")
- public void flowExecution() {
- }
-
- @Pointcut("execution(* org.argeo.slc.execution.ExecutionContext.getVariable(..))")
- public void getVariable() {
- }
-
- public void setExecutionStack(ExecutionStack executionStack) {
- this.executionStack = executionStack;
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- protected void logStackEvent(String symbol, ExecutionFlow executionFlow) {
- Integer stackSize = executionStack.getStackSize();
- if (log.isTraceEnabled())
- log.debug(depthSpaces(stackSize) + symbol + executionFlow + " #"
- + executionStack.getCurrentStackLevelUuid() + ", depth="
- + stackSize);
- if (log.isDebugEnabled())
- log.debug(depthSpaces(stackSize) + symbol + executionFlow);
- }
-
- protected void logRunnableExecution(ExecutionFlow executionFlow,
- Runnable runnable) {
- Integer stackSize = executionStack.getStackSize();
- if (log.isDebugEnabled())
- log.debug(depthSpaces(stackSize + 1)
- + runnable.getClass().getSimpleName() + " in "
- + executionFlow);
- }
-
- private String depthSpaces(int depth) {
- StringBuffer buf = new StringBuffer(depth * 2);
- for (int i = 0; i < depth; i++)
- buf.append(" ");
- return buf.toString();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.beans.PropertyDescriptor;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.runtime.InstantiationManager;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.MutablePropertyValues;
-import org.springframework.beans.PropertyValue;
-import org.springframework.beans.PropertyValues;
-import org.springframework.beans.factory.BeanDefinitionStoreException;
-import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
-import org.springframework.beans.factory.config.TypedStringValue;
-import org.springframework.beans.factory.support.ManagedList;
-import org.springframework.beans.factory.support.ManagedMap;
-import org.springframework.beans.factory.support.ManagedSet;
-import org.springframework.util.ObjectUtils;
-import org.springframework.util.StringUtils;
-
-/**
- * Spring post processor which ensures that execution parameters are properly
- * set. It is used at two levels: first during instantiation for instantiation
- * parameters which allow to implement templates, then at runtime in order to
- * interpret @{} placeholders when object of scope execution are instantiated.
- */
-public class ExecutionParameterPostProcessor extends
- InstantiationAwareBeanPostProcessorAdapter {
-
- private final static CmsLog log = CmsLog
- .getLog(ExecutionParameterPostProcessor.class);
-
- private ExecutionContext executionContext;
- private InstantiationManager instantiationManager;
-
- private String placeholderPrefix = "@{";
- private String placeholderSuffix = "}";
- private String nullValue;
-
- @Override
- public PropertyValues postProcessPropertyValues(PropertyValues pvs,
- PropertyDescriptor[] pds, Object bean, String beanName)
- throws BeansException {
-
- // TODO: resolve at execution only if scope is execution
- // TODO: deal with placeholders in RuntimeBeanReference and
- // RuntimeBeanNameReference
-
- MutablePropertyValues newPvs = new MutablePropertyValues();
-
- boolean changesOccured = false;
-
- for (PropertyValue pv : pvs.getPropertyValues()) {
- Object convertedValue = resolveValue(beanName, bean, pv.getValue());
- newPvs.addPropertyValue(new PropertyValue(pv, convertedValue));
- if (convertedValue != pv.getValue()) {
- changesOccured = true;
- }
- }
-
- return changesOccured ? newPvs : pvs;
- }
-
- @Override
- public boolean postProcessAfterInstantiation(Object bean, String beanName)
- throws BeansException {
- if (bean instanceof ExecutionFlow)
- instantiationManager.flowInitializationStarted(
- (ExecutionFlow) bean, beanName);
- return true;
- }
-
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if (bean instanceof ExecutionFlow)
- instantiationManager.flowInitializationFinished(
- (ExecutionFlow) bean, beanName);
- return bean;
- }
-
- protected String resolvePlaceholder(Object bean, String placeholder) {
- if (instantiationManager.isInFlowInitialization())
- return instantiationManager.getInitializingFlowParameter(
- placeholder).toString();
-
- else {// execution
- // next call fail if no execution context available
- Object obj = executionContext.getVariable(placeholder);
- if (obj != null) {
- return obj.toString();
- }
- }
-
- return null;
- }
-
- public Object resolveValue(String beanName, Object bean, Object value) {
- if (value instanceof TypedStringValue) {
- TypedStringValue tsv = (TypedStringValue) value;
- String originalValue = tsv.getValue();
-
- String convertedValue = resolveString(beanName, bean, originalValue);
- if (convertedValue == null)
- return null;
- return convertedValue.equals(originalValue) ? value
- : new TypedStringValue(convertedValue);
- } else if (value instanceof String) {
- String originalValue = value.toString();
- String convertedValue = resolveString(beanName, bean, originalValue);
- if (convertedValue == null)
- return null;
- return convertedValue.equals(originalValue) ? value
- : convertedValue;
- } else if (value instanceof ManagedMap) {
- Map<?, ?> mapVal = (Map<?, ?>) value;
-
- Map<Object, Object> newContent = new ManagedMap<Object, Object>();
- boolean entriesModified = false;
- for (Iterator<?> it = mapVal.entrySet().iterator(); it.hasNext();) {
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
- Object key = entry.getKey();
- int keyHash = (key != null ? key.hashCode() : 0);
- Object newKey = resolveValue(beanName, bean, key);
- int newKeyHash = (newKey != null ? newKey.hashCode() : 0);
- Object val = entry.getValue();
- Object newVal = resolveValue(beanName, bean, val);
- newContent.put(newKey, newVal);
- entriesModified = entriesModified
- || (newVal != val || newKey != key || newKeyHash != keyHash);
- }
-
- return entriesModified ? newContent : value;
- } else if (value instanceof ManagedList) {
- List<?> listVal = (List<?>) value;
- List<Object> newContent = new ManagedList<Object>();
- boolean valueModified = false;
-
- for (int i = 0; i < listVal.size(); i++) {
- Object elem = listVal.get(i);
- Object newVal = resolveValue(beanName, bean, elem);
- newContent.add(newVal);
- if (!ObjectUtils.nullSafeEquals(newVal, elem)) {
- valueModified = true;
- }
- }
- return valueModified ? newContent : value;
- } else if (value instanceof ManagedSet) {
- Set<?> setVal = (Set<?>) value;
- Set<Object> newContent = new ManagedSet<Object>();
- boolean entriesModified = false;
- for (Iterator<?> it = setVal.iterator(); it.hasNext();) {
- Object elem = it.next();
- int elemHash = (elem != null ? elem.hashCode() : 0);
- Object newVal = resolveValue(beanName, bean, elem);
- int newValHash = (newVal != null ? newVal.hashCode() : 0);
- newContent.add(newVal);
- entriesModified = entriesModified
- || (newVal != elem || newValHash != elemHash);
- }
- return entriesModified ? newContent : value;
- } else {
- // log.debug(beanName + ": " + value.getClass() + " : " + value);
- return value;
- }
-
- }
-
- private String resolveString(String beanName, Object bean, String strVal) {
- // in case <null/> is passed
- if (strVal == null)
- return null;
-
- String value = parseStringValue(bean, strVal, new HashSet<String>());
-
- if (value == null)
- throw new SlcException("Could not resolve placeholder '" + strVal
- + "' in bean '" + beanName + "'");
-
- return (value.equals(nullValue) ? null : value);
- }
-
- public void setPlaceholderPrefix(String placeholderPrefix) {
- this.placeholderPrefix = placeholderPrefix;
- }
-
- public void setPlaceholderSuffix(String placeholderSuffix) {
- this.placeholderSuffix = placeholderSuffix;
- }
-
- public void setNullValue(String nullValue) {
- this.nullValue = nullValue;
- }
-
- public void setInstantiationManager(
- InstantiationManager instantiationManager) {
- this.instantiationManager = instantiationManager;
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- //
- // Following methods hacked from the internals of
- // PropertyPlaceholderConfigurer
- //
-
- protected String parseStringValue(Object bean, String strVal,
- Set<String> visitedPlaceholders)
- throws BeanDefinitionStoreException {
-
- // in case <null/> is passed
- if (strVal == null)
- return null;
-
- StringBuffer buf = new StringBuffer(strVal);
-
- int startIndex = strVal.indexOf(placeholderPrefix);
- while (startIndex != -1) {
- int endIndex = findPlaceholderEndIndex(buf, startIndex);
- if (endIndex != -1) {
- String placeholder = buf.substring(startIndex
- + placeholderPrefix.length(), endIndex);
- if (!visitedPlaceholders.add(placeholder)) {
- throw new BeanDefinitionStoreException(
- "Circular placeholder reference '" + placeholder
- + "' in property definitions");
- }
- // Recursive invocation, parsing placeholders contained in
- // the placeholder key.
- placeholder = parseStringValue(bean, placeholder,
- visitedPlaceholders);
- // Now obtain the value for the fully resolved key...
- String propVal = resolvePlaceholder(bean, placeholder);
- if (propVal != null) {
- // Recursive invocation, parsing placeholders contained
- // in the
- // previously resolved placeholder value.
- propVal = parseStringValue(bean, propVal,
- visitedPlaceholders);
- buf.replace(startIndex,
- endIndex + placeholderSuffix.length(), propVal);
- if (log.isTraceEnabled()) {
- log.trace("Resolved placeholder '" + placeholder + "'");
- }
- startIndex = buf.indexOf(placeholderPrefix, startIndex
- + propVal.length());
- } else {
- throw new BeanDefinitionStoreException(
- "Could not resolve placeholder '" + placeholder
- + "'");
- }
- visitedPlaceholders.remove(placeholder);
- } else {
- startIndex = -1;
- }
- }
-
- return buf.toString();
- }
-
- private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
- int index = startIndex + placeholderPrefix.length();
- int withinNestedPlaceholder = 0;
- while (index < buf.length()) {
- if (StringUtils.substringMatch(buf, index, placeholderSuffix)) {
- if (withinNestedPlaceholder > 0) {
- withinNestedPlaceholder--;
- index = index + placeholderSuffix.length();
- } else {
- return index;
- }
- } else if (StringUtils
- .substringMatch(buf, index, placeholderPrefix)) {
- withinNestedPlaceholder++;
- index = index + placeholderPrefix.length();
- } else {
- index++;
- }
- }
- return -1;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-
-import org.springframework.core.io.Resource;
-
-/** Provides write access to resources during execution */
-public interface ExecutionResources {
- /** The base directory where this execution can write */
- public File getWritableBaseDir();
-
- /** Allocates a local file in the writable area and return it as a resource. */
- public Resource getWritableResource(String relativePath);
-
- /**
- * Allocates a local file in the writable area and return it as a fully
- * qualified OS path.
- */
- public String getWritableOsPath(String relativePath);
-
- /**
- * Allocates a local file in the writable area and return it as a
- * {@link File}.
- */
- public File getWritableOsFile(String relativePath);
-
- /**
- * Returns the resource as a file path. If the resource is not writable it
- * is copied as a file in the writable area and the path to this local file
- * is returned.
- */
- public String getAsOsPath(Resource resource, Boolean overwrite);
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.core.io.Resource;
-import org.springframework.util.Assert;
-
-/** Workaround when execution placedholders needs to be passed. */
-public class ExecutionResourcesFactoryBean implements FactoryBean<Resource> {
- private ExecutionResources executionResources;
- private String relativePath;
-
- public Resource getObject() throws Exception {
- Assert.notNull(executionResources, "executionResources is null");
- Assert.notNull(relativePath, "relativePath is null");
- return executionResources.getWritableResource(relativePath);
- }
-
- public Class<? extends Object> getObjectType() {
- return Resource.class;
- }
-
- public boolean isSingleton() {
- return true;
- }
-
- public void setExecutionResources(ExecutionResources executionResources) {
- this.executionResources = executionResources;
- }
-
- public void setRelativePath(String relativePath) {
- this.relativePath = relativePath;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.UnsupportedException;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionSpec;
-import org.argeo.slc.execution.ExecutionStack;
-import org.argeo.slc.runtime.ExecutionThread;
-import org.springframework.beans.factory.ObjectFactory;
-import org.springframework.beans.factory.config.Scope;
-
-/**
- * When Spring beans are instantiated with this scope, the same instance is
- * reused across an execution.
- */
-public class ExecutionScope implements Scope {
- private final static CmsLog log = CmsLog.getLog(ExecutionScope.class);
-
- private final ThreadLocal<ExecutionStack> executionStack = new ThreadLocal<ExecutionStack>();
- public final ThreadLocal<String> executionStackBeanName = new ThreadLocal<String>();
-
- private final ThreadLocal<ExecutionContext> executionContext = new ThreadLocal<ExecutionContext>();
- private final ThreadLocal<String> executionContextBeanName = new ThreadLocal<String>();
-
- public Object get(String name, ObjectFactory<?> objectFactory) {
- if (log.isTraceEnabled())
- log.debug("Get execution scoped bean " + name);
-
- // shortcuts
- if (executionStackBeanName.get() != null
- && name.equals(executionStackBeanName.get())) {
- return executionStack.get();
- }
-
- if (executionContextBeanName.get() != null
- && name.equals(executionContextBeanName.get())) {
- return executionContext.get();
- }
-
- // execution context must be defined first
- if (executionContext.get() == null) {
- Object obj = objectFactory.getObject();
- if (obj instanceof ExecutionContext) {
- return dealWithSpecialScopedObject(name, executionContext,
- executionContextBeanName, (ExecutionContext) obj);
- } else {
- // TODO: use execution context wrapper
- throw new SlcException("No execution context has been defined.");
- }
- }
-
- // for other scoped objects, an executions stack must be available
- if (executionStack.get() == null) {
- Object obj = objectFactory.getObject();
- if (obj instanceof ExecutionStack) {
- return dealWithSpecialScopedObject(name, executionStack,
- executionStackBeanName, (ExecutionStack) obj);
- } else {
- throw new SlcException("No execution stack has been defined.");
- }
- }
-
- // see if the execution stack already knows the object
- Object obj = executionStack.get().findScopedObject(name);
- if (obj == null) {
- obj = objectFactory.getObject();
- if (obj instanceof ExecutionContext)
- throw new SlcException(
- "Only one execution context can be defined per thread");
- if (obj instanceof ExecutionStack)
- throw new SlcException(
- "Only one execution stack can be defined per thread");
-
- checkForbiddenClasses(obj);
-
- executionStack.get().addScopedObject(name, obj);
- }
- return obj;
-
- }
-
- protected <T> T dealWithSpecialScopedObject(String name,
- ThreadLocal<T> threadLocal,
- ThreadLocal<String> threadLocalBeanName, T newObj) {
-
- T obj = threadLocal.get();
- if (obj == null) {
- obj = newObj;
- threadLocal.set(obj);
- threadLocalBeanName.set(name);
- if (log.isTraceEnabled()) {
- log.debug(obj.getClass() + " instantiated. (beanName=" + name
- + ")");
- }
- return obj;
- } else {
- throw new SlcException("Only one scoped " + obj.getClass()
- + " can be defined per thread");
- }
-
- }
-
- protected void checkForbiddenClasses(Object obj) {
- Class<?> clss = obj.getClass();
- if (ExecutionFlow.class.isAssignableFrom(clss)
- || ExecutionSpec.class.isAssignableFrom(clss)) {
- throw new UnsupportedException("Execution scoped object", clss);
- }
- }
-
- public String getConversationId() {
- // TODO: is it the most relevant?
- return executionContext.get().getUuid();
- }
-
- public void registerDestructionCallback(String name, Runnable callback) {
- if (Thread.currentThread() instanceof ExecutionThread) {
- ExecutionThread executionThread = (ExecutionThread) Thread
- .currentThread();
- executionThread.registerDestructionCallback(name, callback);
- }
- }
-
- public Object remove(String name) {
- if (log.isDebugEnabled())
- log.debug("Remove object " + name);
- throw new UnsupportedOperationException();
- }
-
- public Object resolveContextualObject(String key) {
- return executionContext.get().getVariable(key);
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.execution.ExecutionContext;
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.core.io.Resource;
-import org.springframework.util.Assert;
-
-/** Implements write access to resources based on standard Java {@link File} */
-public class FileExecutionResources implements ExecutionResources {
- private final static CmsLog log = CmsLog
- .getLog(FileExecutionResources.class);
- protected final static String DEFAULT_EXECUTION_RESOURCES_DIRNAME = "executionResources";
- public final static String DEFAULT_EXECUTION_RESOURCES_TMP_PATH = System
- .getProperty("java.io.tmpdir")
- + File.separator
- + System.getProperty("user.name")
- + File.separator
- + "slc"
- + File.separator + DEFAULT_EXECUTION_RESOURCES_DIRNAME;
-
- private File baseDir;
- private ExecutionContext executionContext;
- private String prefixDatePattern = "yyMMdd_HHmmss_SSS";
- private SimpleDateFormat sdf = null;
-
- private Boolean withExecutionSubdirectory = true;
-
- public FileExecutionResources() {
- // Default base directory
- String osgiInstanceArea = System.getProperty("osgi.instance.area");
- String osgiInstanceAreaDefault = System
- .getProperty("osgi.instance.area.default");
-
- if (osgiInstanceArea != null) {
- // within OSGi with -data specified
- osgiInstanceArea = removeFilePrefix(osgiInstanceArea);
- baseDir = new File(osgiInstanceArea + File.separator
- + DEFAULT_EXECUTION_RESOURCES_DIRNAME);
- } else if (osgiInstanceAreaDefault != null) {
- // within OSGi without -data specified
- osgiInstanceAreaDefault = removeFilePrefix(osgiInstanceAreaDefault);
- baseDir = new File(osgiInstanceAreaDefault + File.separator
- + DEFAULT_EXECUTION_RESOURCES_DIRNAME);
- } else {// outside OSGi
- baseDir = new File(DEFAULT_EXECUTION_RESOURCES_TMP_PATH);
- }
- }
-
- protected SimpleDateFormat sdf() {
- // Lazy init in case prefix has been externally set
- if (sdf == null)
- sdf = new SimpleDateFormat(prefixDatePattern);
- return sdf;
- }
-
- public Resource getWritableResource(String relativePath) {
- File file = getFile(relativePath);
- File parentDir = file.getParentFile();
-
- if (!parentDir.exists()) {
- // Creates if necessary
- if (log.isTraceEnabled())
- log.trace("Creating parent directory " + parentDir);
- parentDir.mkdirs();
- }
- Resource resource = new FileSystemResource(file);
-
- if (log.isTraceEnabled())
- log.trace("Returns writable resource " + resource);
- return resource;
- }
-
- public String getWritableOsPath(String relativePath) {
- try {
- return getFile(relativePath).getCanonicalPath();
- } catch (IOException e) {
- throw new SlcException("Cannot find canonical path", e);
- }
- }
-
- public File getWritableOsFile(String relativePath) {
- return getFile(relativePath);
- }
-
- public String getAsOsPath(Resource resource, Boolean overwrite) {
- File file = fileFromResource(resource);
- if (file != null)
- try {
- if (log.isTraceEnabled())
- log.debug("Directly interpret " + resource + " as OS file "
- + file);
- return file.getCanonicalPath();
- } catch (IOException e1) {
- // silent
- }
-
- if (log.isTraceEnabled())
- log.trace("Resource " + resource
- + " is not available on the file system. Retrieving it...");
-
- InputStream in = null;
- OutputStream out = null;
- try {
- String path = resource.getURL().getPath();
- file = getFile(path);
- if (file.exists() && !overwrite)
- return file.getCanonicalPath();
-
- file.getParentFile().mkdirs();
- in = resource.getInputStream();
- out = new FileOutputStream(file);
- IOUtils.copy(in, out);
- if (log.isDebugEnabled())
- log.debug("Retrieved " + resource + " to OS file " + file);
- return file.getCanonicalPath();
- } catch (IOException e) {
- throw new SlcException("Could not make resource " + resource
- + " an OS file.", e);
- } finally {
- IOUtils.closeQuietly(in);
- IOUtils.closeQuietly(out);
- }
- }
-
- /**
- * Extract the underlying file from the resource.
- *
- * @return the file or null if no files support this resource.
- */
- protected File fileFromResource(Resource resource) {
- try {
- return resource.getFile();
- } catch (IOException e) {
- return null;
- }
-
- }
-
- protected File getFile(String relativePath) {
- File writableBaseDir = getWritableBaseDir();
- return new File(writableBaseDir.getPath() + File.separator
- + relativePath.replace('/', File.separatorChar));
- }
-
- public File getWritableBaseDir() {
- if (withExecutionSubdirectory) {
- Date executionContextCreationDate = (Date) executionContext
- .getVariable(ExecutionContext.VAR_EXECUTION_CONTEXT_CREATION_DATE);
- Assert.notNull(executionContext, "execution context is null");
- String path = baseDir.getPath() + File.separator
- + sdf().format(executionContextCreationDate);
- // TODO write execution id somewhere? like in a txt file
- return new File(path);
- } else {
- return baseDir;
- }
- }
-
- protected String removeFilePrefix(String url) {
- if (url.startsWith("file:"))
- return url.substring("file:".length());
- else if (url.startsWith("reference:file:"))
- return url.substring("reference:file:".length());
- else
- return url;
- }
-
- public void setBaseDir(File baseDir) {
- this.baseDir = baseDir;
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- public void setPrefixDatePattern(String prefixDatePattern) {
- this.prefixDatePattern = prefixDatePattern;
- }
-
- public File getBaseDir() {
- return baseDir;
- }
-
- public ExecutionContext getExecutionContext() {
- return executionContext;
- }
-
- public String getPrefixDatePattern() {
- return prefixDatePattern;
- }
-
- /** Default is true. */
- public void setWithExecutionSubdirectory(Boolean withExecutionSubdirectory) {
- this.withExecutionSubdirectory = withExecutionSubdirectory;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionStack;
-import org.springframework.beans.BeanWrapper;
-import org.springframework.beans.BeanWrapperImpl;
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-public class MapExecutionContext implements ExecutionContext,
- ApplicationContextAware {
- private final Map<String, Object> variables = Collections
- .synchronizedMap(new HashMap<String, Object>());
-
- private final String uuid;
-
- private ApplicationContext applicationContext;
- private ExecutionStack executionStack;
-
- public MapExecutionContext() {
- uuid = UUID.randomUUID().toString();
- variables.put(VAR_EXECUTION_CONTEXT_ID, uuid);
- variables.put(VAR_EXECUTION_CONTEXT_CREATION_DATE, new Date());
- }
-
- public void setVariable(String key, Object value) {
- // check if we do not refer to a bean
- int lastInd = key.lastIndexOf('.');
- if (applicationContext != null && lastInd > 0) {
- String beanName = key.substring(0, lastInd);
- String propertyName = key.substring(lastInd + 1);
- if (applicationContext.containsBean(beanName)) {
- BeanWrapper beanWrapper = new BeanWrapperImpl(
- applicationContext.getBean(beanName));
- if (!beanWrapper.isWritableProperty(propertyName))
- throw new SlcException("No writable property "
- + propertyName + " in bean " + beanName);
- beanWrapper.setPropertyValue(propertyName, value);
- }
- }
-
- variables.put(key, value);
- }
-
- public Object getVariable(String key) {
- // check if we do not refer to a bean
- int lastInd = key.lastIndexOf('.');
- if (applicationContext != null && lastInd > 0) {
- String beanName = key.substring(0, lastInd);
- String propertyName = key.substring(lastInd + 1);
- if (applicationContext.containsBean(beanName)) {
- BeanWrapper beanWrapper = new BeanWrapperImpl(
- applicationContext.getBean(beanName));
- if (!beanWrapper.isReadableProperty(propertyName))
- throw new SlcException("No readable property "
- + propertyName + " in bean " + beanName);
- Object obj = beanWrapper.getPropertyValue(propertyName);
- return obj;
- }
- }
-
- Object value = variables.get(key);
- // try system property in last resort
- if (value == null)
- value = System.getProperty(key);
-
- // if the variable was not found, look in the stack starting at the
- // upper flows
- if (value == null) {
- value = executionStack.findLocalVariable(key);
- }
- return value;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- @Override
- public void beforeFlow(ExecutionFlow executionFlow) {
- // getUuid();
- executionStack.enterFlow(executionFlow);
- setVariable(ExecutionContext.VAR_FLOW_ID,
- executionStack.getCurrentStackLevelUuid());
- setVariable(ExecutionContext.VAR_FLOW_NAME, executionFlow.getName());
- }
-
- @Override
- public void afterFlow(ExecutionFlow executionFlow) {
- executionStack.leaveFlow(executionFlow);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof ExecutionContext)
- return uuid.equals(((ExecutionContext) obj).getUuid());
- return false;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "#" + uuid;
- }
-
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.applicationContext = applicationContext;
- }
-
- public void setExecutionStack(ExecutionStack executionStack) {
- this.executionStack = executionStack;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.core.io.Resource;
-import org.springframework.util.Assert;
-
-/** Retrieve an OS File from the given resource. */
-public class OsFileFactoryBean implements FactoryBean<String> {
- private ExecutionResources executionResources;
- private Resource resource;
- private Boolean overwrite = false;
-
- /** Return an existing file on the file system. */
- public String getObject() throws Exception {
- Assert.notNull(executionResources, "executionResources is null");
- Assert.notNull(resource, "resource is null");
- return executionResources.getAsOsPath(resource, overwrite);
- }
-
- /** Return {@link Object} because CGLIB is unable to proxy {@link File}. */
- public Class<? extends Object> getObjectType() {
- return CharSequence.class;
- }
-
- public boolean isSingleton() {
- return false;
- }
-
- /** The execution resources object. */
- public void setExecutionResources(ExecutionResources executionResources) {
- this.executionResources = executionResources;
- }
-
- /** The resource to access. */
- public void setResource(Resource resource) {
- this.resource = resource;
- }
-
- /**
- * Whether to overwrite the resource if it already exists. Default is
- * <code>false</code>.
- */
- public void setOverwrite(Boolean overwrite) {
- this.overwrite = overwrite;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.runtime.InstantiationManager;
-import org.springframework.beans.factory.FactoryBean;
-
-public class ParameterRef implements FactoryBean<Object> {
- private final static CmsLog log = CmsLog.getLog(ParameterRef.class);
-
- private InstantiationManager instantiationManager;
- private String name;
-
- /** Cached object. */
- private Object object;
-
- public ParameterRef() {
- }
-
- public ParameterRef(String name) {
- this.name = name;
- }
-
- public Object getObject() throws Exception {
- if (log.isTraceEnabled())
- log.debug("Parameter ref called for " + name);
-
- if (object == null)
- object = instantiationManager.getInitializingFlowParameter(name);
- return object;
- }
-
- public Class<?> getObjectType() {
- if (object == null)
- return instantiationManager.getInitializingFlowParameterClass(name);
- else
- return object.getClass();
- }
-
- public boolean isSingleton() {
- return true;
- }
-
- public void setInstantiationManager(
- InstantiationManager instantiationManager) {
- this.instantiationManager = instantiationManager;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-
-/** Experimental and suboptimal */
-public class SedFilteredResource implements FactoryBean<Resource>,
- InitializingBean {
- private Resource source;
-
- private List<String> filters = new ArrayList<String>();
- private Map<Pattern, String> patterns = new HashMap<Pattern, String>();
-
- private String charset = "UTF-8";
- private Charset cs;
- private CharsetDecoder decoder;
-
- // private CharsetEncoder encoder;
-
- public Resource getObject() throws Exception {
- if (filters.size() == 0)
- return source;
-
- // int capacity = 100 * 1024;// 100 KB
- ByteBuffer bb;
- if (source instanceof ByteArrayResource) {
- bb = ByteBuffer.wrap(((ByteArrayResource) source).getByteArray());
- } else {
- FileInputStream fis = null;
- try {
- File file = source.getFile();
- fis = new FileInputStream(file);
- FileChannel fc = fis.getChannel();
-
- // Get the file's size and then map it into memory
- int sz = (int) fc.size();
- bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
- } catch (IOException e) {
- // ReadableByteChannel channel = Channels.newChannel(source
- // .getInputStream());
- // bb = ByteBuffer.allocateDirect(capacity);
- // int read = 0;
- // do {
- // read = channel.read(bb);
- // } while (read > 0);
- // FIXME : use nio to parse the stream as it goes
- bb = ByteBuffer.wrap(IOUtils.toByteArray(source
- .getInputStream()));
- } finally {
- IOUtils.closeQuietly(fis);
- }
- }
- CharBuffer cb = decoder.decode(bb);
- for (Pattern pattern : patterns.keySet()) {
- Matcher matcher = pattern.matcher(cb);
- String output = matcher.replaceAll(patterns.get(pattern));
- cb = CharBuffer.wrap(output);
- }
- // ByteBuffer bbout = encoder.encode(cb);
- // ByteArrayOutputStream out = new ByteArrayOutputStream(capacity);
- // WritableByteChannel wchannel = Channels.newChannel(out);
- // wchannel.write(bbout);
- ByteArrayResource res = new ByteArrayResource(cb.toString().getBytes());
- return res;
- }
-
- public Class<?> getObjectType() {
- return Resource.class;
- }
-
- public boolean isSingleton() {
- return true;
- }
-
- public void afterPropertiesSet() throws Exception {
- cs = Charset.forName(charset);
- decoder = cs.newDecoder();
- // encoder = cs.newEncoder();
-
- for (String sedStr : filters) {
- sedStr = sedStr.trim();
- if (sedStr.length() < 4)
- throw new SlcException(sedStr + " not properly formatted.");
- if (sedStr.charAt(0) != 's')
- throw new SlcException(sedStr + " not properly formatted.");
- Character sep = sedStr.charAt(1);
- List<String> tokens = new ArrayList<String>(4);
- StringTokenizer st = new StringTokenizer(sedStr, sep.toString());
- while (st.hasMoreTokens())
- tokens.add(st.nextToken());
- if (tokens.size() != 3 && tokens.size() != 4)
- throw new SlcException(sedStr + " not properly formatted.");
- patterns.put(Pattern.compile(tokens.get(1)), tokens.get(2));
- }
- }
-
- public void setSource(Resource source) {
- this.source = source;
- }
-
- public void setFilters(List<String> filters) {
- this.filters = filters;
- }
-
- public void setCharset(String charset) {
- this.charset = charset;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <bean id="slcDefault.executionResources" parent="slcTemplate.fileResources"
- scope="execution" lazy-init="true">
- <aop:scoped-proxy proxy-target-class="false" />
- <property name="executionContext" ref="executionContext" />
- </bean>
-
- <bean id="slcDefault.writableResource" parent="slcTemplate.writableResource"
- abstract="true">
- <property name="executionResources" ref="slcDefault.executionResources" />
- </bean>
-
- <bean id="slcDefault.osFile" parent="slcTemplate.osFile" abstract="true">
- <property name="executionResources" ref="slcDefault.executionResources" />
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution.doc;
-
-import org.springframework.beans.MutablePropertyValues;
-import org.springframework.beans.PropertyValue;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-
-public class ConsoleContextDescriber implements ContextDescriber {
- public void describeContext(BeanDefinitionRegistry registry) {
- String[] beanNames = registry.getBeanDefinitionNames();
- for (String beanName : beanNames) {
- log("\n## BEAN: " + beanName);
- describeBean(registry.getBeanDefinition(beanName));
- }
- }
-
- public void describeBean(BeanDefinition beanDefinition) {
- log("BeanDefinition class: "+beanDefinition.getClass());
- log("# ATTRIBUTES");
- for(String attr:beanDefinition.attributeNames()){
- log(attr+"="+beanDefinition.getAttribute(attr));
- }
- log("# PROPERTIES");
- MutablePropertyValues pValues = beanDefinition.getPropertyValues();
- for (PropertyValue pv : pValues.getPropertyValues()) {
- log(pv.getName() + "= (" + pv.getValue().getClass() + ") "
- + pv.getValue());
- }
- }
-
- protected void log(Object obj){
- System.out.println(obj);
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.doc;
-
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-
-public interface ContextDescriber {
- public void describeContext(BeanDefinitionRegistry registry);
- public void describeBean(BeanDefinition bd);
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.Map;
-
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-
-/**
- * Composite <code>RunnableFactory</code>, redirecting the Runnable
- * creation to on of the configured <code>RunnableFactory</code> depending
- * on an entry of the data of the <code>RunnableDataNode</code>.
- */
-public class CompositeRunnableFactory implements RunnableFactory {
-
- /**
- * Key used to access factory ID in the data of the <code>RunnableDataNode</code>
- */
- private String factoryKey;
-
- /**
- * Maps a factory ID to an ExecutionFlowFactory
- */
- private Map<String, RunnableFactory> factories;
-
- public void createAndRegisterRunnable(RunnableDataNode node,
- BeanDefinitionRegistry beanDefinitionRegistry) {
- findFactory(node).createAndRegisterRunnable(node, beanDefinitionRegistry);
- }
-
- /**
- * Finds the <code>RunnableFactory</code> to use for a <code>RunnableDataNode</code>
- * @param node
- * @return the <code>RunnableFactory</code> to use for the <code>RunnableDataNode</code>
- */
- private RunnableFactory findFactory(RunnableDataNode node) {
- // get the factory ID from the data of the RunnableDescriptor
- Map<String, Object> data = node.getData();
- if (!data.containsKey(factoryKey)) {
- throw new SlcException("No data value for key '" + factoryKey + "'");
- }
- String factoryId = data.get(factoryKey).toString();
-
- // see if we have a factory for the factory ID
- if ((factories != null) && factories.containsKey(factoryId)) {
- return factories.get(factoryId);
- }
- // if not, look for a bean of name equals to the factory ID
- else {
- throw new SlcException("Not implemented");
- }
- }
-
- public void setFactoryKey(String factoryKey) {
- this.factoryKey = factoryKey;
- }
-
- public void setFactories(Map<String, RunnableFactory> factories) {
- this.factories = factories;
- }
-
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Default implementation of <code>RunnableDataNode</code>
- *
- */
-public class DefaultRunnableDataNode implements RunnableDataNode {
-
- private List<RunnableDataNode> children = new ArrayList<RunnableDataNode>();
-
- private RunnableDataNode parent;
-
- /**
- * Data of the RunnableDataNode. Does not contain
- * parent data.
- */
- private Map<String, Object> properData = new HashMap<String, Object>();
-
- private String path;
-
- private String beanName;
-
- public boolean isLeaf() {
- return children.size() == 0;
- }
-
- public List<RunnableDataNode> getChildren() {
- return children;
- }
-
- public void addChild(RunnableDataNode child) {
- child.setParent(this);
- children.add(child);
- }
-
- public Map<String, Object> getData() {
- Map<String, Object> data = new HashMap<String, Object>();
- if(parent != null) {
- Map<String, Object> parentData = parent.getData();
- if(parentData != null) {
- data.putAll(parentData);
- }
- }
- // entries defined in parentData can be overridden
- // in properData
- if(properData != null) {
- data.putAll(properData);
- }
- return data;
- }
-
- public Map<String, Object> getProperData() {
- return properData;
- }
-
- public void setProperData(Map<String, Object> properData) {
- this.properData = properData;
- }
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- public String getBeanName() {
- return beanName;
- }
-
- public void setBeanName(String beanName) {
- this.beanName = beanName;
- }
-
- public void setParent(RunnableDataNode parent) {
- this.parent = parent;
- }
-
- public RunnableDataNode getParent() {
- return parent;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.HashMap;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.aop.scope.ScopedProxyUtils;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.MutablePropertyValues;
-import org.springframework.beans.factory.config.BeanDefinitionHolder;
-import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.beans.factory.config.RuntimeBeanReference;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-import org.springframework.beans.factory.support.GenericBeanDefinition;
-import org.springframework.core.Ordered;
-
-/**
- * Generates <code>ExecutionFlows</code> and <code>Runnables</code> as
- * beans in the Spring Application Context.
- * Called by the Application Context as a <code>BeanFactoryPostProcessor</code>.
- * Two kinds of beans are generated:
- * <code>RunnableCallFlow</code>, calling a list of <code>Runnables</code> from the
- * Application Context after configuring the <code>ExecutionContext</code>,
- * and outputs of a <code>RunnableFactory</code>.
- */
-public class ExecutionFlowGenerator implements BeanFactoryPostProcessor,
- Ordered {
-
- private final CmsLog log = CmsLog.getLog(getClass());
-
- /**
- * Source providing a list of <code>RunnableCallFlowDescriptor</code>
- * used to create <code>RunnableCallFlow</code> and a list of
- * <code>RunnableDataNode</code> used to create any kind of flow via a factory
- */
- protected ExecutionFlowGeneratorSource source;
-
- /**
- * Factory used to create Runnables in the Application context from
- * the <code>RunnableDataNode</code> provided from the source.
- */
- protected RunnableFactory runnableFactory;
-
- /**
- * Bean name of the <code>ExecutionContext</code>.
- * Used to provide the created <code>RunnableCallFlow</code> beans
- * with a <code>RuntimeBeanReference</code> to
- * the <code>ExecutionContext</code>
- */
- private String executionContextBeanName = "executionContext";
-
- /**
- * Bean name of the context values Map.
- * A bean of class HashMap is created with this name, and a
- * <code>RuntimeBeanReference</code> is provided to the created
- * <code>RunnableCallFlow</code> beans.
- */
- private String contextValuesBeanName = "executionFlowGenerator.contextValues";
-
- /**
- * Prefix added to the bean names defined in each
- * <code>RunnableCallFlowDescriptor</code>
- */
- private String flowBeanNamesPrefix = "";
-
- private int order = Ordered.HIGHEST_PRECEDENCE;
-
- public void postProcessBeanFactory(
- ConfigurableListableBeanFactory beanFactory) throws BeansException {
-
- // assert that the beanFactory is a BeanDefinitionRegistry
- if (!(beanFactory instanceof BeanDefinitionRegistry)) {
- throw new SlcException("Can only work on "
- + BeanDefinitionRegistry.class);
- }
-
- // add bean for the Context Values Map
- createAndRegisterContextValuesBean((BeanDefinitionRegistry) beanFactory);
-
- // add beans for each RunnableDataNode
- for(RunnableDataNode node : source.getRunnableDataNodes()) {
- runnableFactory.createAndRegisterRunnable(node, (BeanDefinitionRegistry) beanFactory);
- }
-
- // add beans for each RunnableCallFlowDescriptor of the source to the application context
- for (RunnableCallFlowDescriptor descriptor : source
- .getRunnableCallFlowDescriptors()) {
- createAndRegisterFlowFor(descriptor, (BeanDefinitionRegistry) beanFactory);
- }
- }
-
- /**
- * Creates a <code>RunnableCallFlow</code> bean
- * for a <code>RunnableCallFlowDescriptor</code> and registers
- * it in the <code>BeanDefinitionRegistry</code>
- * @param flowDescriptor
- * @param registry
- */
- private void createAndRegisterFlowFor(RunnableCallFlowDescriptor flowDescriptor, BeanDefinitionRegistry registry) {
- // create the flow bean
- GenericBeanDefinition flowBean = new GenericBeanDefinition();
- flowBean.setBeanClass(RunnableCallFlow.class);
-
- String beanName = flowBeanNamesPrefix + flowDescriptor.getBeanName();
-
- MutablePropertyValues mpv = new MutablePropertyValues();
- mpv.addPropertyValue("runnableCalls", flowDescriptor.getRunnableCalls());
- mpv.addPropertyValue("sharedContextValuesMap", new RuntimeBeanReference(contextValuesBeanName));
-
- mpv.addPropertyValue("name", beanName);
- mpv.addPropertyValue("path", flowDescriptor.getPath());
-
- mpv.addPropertyValue("executionContext", new RuntimeBeanReference(executionContextBeanName));
-
- flowBean.setPropertyValues(mpv);
-
- // register it
- if(log.isDebugEnabled()) {
- log.debug("Registering bean definition for RunnableCallFlow " + beanName);
- }
- registry.registerBeanDefinition(beanName, flowBean);
- }
-
- /**
- * Creates the Context Values bean and register it in the
- * <code>BeanDefinitionRegistry</code>
- * @param registry
- */
- private void createAndRegisterContextValuesBean(BeanDefinitionRegistry registry) {
- GenericBeanDefinition contextValuesBean = new GenericBeanDefinition();
- contextValuesBean.setBeanClass(HashMap.class);
-
- BeanDefinitionHolder bdh = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(contextValuesBean, contextValuesBeanName), registry, true);
- registry.registerBeanDefinition(contextValuesBeanName, bdh.getBeanDefinition());
- }
-
- public int getOrder() {
- return order;
- }
-
- public void setOrder(int order) {
- this.order = order;
- }
-
- public void setSource(ExecutionFlowGeneratorSource source) {
- this.source = source;
- }
-
- public void setRunnableFactory(RunnableFactory runnableFactory) {
- this.runnableFactory = runnableFactory;
- }
-
- public void setExecutionContextBeanName(String executionContextBeanName) {
- this.executionContextBeanName = executionContextBeanName;
- }
-
- public void setContextValuesBeanName(String contextValuesBeanName) {
- this.contextValuesBeanName = contextValuesBeanName;
- }
-
- public void setFlowBeanNamesPrefix(String flowBeanNamesPrefix) {
- this.flowBeanNamesPrefix = flowBeanNamesPrefix;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.List;
-
-/**
- * Provides 2 types of information required by an <code>ExecutionFlowGenerator</code>:
- * a list of <code>RunnableCallFlowDescriptor</code> used to create <code>RunnableCallFlow</code>
- * and a list of <code>RunnableDataNode</code> used to create any kind of flow via a factory.
- */
-public interface ExecutionFlowGeneratorSource {
-
- /**
- * @return a list of <code>RunnableCallFlowDescriptor</code> used
- * by a <code>ExecutionFlowGenerator</code> to create <code>RunnableCallFlow</code>
- */
- public List<RunnableCallFlowDescriptor> getRunnableCallFlowDescriptors();
-
- /**
- * @return a list of <code>RunnableDataNode</code> used
- * by a <code>ExecutionFlowGenerator</code> to create any kind of flow via a factory
- */
- public List<RunnableDataNode> getRunnableDataNodes();
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.Map;
-
-/**
- * Storage class for information required to call a flow
- * of the Spring execution context:
- * bean name of the flow,
- * variables to add to the Execution Context before the call
- * and variables (context values) to add to a Map
- * potentially referenced by the called flow
- */
-public class RunnableCall {
-
- /**
- * Bean name of the flow to call
- */
- private String beanName;
-
- /**
- * Variables to add to the execution context before the call
- */
- private Map<String, Object> executionVariables;
-
- /**
- * Variables to add to the Map potentially referenced by
- * the called flow
- */
- private Map<String, Object> contextValues;
-
- public String getBeanName() {
- return beanName;
- }
-
- public void setBeanName(String beanName) {
- this.beanName = beanName;
- }
-
- public Map<String, Object> getExecutionVariables() {
- return executionVariables;
- }
-
- public void setExecutionVariables(Map<String, Object> executionVariables) {
- this.executionVariables = executionVariables;
- }
-
- public Map<String, Object> getContextValues() {
- return contextValues;
- }
-
- public void setContextValues(Map<String, Object> contextValues) {
- this.contextValues = contextValues;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.DefaultExecutionSpec;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionSpec;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-/**
- * Execution Flow calling a list of <code>Runnable</code> (identified by their
- * bean name in the Spring Application Context) after configuring the Execution
- * context and a Map potentially shared by the called <code>Runnable</code>
- *
- */
-public class RunnableCallFlow implements ExecutionFlow, ApplicationContextAware {
-
- private final static CmsLog log = CmsLog.getLog(RunnableCallFlow.class);
-
- /**
- * Key in the execution context for the index of the call (e.g. 0 for the
- * first runnable called, ...)
- */
- public final static String VAR_CALL_INDEX = "slcVar.runnableCallFlow.callIndex";
-
- /**
- * Name of the flow. Also bean name
- */
- private String name;
-
- /**
- * Path of the flow
- */
- private String path;
-
- /**
- * Whether an exception in a <code>Runnable</code> shall stop the execution
- * of the flow
- */
- private Boolean failOnError = true;
-
- /**
- * List of <code>Runnable</code> to call, with bean name, execution
- * variables and context values
- */
- private List<RunnableCall> runnableCalls;
-
- /**
- * Map potentially referenced by called flows. Updated with the context
- * values of a Runnable before calling it.
- */
- private Map<String, Object> sharedContextValuesMap;
-
- /**
- * ExecutionSpec of the flow. Does not contain any attribute.
- */
- private ExecutionSpec executionSpec = new DefaultExecutionSpec();
-
- /**
- * Reference to the ExecutionContext
- */
- private ExecutionContext executionContext;
-
- /**
- * Reference to the Spring <code>ApplicationContext</code>. Set via
- * <code>setApplicationContext</code>, the class implementing
- * <code>ApplicationContextAware</code>
- */
- private ApplicationContext applicationContext;
-
- /**
- * Runs a <code>Runnable</code> after configuring the Execution Context and
- * <code>sharedContextValuesMap</code>
- *
- * @param runnable
- * the <code>Runnable</code> to call
- * @param executionVariables
- * the variables to add to the <code>ExecutionContext</code>
- * @param contextValues
- * the variables to add to <code>sharedContextValuesMap</code>
- * @param callIndex
- * index of the call (0 for the first called
- * <code>Runnable</code>) set as variable of the
- * <code>ExecutionContext</code>
- */
- private void run(Runnable runnable, Map<String, Object> executionVariables,
- Map<String, Object> contextValues, int callIndex) {
- // add all variables to the Execution Context
- for (Map.Entry<String, Object> entry : executionVariables.entrySet()) {
- executionContext.setVariable(entry.getKey(), entry.getValue());
- }
-
- // add call Index Variable
- executionContext.setVariable(VAR_CALL_INDEX, callIndex);
-
- // clear sharedContextValues and add all values of contextValues
- if (sharedContextValuesMap != null) {
- sharedContextValuesMap.clear();
- sharedContextValuesMap.putAll(contextValues);
- }
-
- // then run the runnable
- doExecuteRunnable(runnable);
- }
-
- public void doExecuteRunnable(Runnable runnable) {
- runnable.run();
- }
-
- /**
- * Executes the flow. For each <code>RunnableCall</code>, the corresponding
- * flow is retrieved from the Spring Application Context, the
- * <code>ExecutionContext</code> and <code>sharedContextValuesMap</code> are
- * configured and the <code>Runnable</code> is called.
- */
- public void run() {
- if (applicationContext == null) {
- throw new SlcException("No ApplicationContext defined");
- }
-
- try {
- for (int callIndex = 0; callIndex < runnableCalls.size(); ++callIndex) {
- RunnableCall runnableCall = runnableCalls.get(callIndex);
- Object bean = applicationContext.getBean(
- runnableCall.getBeanName(), Runnable.class);
- if (log.isDebugEnabled())
- log.debug("Running flow '" + runnableCall.getBeanName()
- + "'");
- run((Runnable) bean, runnableCall.getExecutionVariables(),
- runnableCall.getContextValues(), callIndex);
- }
- } catch (RuntimeException e) {
- if (failOnError)
- throw e;
- else {
- log.error("Execution flow failed,"
- + " but process did not fail"
- + " because failOnError property"
- + " is set to false: " + e);
- if (log.isTraceEnabled())
- e.printStackTrace();
- }
- }
- }
-
- public Iterator<Runnable> runnables() {
- List<Runnable> runnables = new ArrayList<Runnable>();
- for (int callIndex = 0; callIndex < runnableCalls.size(); ++callIndex) {
- RunnableCall runnableCall = runnableCalls.get(callIndex);
- Object bean = applicationContext.getBean(
- runnableCall.getBeanName(), Runnable.class);
- runnables.add((Runnable) bean);
- }
- return runnables.iterator();
- }
-
- public Runnable getRunnable() {
- if (runnableCalls.size() == 1)
- return runnables().next();
- else
- throw new SlcException("There are " + runnableCalls.size()
- + " runnables in flow " + getName());
- }
-
- @Override
- public String toString() {
- return new StringBuffer("RunnableCallFlow ").append(name).toString();
- }
-
- public ExecutionSpec getExecutionSpec() {
- return executionSpec;
- }
-
- public String getName() {
- return name;
- }
-
- public Object getParameter(String key) {
- throw new SlcException("RunnableCallFlow have no parameters");
- }
-
- public String getPath() {
- return path;
- }
-
- public Boolean isSetAsParameter(String key) {
- // The ExecutionSpec having no attribute,
- // always return false
- return false;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- public void setRunnableCalls(List<RunnableCall> runnableCalls) {
- this.runnableCalls = runnableCalls;
- }
-
- public void setApplicationContext(ApplicationContext applicationContext) {
- this.applicationContext = applicationContext;
- }
-
- public void setSharedContextValuesMap(Map<String, Object> contextValues) {
- this.sharedContextValuesMap = contextValues;
- }
-
- public void setFailOnError(Boolean failOnError) {
- this.failOnError = failOnError;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Storage Class for information required to
- * instantiate a <code>RunnableCallFlow</code>:
- * bean name of the flow,
- * path of the flow
- * and list of <code>RunnableCall</code>.
- *
- */
-public class RunnableCallFlowDescriptor {
-
- /**
- * Bean name of the flow to instantiate
- */
- private String beanName;
-
- /**
- * Path of the flow to instantiate
- */
- private String path;
-
- /**
- * List of <code>RunnableCall</code>
- */
- private List<RunnableCall> runnableCalls = new ArrayList<RunnableCall>();
-
- public String getBeanName() {
- return beanName;
- }
-
- public void setBeanName(String beanName) {
- this.beanName = beanName;
- }
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- public List<RunnableCall> getRunnableCalls() {
- return runnableCalls;
- }
-
- public void setRunnableCalls(List<RunnableCall> runnableCalls) {
- this.runnableCalls = runnableCalls;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * Stores information relative to a Runnable.
- * Allows to structure the information as a tree, each node
- * storing data as a Map.
- */
-public interface RunnableDataNode {
-
- /**
- * @return a Map containing the data associated with this node.
- * Data associated with parent nodes are expected
- * to be contained in the returned Map
- */
- public Map<String, Object> getData();
-
- /**
- * @return the name of the bean to create.
- * Can be null if no bean shall be created for the
- * <code>RunnableDataNode</code> (e.g. is is a sub-node)
- */
- public String getBeanName();
-
- /**
- * @return the path of the flow bean to create.
- * Can be null if the bean to created is not an
- * <code>ExecutionFlow</code> or if no bean shall be created for the
- * <code>RunnableDataNode</code> (e.g. is is a sub-node)
- */
- public String getPath();
-
- /**
- * @return whether the <code>RunnableDataNode</code> has
- * children or not.
- * Expected to be equivalent to <code>getChildren().empty()</code>
- */
- public boolean isLeaf();
-
- /**
- * @return the list of <code>RunnableDataNode</code> children.
- * Can be empty. Shall not be null.
- */
- public List<RunnableDataNode> getChildren();
-
- /**
- * @return the <code>RunnableDataNode</code> parent.
- * Can be null if no parent is defined (top node).
- */
- public RunnableDataNode getParent();
-
- /**
- * Sets the <code>RunnableDataNode</code> parent
- * @param parent
- */
- public void setParent(RunnableDataNode parent);
-}
+++ /dev/null
-package org.argeo.slc.core.execution.generator;
-
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-
-/**
- * Interprets a <code>RunnableDataNode</code> by creating corresponding
- * beans and registering them in a <code>BeanDefinitionRegistry</code>
- *
- */
-public interface RunnableFactory {
-
- public void createAndRegisterRunnable(RunnableDataNode node,
- BeanDefinitionRegistry beanDefinitionRegistry);
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 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. -->
-<!-- Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org> 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. -->
-
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <description>Bare minimal runtime configuration. In general you will
- want to use simple.xml instead.
- </description>
-
- <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
- <property name="scopes">
- <map>
- <entry key="execution">
- <bean class="org.argeo.slc.core.execution.ExecutionScope" />
- </entry>
- </map>
- </property>
- </bean>
-
-
- <bean id="executionStack" class="org.argeo.slc.runtime.DefaultExecutionStack"
- scope="execution">
- <aop:scoped-proxy proxy-target-class="false" />
- </bean>
-
- <bean id="instantiationManager" class="org.argeo.slc.runtime.InstantiationManager" />
-
- <bean class="org.argeo.slc.core.execution.ExecutionParameterPostProcessor">
- <property name="executionContext" ref="executionContext" />
- <property name="instantiationManager" ref="instantiationManager" />
- </bean>
-
- <!-- <bean class="org.argeo.slc.core.execution.ExecutionAspect"> -->
- <!-- <property name="executionStack" ref="executionStack" /> -->
- <!-- <property name="executionContext" ref="executionContext" /> -->
- <!-- </bean> -->
-
- <aop:aspectj-autoproxy />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 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. -->
-<!-- Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org> 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. -->
-
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <description>Default Capabilities</description>
-
- <import resource="runtime.xml" />
-
- <bean id="executionContext" class="org.argeo.slc.core.execution.MapExecutionContext"
- scope="execution">
- <aop:scoped-proxy proxy-target-class="false" />
- <property name="executionStack" ref="executionStack" />
- </bean>
-
- <bean id="executionFlowDescriptorConverter"
- class="org.argeo.slc.core.execution.DefaultExecutionFlowDescriptorConverter"></bean>
-
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
- <property name="ignoreUnresolvablePlaceholders" value="true" />
- </bean>
-
- <bean id="parameterRef" class="org.argeo.slc.core.execution.ParameterRef"
- abstract="true">
- <property name="instantiationManager" ref="instantiationManager" />
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <bean id="specAttr.primitive" class="org.argeo.slc.primitive.PrimitiveSpecAttribute"
- abstract="true" />
- <bean id="specAttr.resource" class="org.argeo.slc.core.execution.ResourceSpecAttribute"
- abstract="true" />
- <bean id="specAttr.ref" class="org.argeo.slc.execution.RefSpecAttribute"
- abstract="true" />
-
- <bean id="slcTemplate.simpleFlow" class="org.argeo.slc.core.execution.DefaultExecutionFlow"
- abstract="true" />
- <bean id="slcTemplate.simpleSpec" class="org.argeo.slc.core.execution.DefaultExecutionSpec"
- abstract="true" />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<!-- Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org> 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. -->
-
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <description>
- Simple runtime enriched with defaults and templates used
- to simplify XML files. These templates have been deprecated by the
- custom XML namespace and will be removed in SLC 2.x. Use the XML
- namespace instead.
- </description>
-
- <import resource="simple.xml" />
-
- <import resource="specs.xml" />
- <import resource="templates.xml" />
- <import resource="defaults.xml" />
- <import resource="utils.xml" />
- <import resource="tasks/core.xml" />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import org.argeo.slc.test.TestResult;
-
-public class CloseTestResult implements Runnable {
- private TestResult testResult;
-
- public void run() {
- testResult.close();
- }
-
- public void setTestResult(TestResult testResult) {
- this.testResult = testResult;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.commons.io.FileUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.core.io.Resource;
-
-public class Echo implements Runnable {
- private final static CmsLog defaultLog = CmsLog.getLog(Echo.class);
- private Resource writeTo = null;
-
- private CmsLog log;
- private Object message;
-
- public void run() {
- log().info(message);
-
- if (writeTo != null) {
- try {
- File file = writeTo.getFile();
- if (log().isDebugEnabled())
- log().debug("Write to " + file);
- if (message != null)
- FileUtils.writeStringToFile(file, message.toString());
- } catch (IOException e) {
- throw new SlcException("Could not write to " + writeTo, e);
- }
- }
- }
-
- private CmsLog log() {
- return log != null ? log : defaultLog;
- }
-
- public void setMessage(Object message) {
- this.message = message;
- }
-
- public void setWriteTo(Resource writeTo) {
- this.writeTo = writeTo;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import org.argeo.slc.SlcException;
-
-/** Conditional execution */
-public class If implements Runnable {
- private Boolean is;
- private Boolean not;
- private Runnable then;
- private Runnable els;
-
- public void run() {
- if (is == null && not == null)
- throw new SlcException("No condition set");
- if (is != null && not != null)
- throw new SlcException("Both is and not cannot be set");
-
- boolean bool = (is != null ? is : !not);
- if (bool) {
- if (then != null)
- then.run();
- } else {
- if (els != null)
- els.run();
- }
-
- }
-
- public void setIs(Boolean bool) {
- this.is = bool;
- }
-
- public void setThen(Runnable then) {
- this.then = then;
- }
-
- public void setEls(Runnable els) {
- this.els = els;
- }
-
- public Boolean getNot() {
- return not;
- }
-
- public void setNot(Boolean not) {
- this.not = not;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.core.io.Resource;
-
-/** A Java Virtual Machine process. */
-public class JvmProcess extends SystemCall implements InitializingBean {
- private Properties systemProperties = new Properties();
- private List<Resource> classpath = new ArrayList<Resource>();
- private List<Resource> pBootClasspath = new ArrayList<Resource>();
- private Resource jvm = null;
- private String mainClass;
- private String mainJar;
- private List<String> jvmArgs = new ArrayList<String>();
- private List<String> args = new ArrayList<String>();
-
- private String systemPropertiesFileProperty = null;
- private String systemPropertiesFileDir = null;
- private String systemPropertiesFileName = null;
-
- public void afterPropertiesSet() throws Exception {
- List<Object> command = new ArrayList<Object>();
- if (jvm != null)
- command.add(asFile(jvm).getPath());
- else
- command.add("java");
-
- if (pBootClasspath.size() > 0) {
- StringBuffer buf = new StringBuffer("-Xbootclasspath/p:");
- Boolean first = true;
- for (Resource res : pBootClasspath) {
- if (first)
- first = false;
- else
- buf.append(File.pathSeparatorChar);
-
- buf.append(asFile(res));
- }
- command.add(buf.toString());
- }
-
- for (String jvmArg : jvmArgs) {
- command.add(jvmArg);
- }
-
- if (classpath.size() > 0) {
- command.add("-cp");
- StringBuffer buf = new StringBuffer("");
- for (Resource res : classpath) {
- if (buf.length() != 0)
- buf.append(File.pathSeparatorChar);
- buf.append(asFile(res));
- }
- command.add(buf.toString());
- }
-
- if (systemPropertiesFileProperty == null) {
- // pass system properties as argument
- for (Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
- command.add("-D" + entry.getKey() + "=" + entry.getValue());
- }
- } else {
- // write system properties in a file to work around OS limitations
- // with command line (e.g. Win XP)
- String dir = systemPropertiesFileDir;
- if (dir == null)
- dir = getExecDirToUse();
- String fileName = systemPropertiesFileName;
- if (fileName == null)
- fileName = systemPropertiesFileProperty + ".properties";
-
- // Write file
- FileOutputStream fos = null;
- File file = new File(dir + File.separator + fileName);
- try {
-
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- fos = new FileOutputStream(file);
- systemProperties.store(fos, "Automatically generated by "
- + getClass());
- command.add("-D" + systemPropertiesFileProperty + "="
- + file.getCanonicalPath());
- } catch (IOException e) {
- throw new SlcException("Cannot write to system properties to "
- + file, e);
- } finally {
- IOUtils.closeQuietly(fos);
- }
- }
-
- // Program
- if (mainClass != null) {
- command.add(mainClass);
- } else if (mainJar != null) {
- command.add("-jar");
- command.add(mainJar);
- } else {
- throw new SlcException("No main class or jar defined");
- }
-
- for (String arg : args) {
- command.add(arg);
- }
-
- setCommand(command);
- }
-
- protected File asFile(Resource res) {
- try {
- return res.getFile();
- } catch (FileNotFoundException e) {
- return copyToTempFile(res);
- } catch (IOException e) {
- throw new SlcException("Cannot convert resource to file", e);
- }
-
- }
-
- protected File copyToTempFile(Resource res) {
- File tempFile;
- FileOutputStream fos;
- try {
- tempFile = File.createTempFile("slcJvmProcess-", res.getFilename());
- tempFile.deleteOnExit();
- fos = new FileOutputStream(tempFile);
- IOUtils.copy(res.getInputStream(), fos);
- } catch (IOException e) {
- throw new SlcException("Cannot copy " + res + " to temp file.", e);
- }
- IOUtils.closeQuietly(fos);
- return tempFile;
- }
-
- /** Append the argument (for chaining) */
- @Override
- public SystemCall arg(String arg) {
- args.add(arg);
- return this;
- }
-
- /** Append the argument (for chaining) */
- @Override
- public SystemCall arg(String arg, String value) {
- args.add(arg);
- args.add(value);
- return this;
- }
-
- public Properties getSystemProperties() {
- return systemProperties;
- }
-
- public void setSystemProperties(Properties systemProperties) {
- this.systemProperties = systemProperties;
- }
-
- public List<Resource> getClasspath() {
- return classpath;
- }
-
- public void setClasspath(List<Resource> classpath) {
- this.classpath = classpath;
- }
-
- public List<Resource> getPBootClasspath() {
- return pBootClasspath;
- }
-
- public void setPBootClasspath(List<Resource> bootClasspath) {
- pBootClasspath = bootClasspath;
- }
-
- public Resource getJvm() {
- return jvm;
- }
-
- public void setJvm(Resource jvm) {
- this.jvm = jvm;
- }
-
- public String getMainClass() {
- return mainClass;
- }
-
- public void setMainClass(String mainClass) {
- this.mainClass = mainClass;
- }
-
- public String getMainJar() {
- return mainJar;
- }
-
- public void setMainJar(String mainJar) {
- this.mainJar = mainJar;
- }
-
- public List<String> getJvmArgs() {
- return jvmArgs;
- }
-
- public void setJvmArgs(List<String> jvmArgs) {
- this.jvmArgs = jvmArgs;
- }
-
- public List<String> getArgs() {
- return args;
- }
-
- public void setArgs(List<String> args) {
- this.args = args;
- }
-
- public void setSystemPropertiesFileProperty(
- String systemPropertiesFilePropertyName) {
- this.systemPropertiesFileProperty = systemPropertiesFilePropertyName;
- }
-
- public void setSystemPropertiesFileDir(String systemPropertiesFileDir) {
- this.systemPropertiesFileDir = systemPropertiesFileDir;
- }
-
- public void setSystemPropertiesFileName(String systemPropertiesFileName) {
- this.systemPropertiesFileName = systemPropertiesFileName;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.beans.factory.FactoryBean;
-
-/** Merge the provided lists in one single list, in the order provided. */
-public class MergedLists implements FactoryBean<List<Object>> {
- private List<List<Object>> lists = new ArrayList<List<Object>>();
-
- public void setLists(List<List<Object>> lists) {
- this.lists = lists;
- }
-
- public List<Object> getObject() throws Exception {
- List<Object> merged = new ArrayList<Object>();
- for (List<Object> lst : lists) {
- merged.addAll(lst);
- }
- return merged;
- }
-
- public Class<?> getObjectType() {
- return List.class;
- }
-
- public boolean isSingleton() {
- return false;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.util.Assert;
-import org.springframework.util.ReflectionUtils;
-
-public class MethodCall implements Runnable {
- private Object target;
- private String method;
- private List<Object> args = new ArrayList<Object>();
-
- public void run() {
- Assert.notNull(target, "target");
- Assert.notNull(method, "method");
- Method methodRef = ReflectionUtils
- .findMethod(target.getClass(), method);
- if (args.size() == 0)
- ReflectionUtils.invokeMethod(methodRef, target);
- else
- ReflectionUtils.invokeMethod(methodRef, methodRef, args.toArray());
- }
-
- public void setTarget(Object target) {
- this.target = target;
- }
-
- public void setMethod(String method) {
- this.method = method;
- }
-
- public void setArgs(List<Object> args) {
- this.args = args;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.test.context.SimpleContextAware;
-import org.argeo.slc.test.context.ContextAware;
-
-/**
- * Overrides Values and Expected values of a target
- * <code>SimpleContextAware</code> with the corresponding
- * values and expected values of a source <code>ContextAware</code>
- *
- */
-public class OverrideContextAware implements Runnable {
-
- private ContextAware source;
-
- private SimpleContextAware target;
-
- /**
- * Whether an exception shall be thrown if a value
- * or expected value of the source is not defined
- * in the target
- */
- private Boolean failIfUndefinedInSource = true;
-
- public void run() {
- // override values
- if(source.getValues() != null)
- for(String key : source.getValues().keySet()) {
- if(failIfUndefinedInSource && !target.getValues().containsKey(key)) {
- throw new SlcException("No entry in target values for key '" + key + "'");
- }
- target.getValues().put(key, source.getValues().get(key));
- }
-
- // override expected values
- if(source.getExpectedValues() != null)
- for(String key : source.getExpectedValues().keySet()) {
- if(failIfUndefinedInSource && !target.getExpectedValues().containsKey(key)) {
- throw new SlcException("No entry in target expected values for key '" + key + "'");
- }
- target.getExpectedValues().put(key, source.getExpectedValues().get(key));
- }
- }
-
- public void setSource(ContextAware source) {
- this.source = source;
- }
-
- public void setTarget(SimpleContextAware target) {
- this.target = target;
- }
-
- public void setFailIfUndefinedInSource(Boolean failIfUndefinedInSource) {
- this.failIfUndefinedInSource = failIfUndefinedInSource;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.security.auth.callback.CallbackHandler;
-
-import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.DefaultExecutor;
-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.LogOutputStream;
-import org.apache.commons.exec.PumpStreamHandler;
-import org.apache.commons.exec.ShutdownHookProcessDestroyer;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.UnsupportedException;
-import org.argeo.slc.core.execution.ExecutionResources;
-import org.argeo.slc.runtime.test.SimpleResultPart;
-import org.argeo.slc.test.TestResult;
-import org.argeo.slc.test.TestStatus;
-import org.springframework.core.io.Resource;
-
-/** Execute an OS specific system call. */
-public class SystemCall implements Runnable {
- public final static String LOG_STDOUT = "System.out";
-
- private final CmsLog log = CmsLog.getLog(getClass());
-
- private String execDir;
-
- private String cmd = null;
- private List<Object> command = null;
-
- private Executor executor = new DefaultExecutor();
- private Boolean synchronous = true;
-
- private String stdErrLogLevel = "ERROR";
- private String stdOutLogLevel = "INFO";
-
- private Resource stdOutFile = null;
- private Resource stdErrFile = null;
-
- private Resource stdInFile = null;
- /**
- * If no {@link #stdInFile} provided, writing to this stream will write to
- * the stdin of the process.
- */
- private OutputStream stdInSink = null;
-
- private Boolean redirectStdOut = false;
-
- private List<SystemCallOutputListener> outputListeners = Collections
- .synchronizedList(new ArrayList<SystemCallOutputListener>());
-
- private Map<String, List<Object>> osCommands = new HashMap<String, List<Object>>();
- private Map<String, String> osCmds = new HashMap<String, String>();
- private Map<String, String> environmentVariables = new HashMap<String, String>();
-
- private Boolean logCommand = false;
- private Boolean redirectStreams = true;
- private Boolean exceptionOnFailed = true;
- private Boolean mergeEnvironmentVariables = true;
-
-// private Authentication authentication;
-
- private String osConsole = null;
- private String generateScript = null;
-
- /** 24 hours */
- private Long watchdogTimeout = 24 * 60 * 60 * 1000l;
-
- private TestResult testResult;
-
- private ExecutionResources executionResources;
-
- /** Sudo the command, as root if empty or as user if not. */
- private String sudo = null;
- // TODO make it more secure and robust, test only once
- private final String sudoPrompt = UUID.randomUUID().toString();
- private String askPassProgram = "/usr/libexec/openssh/ssh-askpass";
- @SuppressWarnings("unused")
- private boolean firstLine = true;
- @SuppressWarnings("unused")
- private CallbackHandler callbackHandler;
- /** Chroot to the this path (must not be empty) */
- private String chroot = null;
-
- // Current
- /** Current watchdog, null if process is completed */
- ExecuteWatchdog currentWatchdog = null;
-
- /** Empty constructor */
- public SystemCall() {
-
- }
-
- /**
- * Constructor based on the provided command list.
- *
- * @param command
- * the command list
- */
- public SystemCall(List<Object> command) {
- this.command = command;
- }
-
- /**
- * Constructor based on the provided command.
- *
- * @param cmd
- * the command. If the provided string contains no space a
- * command list is initialized with the argument as first
- * component (useful for chained construction)
- */
- public SystemCall(String cmd) {
- if (cmd.indexOf(' ') < 0) {
- command = new ArrayList<Object>();
- command.add(cmd);
- } else {
- this.cmd = cmd;
- }
- }
-
- /** Executes the system call. */
- public void run() {
-// authentication = SecurityContextHolder.getContext().getAuthentication();
-
- // Manage streams
- Writer stdOutWriter = null;
- OutputStream stdOutputStream = null;
- Writer stdErrWriter = null;
- InputStream stdInStream = null;
- if (stdOutFile != null)
- if (redirectStdOut)
- stdOutputStream = createOutputStream(stdOutFile);
- else
- stdOutWriter = createWriter(stdOutFile, true);
-
- if (stdErrFile != null) {
- stdErrWriter = createWriter(stdErrFile, true);
- } else {
- if (stdOutFile != null && !redirectStdOut)
- stdErrWriter = createWriter(stdOutFile, true);
- }
-
- try {
- if (stdInFile != null)
- stdInStream = stdInFile.getInputStream();
- else {
- stdInStream = new PipedInputStream();
- stdInSink = new PipedOutputStream(
- (PipedInputStream) stdInStream);
- }
- } catch (IOException e2) {
- throw new SlcException("Cannot open a stream for " + stdInFile, e2);
- }
-
- if (log.isTraceEnabled()) {
- log.debug("os.name=" + System.getProperty("os.name"));
- log.debug("os.arch=" + System.getProperty("os.arch"));
- log.debug("os.version=" + System.getProperty("os.version"));
- }
-
- // Execution directory
- File dir = new File(getExecDirToUse());
- // if (!dir.exists())
- // dir.mkdirs();
-
- // Watchdog to check for lost processes
- Executor executorToUse;
- if (executor != null)
- executorToUse = executor;
- else
- executorToUse = new DefaultExecutor();
- executorToUse.setWatchdog(createWatchdog());
-
- if (redirectStreams) {
- // Redirect standard streams
- executorToUse.setStreamHandler(createExecuteStreamHandler(
- stdOutWriter, stdOutputStream, stdErrWriter, stdInStream));
- } else {
- // Dummy stream handler (otherwise pump is used)
- executorToUse.setStreamHandler(new DummyexecuteStreamHandler());
- }
-
- executorToUse.setProcessDestroyer(new ShutdownHookProcessDestroyer());
- executorToUse.setWorkingDirectory(dir);
-
- // Command line to use
- final CommandLine commandLine = createCommandLine();
- if (logCommand)
- log.info("Execute command:\n" + commandLine
- + "\n in working directory: \n" + dir + "\n");
-
- // Env variables
- Map<String, String> environmentVariablesToUse = null;
- environmentVariablesToUse = new HashMap<String, String>();
- if (mergeEnvironmentVariables)
- environmentVariablesToUse.putAll(System.getenv());
- if (environmentVariables.size() > 0)
- environmentVariablesToUse.putAll(environmentVariables);
-
- // Execute
- ExecuteResultHandler executeResultHandler = createExecuteResultHandler(commandLine);
-
- //
- // THE EXECUTION PROPER
- //
- try {
- if (synchronous)
- try {
- int exitValue = executorToUse.execute(commandLine,
- environmentVariablesToUse);
- executeResultHandler.onProcessComplete(exitValue);
- } catch (ExecuteException e1) {
- if (e1.getExitValue() == Executor.INVALID_EXITVALUE) {
- Thread.currentThread().interrupt();
- return;
- }
- // Sleep 1s in order to make sure error logs are flushed
- Thread.sleep(1000);
- executeResultHandler.onProcessFailed(e1);
- }
- else
- executorToUse.execute(commandLine, environmentVariablesToUse,
- executeResultHandler);
- } catch (SlcException e) {
- throw e;
- } catch (Exception e) {
- throw new SlcException("Could not execute command " + commandLine,
- e);
- } finally {
- IOUtils.closeQuietly(stdOutWriter);
- IOUtils.closeQuietly(stdErrWriter);
- IOUtils.closeQuietly(stdInStream);
- IOUtils.closeQuietly(stdInSink);
- }
-
- }
-
- public synchronized String function() {
- final StringBuffer buf = new StringBuffer("");
- SystemCallOutputListener tempOutputListener = new SystemCallOutputListener() {
- private Long lineCount = 0l;
-
- public void newLine(SystemCall systemCall, String line,
- Boolean isError) {
- if (!isError) {
- if (lineCount != 0l)
- buf.append('\n');
- buf.append(line);
- lineCount++;
- }
- }
- };
- addOutputListener(tempOutputListener);
- run();
- removeOutputListener(tempOutputListener);
- return buf.toString();
- }
-
- public String asCommand() {
- return createCommandLine().toString();
- }
-
- @Override
- public String toString() {
- return asCommand();
- }
-
- /**
- * Build a command line based on the properties. Can be overridden by
- * specific command wrappers.
- */
- protected CommandLine createCommandLine() {
- // Check if an OS specific command overrides
- String osName = System.getProperty("os.name");
- List<Object> commandToUse = null;
- if (osCommands.containsKey(osName))
- commandToUse = osCommands.get(osName);
- else
- commandToUse = command;
- String cmdToUse = null;
- if (osCmds.containsKey(osName))
- cmdToUse = osCmds.get(osName);
- else
- cmdToUse = cmd;
-
- CommandLine commandLine = null;
-
- // Which command definition to use
- if (commandToUse == null && cmdToUse == null)
- throw new SlcException("Please specify a command.");
- else if (commandToUse != null && cmdToUse != null)
- throw new SlcException(
- "Specify the command either as a line or as a list.");
- else if (cmdToUse != null) {
- if (chroot != null && !chroot.trim().equals(""))
- cmdToUse = "chroot \"" + chroot + "\" " + cmdToUse;
- if (sudo != null) {
- environmentVariables.put("SUDO_ASKPASS", askPassProgram);
- if (!sudo.trim().equals(""))
- cmdToUse = "sudo -p " + sudoPrompt + " -u " + sudo + " "
- + cmdToUse;
- else
- cmdToUse = "sudo -p " + sudoPrompt + " " + cmdToUse;
- }
-
- // GENERATE COMMAND LINE
- commandLine = CommandLine.parse(cmdToUse);
- } else if (commandToUse != null) {
- if (commandToUse.size() == 0)
- throw new SlcException("Command line is empty.");
-
- if (chroot != null && sudo != null) {
- commandToUse.add(0, "chroot");
- commandToUse.add(1, chroot);
- }
-
- if (sudo != null) {
- environmentVariables.put("SUDO_ASKPASS", askPassProgram);
- commandToUse.add(0, "sudo");
- commandToUse.add(1, "-p");
- commandToUse.add(2, sudoPrompt);
- if (!sudo.trim().equals("")) {
- commandToUse.add(3, "-u");
- commandToUse.add(4, sudo);
- }
- }
-
- // GENERATE COMMAND LINE
- commandLine = new CommandLine(commandToUse.get(0).toString());
-
- for (int i = 1; i < commandToUse.size(); i++) {
- if (log.isTraceEnabled())
- log.debug(commandToUse.get(i));
- commandLine.addArgument(commandToUse.get(i).toString());
- }
- } else {
- // all cases covered previously
- throw new UnsupportedException();
- }
-
- if (generateScript != null) {
- File scriptFile = new File(getExecDirToUse() + File.separator
- + generateScript);
- try {
- FileUtils.writeStringToFile(scriptFile,
- (osConsole != null ? osConsole + " " : "")
- + commandLine.toString());
- } catch (IOException e) {
- throw new SlcException("Could not generate script "
- + scriptFile, e);
- }
- commandLine = new CommandLine(scriptFile);
- } else {
- if (osConsole != null)
- commandLine = CommandLine.parse(osConsole + " "
- + commandLine.toString());
- }
-
- return commandLine;
- }
-
- /**
- * Creates a {@link PumpStreamHandler} which redirects streams to the custom
- * logging mechanism.
- */
- protected ExecuteStreamHandler createExecuteStreamHandler(
- final Writer stdOutWriter, final OutputStream stdOutputStream,
- final Writer stdErrWriter, final InputStream stdInStream) {
-
- // Log writers
- OutputStream stdout = stdOutputStream != null ? stdOutputStream
- : new LogOutputStream() {
- protected void processLine(String line, int level) {
- // if (firstLine) {
- // if (sudo != null && callbackHandler != null
- // && line.startsWith(sudoPrompt)) {
- // try {
- // PasswordCallback pc = new PasswordCallback(
- // "sudo password", false);
- // Callback[] cbs = { pc };
- // callbackHandler.handle(cbs);
- // char[] pwd = pc.getPassword();
- // char[] arr = Arrays.copyOf(pwd,
- // pwd.length + 1);
- // arr[arr.length - 1] = '\n';
- // IOUtils.write(arr, stdInSink);
- // stdInSink.flush();
- // } catch (Exception e) {
- // throw new SlcException(
- // "Cannot retrieve sudo password", e);
- // }
- // }
- // firstLine = false;
- // }
-
- if (line != null && !line.trim().equals(""))
- logStdOut(line);
-
- if (stdOutWriter != null)
- appendLineToFile(stdOutWriter, line);
- }
- };
-
- OutputStream stderr = new LogOutputStream() {
- protected void processLine(String line, int level) {
- if (line != null && !line.trim().equals(""))
- logStdErr(line);
- if (stdErrWriter != null)
- appendLineToFile(stdErrWriter, line);
- }
- };
-
- PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdout,
- stderr, stdInStream) {
-
- @Override
- public void stop() throws IOException {
- // prevents the method to block when joining stdin
- if (stdInSink != null)
- IOUtils.closeQuietly(stdInSink);
-
- super.stop();
- }
- };
- return pumpStreamHandler;
- }
-
- /** Creates the default {@link ExecuteResultHandler}. */
- protected ExecuteResultHandler createExecuteResultHandler(
- final CommandLine commandLine) {
- return new ExecuteResultHandler() {
-
- public void onProcessComplete(int exitValue) {
- String msg = "System call '" + commandLine
- + "' properly completed.";
- if (log.isTraceEnabled())
- log.trace(msg);
- if (testResult != null) {
- forwardPath(testResult);
- testResult.addResultPart(new SimpleResultPart(
- TestStatus.PASSED, msg));
- }
- releaseWatchdog();
- }
-
- public void onProcessFailed(ExecuteException e) {
-
- String msg = "System call '" + commandLine + "' failed.";
- if (testResult != null) {
- forwardPath(testResult);
- testResult.addResultPart(new SimpleResultPart(
- TestStatus.ERROR, msg, e));
- } else {
- if (exceptionOnFailed)
- throw new SlcException(msg, e);
- else
- log.error(msg, e);
- }
- releaseWatchdog();
- }
- };
- }
-
- @Deprecated
- protected void forwardPath(TestResult testResult) {
- // TODO: allocate a TreeSPath
- }
-
- /**
- * Shortcut method getting the execDir to use
- */
- protected String getExecDirToUse() {
- try {
- if (execDir != null) {
- return execDir;
- }
- return System.getProperty("user.dir");
- } catch (Exception e) {
- throw new SlcException("Cannot find exec dir", e);
- }
- }
-
- protected void logStdOut(String line) {
- for (SystemCallOutputListener outputListener : outputListeners)
- outputListener.newLine(this, line, false);
- log(stdOutLogLevel, line);
- }
-
- protected void logStdErr(String line) {
- for (SystemCallOutputListener outputListener : outputListeners)
- outputListener.newLine(this, line, true);
- log(stdErrLogLevel, line);
- }
-
- /** Log from the underlying streams. */
- protected void log(String logLevel, String line) {
- // TODO optimize
-// if (SecurityContextHolder.getContext().getAuthentication() == null) {
-// SecurityContextHolder.getContext()
-// .setAuthentication(authentication);
-// }
-
- if ("ERROR".equals(logLevel))
- log.error(line);
- else if ("WARN".equals(logLevel))
- log.warn(line);
- else if ("INFO".equals(logLevel))
- log.info(line);
- else if ("DEBUG".equals(logLevel))
- log.debug(line);
- else if ("TRACE".equals(logLevel))
- log.trace(line);
- else if (LOG_STDOUT.equals(logLevel))
- System.out.println(line);
- else if ("System.err".equals(logLevel))
- System.err.println(line);
- else
- throw new SlcException("Unknown log level " + logLevel);
- }
-
- /** Append line to a log file. */
- protected void appendLineToFile(Writer writer, String line) {
- try {
- writer.append(line).append('\n');
- } catch (IOException e) {
- log.error("Cannot write to log file", e);
- }
- }
-
- /** Creates the writer for the output/err files. */
- protected Writer createWriter(Resource target, Boolean append) {
- FileWriter writer = null;
- try {
-
- final File file;
- if (executionResources != null)
- file = new File(executionResources.getAsOsPath(target, true));
- else
- file = target.getFile();
- writer = new FileWriter(file, append);
- } catch (IOException e) {
- log.error("Cannot get file for " + target, e);
- IOUtils.closeQuietly(writer);
- }
- return writer;
- }
-
- /** Creates an outputstream for the output/err files. */
- 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;
- }
-
- /** Append the argument (for chaining) */
- public SystemCall arg(String arg) {
- if (command == null)
- command = new ArrayList<Object>();
- command.add(arg);
- return this;
- }
-
- /** Append the argument (for chaining) */
- public SystemCall arg(String arg, String value) {
- if (command == null)
- command = new ArrayList<Object>();
- command.add(arg);
- command.add(value);
- return this;
- }
-
- // CONTROL
- public synchronized Boolean isRunning() {
- return currentWatchdog != null;
- }
-
- private synchronized ExecuteWatchdog createWatchdog() {
-// if (currentWatchdog != null)
-// throw new SlcException("A process is already being monitored");
- currentWatchdog = new ExecuteWatchdog(watchdogTimeout);
- return currentWatchdog;
- }
-
- private synchronized void releaseWatchdog() {
- currentWatchdog = null;
- }
-
- public synchronized void kill() {
- if (currentWatchdog != null)
- currentWatchdog.destroyProcess();
- }
-
- /** */
- public void setCmd(String command) {
- this.cmd = command;
- }
-
- public void setCommand(List<Object> command) {
- this.command = command;
- }
-
- public void setExecDir(String execdir) {
- this.execDir = execdir;
- }
-
- public void setStdErrLogLevel(String stdErrLogLevel) {
- this.stdErrLogLevel = stdErrLogLevel;
- }
-
- public void setStdOutLogLevel(String stdOutLogLevel) {
- this.stdOutLogLevel = stdOutLogLevel;
- }
-
- public void setSynchronous(Boolean synchronous) {
- this.synchronous = synchronous;
- }
-
- public void setOsCommands(Map<String, List<Object>> osCommands) {
- this.osCommands = osCommands;
- }
-
- public void setOsCmds(Map<String, String> osCmds) {
- this.osCmds = osCmds;
- }
-
- public void setEnvironmentVariables(Map<String, String> environmentVariables) {
- this.environmentVariables = environmentVariables;
- }
-
- public Map<String, String> getEnvironmentVariables() {
- return environmentVariables;
- }
-
- public void setWatchdogTimeout(Long watchdogTimeout) {
- this.watchdogTimeout = watchdogTimeout;
- }
-
- public void setStdOutFile(Resource stdOutFile) {
- this.stdOutFile = stdOutFile;
- }
-
- public void setStdErrFile(Resource stdErrFile) {
- this.stdErrFile = stdErrFile;
- }
-
- public void setStdInFile(Resource stdInFile) {
- this.stdInFile = stdInFile;
- }
-
- public void setTestResult(TestResult testResult) {
- this.testResult = testResult;
- }
-
- public void setLogCommand(Boolean logCommand) {
- this.logCommand = logCommand;
- }
-
- public void setRedirectStreams(Boolean redirectStreams) {
- this.redirectStreams = redirectStreams;
- }
-
- public void setExceptionOnFailed(Boolean exceptionOnFailed) {
- this.exceptionOnFailed = exceptionOnFailed;
- }
-
- public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables) {
- this.mergeEnvironmentVariables = mergeEnvironmentVariables;
- }
-
- public void setOsConsole(String osConsole) {
- this.osConsole = osConsole;
- }
-
- public void setGenerateScript(String generateScript) {
- this.generateScript = generateScript;
- }
-
- public void setExecutionResources(ExecutionResources executionResources) {
- this.executionResources = executionResources;
- }
-
- public void setRedirectStdOut(Boolean redirectStdOut) {
- this.redirectStdOut = redirectStdOut;
- }
-
- public void addOutputListener(SystemCallOutputListener outputListener) {
- outputListeners.add(outputListener);
- }
-
- public void removeOutputListener(SystemCallOutputListener outputListener) {
- outputListeners.remove(outputListener);
- }
-
- public void setOutputListeners(
- List<SystemCallOutputListener> outputListeners) {
- this.outputListeners = outputListeners;
- }
-
- public void setExecutor(Executor executor) {
- this.executor = executor;
- }
-
- public void setSudo(String sudo) {
- this.sudo = sudo;
- }
-
- public void setCallbackHandler(CallbackHandler callbackHandler) {
- this.callbackHandler = callbackHandler;
- }
-
- public void setChroot(String chroot) {
- this.chroot = chroot;
- }
-
- private class DummyexecuteStreamHandler implements ExecuteStreamHandler {
-
- public void setProcessErrorStream(InputStream is) throws IOException {
- }
-
- public void setProcessInputStream(OutputStream os) throws IOException {
- }
-
- public void setProcessOutputStream(InputStream is) throws IOException {
- }
-
- public void start() throws IOException {
- }
-
- public void stop() {
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-public interface SystemCallOutputListener {
- public void newLine(SystemCall systemCall, String line, Boolean isError);
-}
+++ /dev/null
-package org.argeo.slc.core.execution.tasks;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.attachment.Attachment;
-import org.argeo.slc.attachment.AttachmentsEnabled;
-import org.argeo.slc.core.attachment.AttachmentUploader;
-import org.springframework.core.io.Resource;
-
-public class UploadAttachments implements Runnable {
- private AttachmentUploader attachmentUploader;
- private Attachment attachment = null;
- private Resource resource = null;
- private Map<Attachment, Resource> attachments = new HashMap<Attachment, Resource>();
- private List<AttachmentsEnabled> attachTo = new ArrayList<AttachmentsEnabled>();
- private Boolean newUuidPerExecution = true;
-
- public void run() {
- if (attachment != null) {
- if (resource == null)
- throw new SlcException("A resource must be specified.");
- uploadAndAdd(attachment, resource);
- }
-
- for (Attachment attachmentT : attachments.keySet()) {
- Resource resourceT = attachments.get(attachmentT);
- uploadAndAdd(attachmentT, resourceT);
- }
-
- }
-
- protected void uploadAndAdd(Attachment attachment, Resource resource) {
- if (newUuidPerExecution)
- attachment.setUuid(UUID.randomUUID().toString());
- attachmentUploader.upload(attachment, resource);
- for (AttachmentsEnabled attachmentsEnabled : attachTo) {
- attachmentsEnabled.addAttachment(attachment);
- }
- }
-
- public void setAttachmentUploader(AttachmentUploader attachmentUploader) {
- this.attachmentUploader = attachmentUploader;
- }
-
- public void setAttachments(Map<Attachment, Resource> attachments) {
- this.attachments = attachments;
- }
-
- public void setAttachTo(List<AttachmentsEnabled> attachTo) {
- this.attachTo = attachTo;
- }
-
- public void setAttachment(Attachment attachment) {
- this.attachment = attachment;
- }
-
- public void setResource(Resource resource) {
- this.resource = resource;
- }
-
- public void setNewUuidPerExecution(Boolean newUuidPerExecution) {
- this.newUuidPerExecution = newUuidPerExecution;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <bean id="task.echo" class="org.argeo.slc.core.execution.tasks.Echo"
- abstract="true" />
- <bean id="task.systemCall" class="org.argeo.slc.core.execution.tasks.SystemCall"
- abstract="true" />
- <bean id="task.closeTestResult" class="org.argeo.slc.core.execution.tasks.CloseTestResult"
- abstract="true" />
- <bean id="task.slcManager" class="org.argeo.slc.core.execution.tasks.SlcManager"
- abstract="true" />
- <bean id="task.overrideContextAware" class="org.argeo.slc.core.execution.tasks.OverrideContextAware"
- abstract="true" />
- <bean id="task.uploadAttachments" class="org.argeo.slc.core.execution.tasks.UploadAttachments"
- abstract="true" />
-
- <bean id="taskArg.attachment" class="org.argeo.slc.core.attachment.SimpleAttachment"
- abstract="true" />
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <bean id="slcTemplate.fileResources" class="org.argeo.slc.core.execution.FileExecutionResources"
- abstract="true" />
-
- <bean id="slcTemplate.resourcesFactoryBean" parent="slcTemplate.writableResource"
- abstract="true" />
-
- <bean id="slcTemplate.writableResource"
- class="org.argeo.slc.core.execution.ExecutionResourcesFactoryBean"
- abstract="true" />
-
- <bean id="slcTemplate.osFile" class="org.argeo.slc.core.execution.OsFileFactoryBean"
- abstract="true" />
-
-</beans>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <bean id="mergedLists" class="org.argeo.slc.core.execution.tasks.MergedLists"
- abstract="true">
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.DefaultExecutionFlow;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.springframework.beans.BeanMetadataElement;
-import org.springframework.beans.factory.config.BeanDefinitionHolder;
-import org.springframework.beans.factory.config.RuntimeBeanReference;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.support.ManagedList;
-import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Node;
-
-/** Publishes a {@link Runnable} as an {@link ExecutionFlow} */
-public class AsFlowDecorator implements BeanDefinitionDecorator {
- private CmsLog log = CmsLog.getLog(AsFlowDecorator.class);
-
- public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder bean,
- ParserContext ctx) {
- String attrValue = ((Attr) node).getValue();
- if (attrValue.charAt(attrValue.length() - 1) == '/')
- throw new SlcException(attrValue + " cannot end with a path");
- final String flowBeanName = attrValue;
-
- if (log.isTraceEnabled())
- log.trace("flowBeanName=" + flowBeanName);
-
- if (ctx.getRegistry().containsBeanDefinition(flowBeanName))
- throw new SlcException("A bean named " + flowBeanName
- + " is already defined.");
- BeanDefinitionBuilder flow = BeanDefinitionBuilder
- .rootBeanDefinition(DefaultExecutionFlow.class);
- ManagedList<BeanMetadataElement> executables = new ManagedList<BeanMetadataElement>(
- 1);
-
- String beanName = bean.getBeanName();
- if (beanName == null)
- executables.add(bean.getBeanDefinition());
- else
- executables.add(new RuntimeBeanReference(beanName));
-
- // if (path != null)
- // flow.addPropertyValue("path", path);
- flow.addPropertyValue("executables", executables);
-
- if (beanName != null)
- ctx.getRegistry().registerBeanDefinition(flowBeanName,
- flow.getBeanDefinition());
- return bean;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.springframework.aop.scope.ScopedProxyUtils;
-import org.springframework.beans.factory.config.BeanDefinitionHolder;
-import org.springframework.beans.factory.parsing.BeanComponentDefinition;
-import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Inspired by org.springframework.aop.config.ScopedProxyBeanDefinitionDecorator
- */
-public class ExecutionScopeDecorator implements BeanDefinitionDecorator {
- private static final String PROXY_TARGET_CLASS = "proxy-target-class";
-
- public BeanDefinitionHolder decorate(Node node,
- BeanDefinitionHolder definition, ParserContext parserContext) {
-
- definition.getBeanDefinition().setScope("execution");
-
- // Default: CGLib not used
- boolean proxyTargetClass = false;
- if (node instanceof Element) {
- Element ele = (Element) node;
- if (ele.hasAttribute(PROXY_TARGET_CLASS)) {
- proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS)).booleanValue();
- }
- }
-
- // Register the original bean definition as it will be referenced by the scoped proxy and is relevant for tooling (validation, navigation).
- String targetBeanName = ScopedProxyUtils.getTargetBeanName(definition.getBeanName());
- parserContext.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName));
-
- return ScopedProxyUtils.createScopedProxy(definition, parserContext.getRegistry(), proxyTargetClass);
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.DefaultExecutionFlow;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.springframework.beans.factory.BeanDefinitionStoreException;
-import org.springframework.beans.factory.config.RuntimeBeanReference;
-import org.springframework.beans.factory.support.AbstractBeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.support.ManagedList;
-import org.springframework.beans.factory.support.ManagedMap;
-import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.util.StringUtils;
-import org.springframework.util.xml.DomUtils;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/** Interprets the <flow:flow> tag */
-public class FlowBeanDefinitionParser extends
- AbstractSingleBeanDefinitionParser {
- private CmsLog log = CmsLog.getLog(FlowBeanDefinitionParser.class);
-
- /** Whether the user has already be warned on path attribute usage. */
- private Boolean warnedAboutPathAttribute = false;
-
- @Override
- protected void doParse(Element element, ParserContext parserContext,
- BeanDefinitionBuilder builder) {
- String path = element.getAttribute("path");
- if (StringUtils.hasText(path)) {
- builder.addPropertyValue("path", path);
-
- // warns user only once
- if (!warnedAboutPathAttribute)
- log.warn("The path=\"\" attribute is deprecated"
- + " and will be removed in a later release."
- + " Use <flow:flow name=\"/my/path/flowName\">.");
- warnedAboutPathAttribute = true;
- }
-
- String spec = element.getAttribute("spec");
- if (StringUtils.hasText(spec))
- builder.getBeanDefinition().getConstructorArgumentValues()
- .addGenericArgumentValue(new RuntimeBeanReference(spec));
-
- String abstrac = element.getAttribute("abstract");
- if (StringUtils.hasText(abstrac))
- builder.setAbstract(Boolean.parseBoolean(abstrac));
-
- String parent = element.getAttribute("parent");
- if (StringUtils.hasText(parent))
- builder.setParentName(parent);
-
- builder.getBeanDefinition().setDescription(
- DomUtils.getChildElementValueByTagName(element, "description"));
-
- List<Element> argsElems = new ArrayList<Element>();
- List<Element> execElems = new ArrayList<Element>();
- List<Element> specElems = new ArrayList<Element>();
- NodeList nodeList = element.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node node = nodeList.item(i);
- if (node instanceof Element) {
- if (DomUtils.nodeNameEquals(node, "arg"))
- argsElems.add((Element) node);
- else if (DomUtils.nodeNameEquals(node, "spec"))
- specElems.add((Element) node);
- else if (!DomUtils.nodeNameEquals(node, "description"))
- execElems.add((Element) node);
- }
- }
-
- // Arguments
- if (argsElems.size() != 0) {
- ManagedMap<String, Object> args = new ManagedMap<String, Object>(
- argsElems.size());
- for (Element argElem : argsElems) {
- Object value = NamespaceUtils.parseValue(argElem,
- parserContext, builder.getBeanDefinition(), null);
- if (value != null)
- args.put(argElem.getAttribute("name"), value);
- else
- throw new SlcException("No value defined.");
- }
- builder.getBeanDefinition().getConstructorArgumentValues()
- .addGenericArgumentValue(args);
- }
-
- // Execution specs
- if (StringUtils.hasText(spec) && specElems.size() != 0)
- throw new SlcException("A flow cannot have multiple specs");
- if (specElems.size() == 1) {
- Object specObj = NamespaceUtils.parseBeanOrReference(
- specElems.get(0), parserContext,
- builder.getBeanDefinition());
- builder.getBeanDefinition().getConstructorArgumentValues()
- .addGenericArgumentValue(specObj);
- } else if (specElems.size() > 1)
- throw new SlcException("A flow cannot have multiple specs");
-
- // Executables
- if (execElems.size() != 0) {
- ManagedList<Object> executables = new ManagedList<Object>(
- execElems.size());
- for (Element child : execElems) {
- // child validity check is performed in xsd
- executables.add(NamespaceUtils.parseBeanOrReference(child,
- parserContext, builder.getBeanDefinition()));
- }
- if (executables.size() > 0)
- builder.addPropertyValue("executables", executables);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected Class<? extends ExecutionFlow> getBeanClass(Element element) {
- String clss = element.getAttribute("class");
- if (StringUtils.hasText(clss))
- // TODO: check that it actually works
- try {
- return (Class<? extends ExecutionFlow>) getClass()
- .getClassLoader().loadClass(clss);
- } catch (ClassNotFoundException e) {
- try {
- return (Class<? extends ExecutionFlow>) Thread
- .currentThread().getContextClassLoader()
- .loadClass(clss);
- } catch (ClassNotFoundException e1) {
- throw new SlcException("Cannot load class " + clss, e);
- }
- }
- else
- return DefaultExecutionFlow.class;
- }
-
- // parse nested bean definition
- // private Object parseBeanReference(Element element,
- // ParserContext parserContext, BeanDefinitionBuilder builder) {
- // return parserContext.getDelegate().parsePropertySubElement(element,
- // builder.getBeanDefinition());
- // }
-
- @Override
- protected String resolveId(Element element,
- AbstractBeanDefinition definition, ParserContext parserContext)
- throws BeanDefinitionStoreException {
- String name = element.getAttribute("name");
- if (StringUtils.hasText(name)) {
- return name;
- } else {
- return super.resolveId(element, definition, parserContext);
- }
- }
-
- protected boolean shouldGenerateIdAsFallback() {
- return true;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
-
-public class FlowNamespaceHandler extends NamespaceHandlerSupport {
-
- public void init() {
- registerBeanDefinitionParser("flow", new FlowBeanDefinitionParser());
- registerBeanDefinitionParser("spec", new SpecBeanDefinitionParser());
- registerBeanDefinitionDecoratorForAttribute("as-flow",
- new AsFlowDecorator());
- registerBeanDefinitionParser("param", new ParamDecorator());
-
- // The objective was to replace
- // - attribute scope="execution"
- // - and element "aop:scoped-proxy"
- // by a single attribute, using an attribute decorator
- // this does not work correctly with other attribute decorators (e.g.
- // p namespace) since this decorator needs to be called after all
- // properties have been set on target bean.
- // It works properly with element decorators (called after all attribute
- // decorators
- registerBeanDefinitionDecorator("variable", new ExecutionScopeDecorator());
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.config.RuntimeBeanReference;
-import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.util.xml.DomUtils;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * Utilities to simplify common tasks when interpreting a custom namespace and
- * converting it into bean definitions.
- */
-public class NamespaceUtils {
- // private final static CmsLog log = CmsLog.getLog(NamespaceUtils.class);
-
- /**
- * Returns the value defined either: directly by the the 'value' attribute,
- * as reference by the 'ref' attribute or as a nested bean.
- */
- public static Object parseValue(Element element,
- ParserContext parserContext,
- BeanDefinition containingBeanDefintion, String valueTagName) {
- Object value = null;
- if (element.hasAttribute("value")) {
- value = element.getAttribute("value");
- }
-
- if (element.hasAttribute("ref")) {
- if (value != null)
- throw new SlcException("Multiple value definition for "
- + element);
- value = new RuntimeBeanReference(element.getAttribute("ref"));
- }
-
- Element uniqueSubElem = null;
- if (valueTagName != null) {
- Element valueElem = DomUtils.getChildElementByTagName(element,
- valueTagName);
- if (valueElem != null) {
- uniqueSubElem = findUniqueSubElement(valueElem);
- if (uniqueSubElem == null)
- throw new SlcException("No subelement found under "
- + valueElem);
- }
- } else {// no intermediary tag
- uniqueSubElem = findUniqueSubElement(element);
- }
-
- if (uniqueSubElem != null) {
- if (value != null)
- throw new SlcException("Multiple value definition for "
- + element);
- value = parseBeanOrReference(uniqueSubElem, parserContext,
- containingBeanDefintion);
- }
- return value;
- }
-
- public static Element findUniqueSubElement(Element element) {
- NodeList childNodes = element.getChildNodes();
-
- Element uniqueSubElem = null;
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node node = childNodes.item(i);
- if (node != null && node instanceof Element) {
- if (uniqueSubElem == null)
- uniqueSubElem = (Element) node;
- else
- throw new SlcException(
- "There are more than one sub element under "
- + element);
- }
- }
- return uniqueSubElem;
- }
-
- public static Object parseBeanOrReference(Element element,
- ParserContext parserContext, BeanDefinition beanDefinition) {
- // return parserContext.getDelegate().parsePropertySubElement(element,
- // beanDefinition);
-
- BeanDefinitionParserDelegate deleg = parserContext.getDelegate();
- // if ("bean".equals(element.getNodeName()))
- // return deleg.parseBeanDefinitionElement(element, beanDefinition);
- // else
- return deleg.parsePropertySubElement(element, beanDefinition);
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import org.argeo.slc.core.execution.ParameterRef;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.util.StringUtils;
-import org.w3c.dom.Element;
-
-public class ParamDecorator extends AbstractSingleBeanDefinitionParser {
-
- // public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder
- // bean,
- // ParserContext ctx) {
- // String paramName = ((Element) node).getAttribute("name");
- // String propertyName = ((Element) node.getParentNode())
- // .getAttribute("name");
- // BeanDefinitionBuilder parameterRef = BeanDefinitionBuilder
- // .genericBeanDefinition(ParameterRef.class);
- // parameterRef.addPropertyReference("instantiationManager",
- // "instantiationManager");
- // parameterRef.addConstructorArgValue(paramName);
- // bean.getBeanDefinition().getPropertyValues().addPropertyValue(
- // propertyName, parameterRef.getBeanDefinition());
- // return bean;
- // }
-
- @Override
- protected void doParse(Element element, ParserContext parserContext,
- BeanDefinitionBuilder builder) {
- String paramName = element.getAttribute("name");
-
- String instantationManagerRef = element
- .getAttribute("instantiationManager");
- if (!StringUtils.hasText(instantationManagerRef))
- instantationManagerRef = "instantiationManager";
- builder.addPropertyReference("instantiationManager",
- instantationManagerRef);
- builder.addConstructorArgValue(paramName);
- }
-
- @Override
- protected Class<ParameterRef> getBeanClass(Element element) {
- return ParameterRef.class;
- }
-}
+++ /dev/null
-package org.argeo.slc.core.execution.xml;
-
-import java.util.List;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.core.execution.DefaultExecutionSpec;
-import org.argeo.slc.execution.RefSpecAttribute;
-import org.argeo.slc.execution.RefValueChoice;
-import org.argeo.slc.primitive.PrimitiveSpecAttribute;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionBuilder;
-import org.springframework.beans.factory.support.ManagedList;
-import org.springframework.beans.factory.support.ManagedMap;
-import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.util.StringUtils;
-import org.springframework.util.xml.DomUtils;
-import org.w3c.dom.Element;
-
-/** Interprets the <flow:spec> tag */
-public class SpecBeanDefinitionParser extends
- AbstractSingleBeanDefinitionParser {
- private CmsLog log = CmsLog.getLog(SpecBeanDefinitionParser.class);
-
- @Override
- protected void doParse(Element element, ParserContext parserContext,
- BeanDefinitionBuilder builder) {
- builder.getBeanDefinition().setDescription(
- DomUtils.getChildElementValueByTagName(element, "description"));
-
- ManagedMap<String, BeanDefinition> attributes = new ManagedMap<String, BeanDefinition>();
-
- // Primitives
- for (Element child : (List<Element>) DomUtils
- .getChildElementsByTagName(element, "primitive")) {
- BeanDefinitionBuilder childBuilder = BeanDefinitionBuilder
- .genericBeanDefinition(PrimitiveSpecAttribute.class);
- addCommonProperties(child, parserContext, childBuilder);
-
- String type = child.getAttribute("type");
- if (StringUtils.hasText(type))
- childBuilder.addPropertyValue("type", type);
-
- putInAttributes(attributes, child,
- childBuilder.getBeanDefinition(), "primitive");
- }
-
- // Refs
- for (Element refAttrElem : (List<Element>) DomUtils
- .getChildElementsByTagName(element, "ref")) {
- BeanDefinitionBuilder refAttrBuilder = BeanDefinitionBuilder
- .genericBeanDefinition(RefSpecAttribute.class);
- addCommonProperties(refAttrElem, parserContext, refAttrBuilder);
-
- String targetClassName = refAttrElem.getAttribute("targetClass");
- if (StringUtils.hasText(targetClassName))
- refAttrBuilder.addPropertyValue("targetClass", targetClassName);
-
- // Choices
- Element choicesElem = DomUtils.getChildElementByTagName(
- refAttrElem, "choices");
- if (choicesElem != null) {
- List<Element> choices = DomUtils.getChildElementsByTagName(
- choicesElem, "choice");
- ManagedList<BeanDefinition> choiceBeans = new ManagedList<BeanDefinition>(
- choices.size());
- for (Element choiceElem : choices) {
- BeanDefinitionBuilder choiceBuilder = BeanDefinitionBuilder
- .genericBeanDefinition(RefValueChoice.class);
- choiceBuilder.addPropertyValue("name",
- choiceElem.getAttribute("name"));
- String desc = choiceElem.getAttribute("description");
- if (StringUtils.hasText(desc))
- choiceBuilder.addPropertyValue("description", desc);
-
- choiceBeans.add(choiceBuilder.getBeanDefinition());
- }
- refAttrBuilder.addPropertyValue("choices", choiceBeans);
- }
-
- putInAttributes(attributes, refAttrElem,
- refAttrBuilder.getBeanDefinition(), "ref");
- }
-
- builder.addPropertyValue("attributes", attributes);
- }
-
- protected void addCommonProperties(Element element,
- ParserContext parserContext, BeanDefinitionBuilder specAttr) {
- addBooleanProperty("isImmutable", specAttr, element);
- addBooleanProperty("isConstant", specAttr, element);
- addBooleanProperty("isHidden", specAttr, element);
- addBooleanProperty("isParameter", specAttr, element);
- addBooleanProperty("isFrozen", specAttr, element);
-
- Object value = NamespaceUtils.parseValue(element, parserContext,
- specAttr.getBeanDefinition(), "value");
- if (value != null)
- specAttr.addPropertyValue("value", value);
-
- }
-
- protected void putInAttributes(
- ManagedMap<String, BeanDefinition> attributes, Element child,
- BeanDefinition beanDefinition, String nature) {
- String name = child.getAttribute("name");
- attributes.put(name, beanDefinition);
- if (log.isTraceEnabled())
- log.debug("Added " + nature + " attribute " + name);
-
- }
-
- private void addBooleanProperty(String name,
- BeanDefinitionBuilder specAttr, Element element) {
- String bool = element.getAttribute(name);
- if (StringUtils.hasText(bool))
- specAttr.addPropertyValue(name, Boolean.parseBoolean(bool));
-
- }
-
- @Override
- protected Class<DefaultExecutionSpec> getBeanClass(Element element) {
- return DefaultExecutionSpec.class;
- }
-
- protected boolean shouldGenerateIdAsFallback() {
- return false;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:flow="http://www.argeo.org/schema/slc-flow" xmlns:beans="http://www.springframework.org/schema/beans"
- targetNamespace="http://www.argeo.org/schema/slc-flow"
- elementFormDefault="qualified" attributeFormDefault="unqualified">
-
- <xsd:import namespace="http://www.springframework.org/schema/beans"
- schemaLocation="http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" />
-
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- SLC Flow Schema, version 0.12
- Authors: Mathieu Baudier
-
- This simplifies the definition of SLC flows and their integration with
- regular Spring beans.
- ]]></xsd:documentation>
- </xsd:annotation>
-
- <xsd:element name="flow">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Adds an SLC execution flow, using the default implementation.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:complexContent>
- <xsd:extension base="beans:identifiedType">
- <xsd:sequence>
- <xsd:element ref="beans:description" minOccurs="0" />
- <xsd:sequence>
- <xsd:element name="arg" minOccurs="0" maxOccurs="unbounded"
- type="flow:argType">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Parameter for an execution flow which will override at instantiation the
- value of the parameter already defined as default value or in a parent bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:sequence>
- <xsd:sequence>
- <xsd:choice minOccurs="0" maxOccurs="unbounded">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="flow:flow" />
- </xsd:choice>
- <!--
- <xsd:any namespace="##other" processContents="strict"
- minOccurs="0" maxOccurs="unbounded" />
- -->
- </xsd:sequence>
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Name of the flow (alternative to ID).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="class" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Another implementation of execution flow.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="path" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The hierarchical path under which to register this flow.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="spec" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference to the related specification bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="parent" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The parent bean definition (in Spring sense).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="abstract" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether this flow is abstract (in Spring sense).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:element name="spec">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- SLC flow specifications, defining the parameters and variables
- which can be used in related flows, along with their default values and
- various constraints.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:complexContent>
- <xsd:extension base="beans:identifiedType">
- <xsd:sequence>
- <xsd:element ref="beans:description" minOccurs="0" />
- <xsd:choice minOccurs="0" maxOccurs="unbounded">
- <xsd:element name="primitive" type="flow:primitiveSpecAttributeType"
- minOccurs="0" maxOccurs="unbounded">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A primitive specification attribute, that is, a plain standard value
- and not a reference to an object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- <xsd:element name="ref" type="flow:refSpecAttributeType"
- minOccurs="0" maxOccurs="unbounded">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference specification attribute, that is, a reference to another object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:choice>
- </xsd:sequence>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:complexType name="specAttributeType">
- <xsd:choice>
- <xsd:element name="value" minOccurs="0" maxOccurs="1">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute as an inner bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:choice minOccurs="1" maxOccurs="1">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="beans:list" />
- <xsd:element ref="beans:set" />
- <xsd:element ref="beans:map" />
- <xsd:element ref="beans:props" />
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the attribute, under which in can then be referenced.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="value" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="ref" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute as a reference to another bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isParameter" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is a parameter, that is, it has to be set at
- instantiation but can be modified afterwards for objects of scope execution.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isFrozen" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is frozen, that is, it cannot be modified at runtime.
- A frozen attribute has to be a parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isHidden" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is hidden, that is, it should not be displayed in UIs.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:complexType name="primitiveSpecAttributeType">
- <xsd:complexContent>
- <xsd:extension base="flow:specAttributeType">
- <xsd:attribute name="type" default="string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The type of the primitive specification attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:string">
- <xsd:enumeration value="string" />
- <xsd:enumeration value="integer" />
- <xsd:enumeration value="long" />
- <xsd:enumeration value="float" />
- <xsd:enumeration value="double" />
- <xsd:enumeration value="boolean" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
-
- <xsd:complexType name="refSpecAttributeType">
- <xsd:complexContent>
- <xsd:extension base="flow:specAttributeType">
- <xsd:choice>
- <xsd:element name="choices" minOccurs="0" maxOccurs="1">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Possible values to chose from, if ommitted, all the beans in the
- application context which implement the provided targetClass will
- be considered.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:choice>
- <xsd:element name="choice" minOccurs="0" maxOccurs="unbounded"
- type="flow:refChoiceType">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A choice for a reference specification attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- <xsd:attribute name="targetClass" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The class that has to be implemented by the underlying object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
-
- <xsd:complexType name="refChoiceType">
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="description" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A human readable description of this choice.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:complexType name="argType">
- <xsd:choice minOccurs="0" maxOccurs="1">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="flow:param" />
- <xsd:element ref="beans:list" />
- <xsd:element ref="beans:set" />
- <xsd:element ref="beans:map" />
- <xsd:element ref="beans:props" />
- </xsd:choice>
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="value" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The plain value of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="ref" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The value of the related parameter as a reference to a bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:attribute name="as-flow" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- If decorating an executable bean, it will generate an implicit SLC
- execution flow with the provided value as name.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <!--
- <xsd:attribute name="var" type="xsd:boolean"> <xsd:annotation>
- <xsd:documentation><![CDATA[ If true, the decorated bean is set to
- scope execution and proxied. ]]></xsd:documentation> </xsd:annotation>
- </xsd:attribute>
- -->
-
- <xsd:element name="variable">
- <xsd:complexType>
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Marks a bean definition as being variable, i.e. a scoped proxy of scope execution
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:attribute name="proxy-target-class" type="xsd:boolean"
- default="true">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Are class-based (CGLIB) proxies to be created?
- This is the default;
- in order to switch to standard Java
- interface-based proxies, turn this flag to
- "false".
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:element name="param">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- If within a property tag of a bean, it will set the value of this property
- with a reference to a parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:attribute name="name" type="xsd:string" use="required">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="instantiationManager" type="xsd:string"
- use="optional" default="instantiationManager">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference to the instantiation manager to use instead of the default one
- (expert usage).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
- </xsd:element>
-
-</xsd:schema>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:flow="http://www.argeo.org/schema/slc-flow" xmlns:beans="http://www.springframework.org/schema/beans"
- targetNamespace="http://www.argeo.org/schema/slc-flow"
- elementFormDefault="qualified" attributeFormDefault="unqualified">
-
- <xsd:import namespace="http://www.springframework.org/schema/beans"
- schemaLocation="http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" />
-
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- SLC Flow Schema, version 1.2
- Authors: Mathieu Baudier
-
- This simplifies the definition of SLC flows and their integration with
- regular Spring beans.
- ]]></xsd:documentation>
- </xsd:annotation>
-
- <xsd:element name="flow">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Adds an SLC execution flow, using the default implementation.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:complexContent>
- <xsd:extension base="beans:identifiedType">
- <xsd:sequence>
- <xsd:element ref="beans:description" minOccurs="0" />
- <xsd:sequence>
- <xsd:element name="arg" minOccurs="0" maxOccurs="unbounded"
- type="flow:argType">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Parameter for an execution flow which will override at instantiation the
- value of the parameter already defined as default value or in a parent bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:sequence>
- <xsd:sequence>
- <xsd:choice minOccurs="0" maxOccurs="unbounded">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="flow:flow" />
- <xsd:element ref="flow:spec" />
- </xsd:choice>
- <!-- <xsd:any namespace="##other" processContents="strict" minOccurs="0"
- maxOccurs="unbounded" /> -->
- </xsd:sequence>
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Name of the flow (alternative to ID).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="class" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Another implementation of execution flow.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="path" type="xsd:string">
- <!-- DEPRECATED: not used anymore -->
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The hierarchical path under which to register this flow.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="spec" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference to the related specification bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="parent" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The parent bean definition (in Spring sense).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="abstract" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether this flow is abstract (in Spring sense).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:element name="spec">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- SLC flow specifications, defining the parameters and variables
- which can be used in related flows, along with their default values and
- various constraints.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:complexContent>
- <xsd:extension base="beans:identifiedType">
- <xsd:sequence>
- <xsd:element ref="beans:description" minOccurs="0" />
- <xsd:choice minOccurs="0" maxOccurs="unbounded">
- <xsd:element name="primitive" type="flow:primitiveSpecAttributeType"
- minOccurs="0" maxOccurs="unbounded">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A primitive specification attribute, that is, a plain standard value
- and not a reference to an object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- <xsd:element name="ref" type="flow:refSpecAttributeType"
- minOccurs="0" maxOccurs="unbounded">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference specification attribute, that is, a reference to another object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:choice>
- </xsd:sequence>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:complexType name="specAttributeType">
- <xsd:choice>
- <xsd:element name="value" minOccurs="0" maxOccurs="1">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute as an inner bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:choice minOccurs="1" maxOccurs="1">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="beans:list" />
- <xsd:element ref="beans:set" />
- <xsd:element ref="beans:map" />
- <xsd:element ref="beans:props" />
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the attribute, under which in can then be referenced.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="value" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="ref" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The default value of the attribute as a reference to another bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isImmutable" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is a parameter, that is, it has to be set at
- instantiation but can be modified afterwards for objects of scope execution.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isParameter" use="optional" type="xsd:boolean"
- default="false">
- <!-- DEPRECATED: old name of isImmutable -->
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is a parameter, that is, it has to be set at
- instantiation but can be modified afterwards for objects of scope execution.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isConstant" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is frozen, that is, it cannot be modified at runtime.
- A frozen attribute has to be a parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isFrozen" use="optional" type="xsd:boolean"
- default="false">
- <!-- DEPRECATED: old name of isConstant -->
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is frozen, that is, it cannot be modified at runtime.
- A frozen attribute has to be a parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="isHidden" use="optional" type="xsd:boolean"
- default="false">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Whether the attribute is hidden, that is, it should not be displayed in UIs.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:complexType name="primitiveSpecAttributeType">
- <xsd:complexContent>
- <xsd:extension base="flow:specAttributeType">
- <xsd:attribute name="type" default="string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The type of the primitive specification attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:string">
- <xsd:enumeration value="string" />
- <xsd:enumeration value="password" />
- <xsd:enumeration value="integer" />
- <xsd:enumeration value="long" />
- <xsd:enumeration value="float" />
- <xsd:enumeration value="double" />
- <xsd:enumeration value="boolean" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
-
- <xsd:complexType name="refSpecAttributeType">
- <xsd:complexContent>
- <xsd:extension base="flow:specAttributeType">
- <xsd:choice>
- <xsd:element name="choices" minOccurs="0" maxOccurs="1">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Possible values to chose from, if ommitted, all the beans in the
- application context which implement the provided targetClass will
- be considered.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:choice>
- <xsd:element name="choice" minOccurs="0" maxOccurs="unbounded"
- type="flow:refChoiceType">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A choice for a reference specification attribute.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:element>
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- <xsd:attribute name="targetClass" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The class that has to be implemented by the underlying object.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
-
- <xsd:complexType name="refChoiceType">
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="description" use="optional" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A human readable description of this choice.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:complexType name="argType">
- <xsd:choice minOccurs="0" maxOccurs="1">
- <xsd:element ref="beans:bean" />
- <xsd:element ref="beans:ref" />
- <xsd:element ref="flow:param" />
- <xsd:element ref="beans:list" />
- <xsd:element ref="beans:set" />
- <xsd:element ref="beans:map" />
- <xsd:element ref="beans:props" />
- </xsd:choice>
- <xsd:attribute name="name" use="required" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="value" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The plain value of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="ref" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The value of the related parameter as a reference to a bean.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
-
- <xsd:attribute name="as-flow" type="xsd:string">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- If decorating an executable bean, it will generate an implicit SLC
- execution flow with the provided value as name.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <!-- <xsd:attribute name="var" type="xsd:boolean"> <xsd:annotation> <xsd:documentation><![CDATA[
- If true, the decorated bean is set to scope execution and proxied. ]]></xsd:documentation>
- </xsd:annotation> </xsd:attribute> -->
-
- <xsd:element name="variable">
- <xsd:complexType>
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Marks a bean definition as being variable, i.e. a scoped proxy of scope execution
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:attribute name="proxy-target-class" type="xsd:boolean"
- default="true">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- Are class-based (CGLIB) proxies to be created?
- This is the default;
- in order to switch to standard Java
- interface-based proxies, turn this flag to
- "false".
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:element name="param">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- If within a property tag of a bean, it will set the value of this property
- with a reference to a parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:attribute name="name" type="xsd:string" use="required">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- The name of the related parameter.
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- <xsd:attribute name="instantiationManager" type="xsd:string"
- use="optional" default="instantiationManager">
- <xsd:annotation>
- <xsd:documentation><![CDATA[
- A reference to the instantiation manager to use instead of the default one
- (expert usage).
- ]]></xsd:documentation>
- </xsd:annotation>
- </xsd:attribute>
- </xsd:complexType>
- </xsd:element>
-
-</xsd:schema>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.core.test.context;
-
-import org.argeo.slc.runtime.test.TestDataUtils;
-import org.argeo.slc.test.TestData;
-import org.argeo.slc.test.TestDataProvider;
-
-public class DefaultContextTestData extends SimpleContextAware implements
- TestData, TestDataProvider {
-
- public <T extends TestData> T getTestData(Class<T> clss, String key) {
- return TestDataUtils.getItSelf(clss, this);
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.test.context;
-
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.runtime.test.ContextUtils;
-import org.argeo.slc.test.context.ContextAware;
-import org.argeo.slc.test.context.ParentContextAware;
-import org.springframework.beans.factory.InitializingBean;
-
-public class SimpleContextAware implements ContextAware, InitializingBean {
- private ParentContextAware parentContext;
-
- private Map<String, Object> values = new TreeMap<String, Object>();
- private Map<String, Object> expectedValues = new TreeMap<String, Object>();
-
- private String contextSkipFlag = DEFAULT_SKIP_FLAG;
- private String contextAnyFlag = DEFAULT_ANY_FLAG;
-
- public Map<String, Object> getValues() {
- return values;
- }
-
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
-
- public Map<String, Object> getExpectedValues() {
- return expectedValues;
- }
-
- public void setExpectedValues(Map<String, Object> expectedValues) {
- this.expectedValues = expectedValues;
- }
-
- /** Used to add this context as a child by setting a property. */
- public void setParentContext(ParentContextAware parentContextAware) {
- if (parentContext != null)
- throw new SlcException("Parent context already set");
- this.parentContext = parentContextAware;
- this.parentContext.addChildContext(this);
- }
-
- protected ParentContextAware getParentContext() {
- return parentContext;
- }
-
- public void afterPropertiesSet() throws Exception {
- if (parentContext != null) {
- ContextUtils.synchronize(parentContext);
- }
- }
-
- public String getContextSkipFlag() {
- return contextSkipFlag;
- }
-
- public void setContextSkipFlag(String contextSkipFlag) {
- this.contextSkipFlag = contextSkipFlag;
- }
-
- public String getContextAnyFlag() {
- return contextAnyFlag;
- }
-
- public void setContextAnyFlag(String contextAnyFlag) {
- this.contextAnyFlag = contextAnyFlag;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.core.test.context;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Vector;
-
-import org.argeo.slc.runtime.test.ContextUtils;
-import org.argeo.slc.test.context.ContextAware;
-import org.argeo.slc.test.context.ParentContextAware;
-import org.springframework.beans.factory.InitializingBean;
-
-public class SimpleParentContextAware extends SimpleContextAware implements
- ParentContextAware, InitializingBean {
- private List<ContextAware> children = new Vector<ContextAware>();
-
- public Collection<ContextAware> getChildContexts() {
- return children;
- }
-
- public void addChildContext(ContextAware contextAware) {
- children.add(contextAware);
- }
-
- @Override
- public void afterPropertiesSet() throws Exception {
- if (getParentContext() != null) {
- // If has a parent, sync it.
- super.afterPropertiesSet();
- } else {
- if (children.size() > 0) {
- // No need to synchronize if no children
- ContextUtils.synchronize(this);
- }
- }
- }
-}
+++ /dev/null
-<html>\r
-<head></head>\r
-<body>\r
-Context variables to be passed between parts of tests.\r
-</body>\r
-</html>
\ No newline at end of file
+++ /dev/null
-<html>\r
-<head></head>\r
-<body>\r
-SLC Test: test of software systems.\r
-</body>\r
-</html>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- 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.
-
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
- default-lazy-init="true">
-
- <bean name="slcDefault.test.testRun"
- class="org.argeo.slc.runtime.test.SimpleTestRun"
- scope="prototype">
- </bean>
-
- <bean name="slcDefault.test.uuid" class="java.util.UUID"
- factory-method="randomUUID" scope="prototype">
- </bean>
-
- <bean id="slcDefault.test.basicSimpleTestResult"
- class="org.argeo.slc.runtime.test.SimpleTestResult"
- abstract="true">
- <property name="uuid">
- <bean factory-bean="slcDefault.test.uuid"
- factory-method="toString">
- </bean>
- </property>
- </bean>
-
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.osgi;
-
-/** <b>Experimental</b> A structured set of OSGi bundles. */
-public interface BundleRegister {
- /**
- * @param pkg
- * the Java package
- * @param version
- * the version, can be only major.minor or null
- * @return the bundle providing this package or null if none was found
- */
- public String bundleProvidingPackage(String pkg, String version);
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.util.Collection;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.eclipse.gemini.blueprint.context.BundleContextAware;
-import org.eclipse.gemini.blueprint.context.event.OsgiBundleApplicationContextEvent;
-import org.eclipse.gemini.blueprint.context.event.OsgiBundleApplicationContextListener;
-import org.eclipse.gemini.blueprint.context.event.OsgiBundleContextClosedEvent;
-import org.eclipse.gemini.blueprint.context.event.OsgiBundleContextFailedEvent;
-import org.eclipse.gemini.blueprint.context.event.OsgiBundleContextRefreshedEvent;
-import org.eclipse.gemini.blueprint.util.OsgiBundleUtils;
-import org.eclipse.gemini.blueprint.util.OsgiFilterUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.Constants;
-import org.osgi.framework.FrameworkEvent;
-import org.osgi.framework.FrameworkListener;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.util.tracker.ServiceTracker;
-import org.springframework.beans.factory.DisposableBean;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.context.ApplicationContext;
-import org.springframework.util.Assert;
-
-/** Wraps low-level access to a {@link BundleContext} */
-@SuppressWarnings("deprecation")
-public class BundlesManager implements BundleContextAware, FrameworkListener,
- InitializingBean, DisposableBean,
- OsgiBundleApplicationContextListener<OsgiBundleApplicationContextEvent> {
- private final static CmsLog log = CmsLog.getLog(BundlesManager.class);
-
- private BundleContext bundleContext;
-
- private Long defaultTimeout = 60 * 1000l;
- private Long pollingPeriod = 200l;
-
- // Refresh sync objects
- private final Object refreshedPackageSem = new Object();
- private Boolean packagesRefreshed = false;
-
- public BundlesManager() {
- }
-
- public BundlesManager(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- /**
- * Stop the module, update it, refresh it and restart it. All synchronously.
- */
- public void upgradeSynchronous(OsgiBundle osgiBundle) {
- try {
- Bundle bundle = findRelatedBundle(osgiBundle);
-
- long begin = System.currentTimeMillis();
-
- long bStop = begin;
- stopSynchronous(bundle);
-
- long bUpdate = System.currentTimeMillis();
- updateSynchronous(bundle);
-
- // Refresh in case there are fragments
- long bRefresh = System.currentTimeMillis();
- refreshSynchronous(bundle);
-
- long bStart = System.currentTimeMillis();
- startSynchronous(bundle);
-
- long aStart = System.currentTimeMillis();
- if (log.isTraceEnabled()) {
- log.debug("OSGi upgrade performed in " + (aStart - begin)
- + "ms for bundle " + osgiBundle);
- log.debug(" stop \t: " + (bUpdate - bStop) + "ms");
- log.debug(" update\t: " + (bRefresh - bUpdate) + "ms");
- log.debug(" refresh\t: " + (bStart - bRefresh) + "ms");
- log.debug(" start\t: " + (aStart - bStart) + "ms");
- log.debug(" TOTAL\t: " + (aStart - begin) + "ms");
- }
-
- long bAppContext = System.currentTimeMillis();
- String filter = "(Bundle-SymbolicName=" + bundle.getSymbolicName()
- + ")";
- // Wait for application context to be ready
- // TODO: use service tracker
- Collection<ServiceReference<ApplicationContext>> srs = getServiceRefSynchronous(
- ApplicationContext.class, filter);
- ServiceReference<ApplicationContext> sr = srs.iterator().next();
- long aAppContext = System.currentTimeMillis();
- long end = aAppContext;
-
- if (log.isTraceEnabled()) {
- log.debug("Application context refresh performed in "
- + (aAppContext - bAppContext) + "ms for bundle "
- + osgiBundle);
- }
-
- if (log.isDebugEnabled())
- log.debug("Bundle '" + bundle.getSymbolicName()
- + "' upgraded and ready " + " (upgrade performed in "
- + (end - begin) + "ms).");
-
- if (log.isTraceEnabled()) {
- ApplicationContext applicationContext = (ApplicationContext) bundleContext
- .getService(sr);
- int beanDefCount = applicationContext.getBeanDefinitionCount();
- log.debug(" " + beanDefCount + " beans in app context of "
- + bundle.getSymbolicName()
- + ", average init time per bean=" + (end - begin)
- / beanDefCount + "ms");
- }
-
- bundleContext.ungetService(sr);
-
- } catch (Exception e) {
- throw new SlcException("Cannot update bundle " + osgiBundle, e);
- }
- }
-
- /** Updates bundle synchronously. */
- protected void updateSynchronous(Bundle bundle) throws BundleException {
- bundle.update();
- boolean waiting = true;
-
- long begin = System.currentTimeMillis();
- do {
- int state = bundle.getState();
- if (state == Bundle.INSTALLED || state == Bundle.ACTIVE
- || state == Bundle.RESOLVED)
- waiting = false;
-
- sleepWhenPolling();
- checkTimeout(begin, "Update of bundle " + bundle.getSymbolicName()
- + " timed out. Bundle state = " + bundle.getState());
- } while (waiting);
-
- if (log.isTraceEnabled())
- log.debug("Bundle " + bundle.getSymbolicName() + " updated.");
- }
-
- /** Starts bundle synchronously. Does nothing if already started. */
- protected void startSynchronous(Bundle bundle) throws BundleException {
- int originalState = bundle.getState();
- if (originalState == Bundle.ACTIVE)
- return;
-
- bundle.start();
- boolean waiting = true;
-
- long begin = System.currentTimeMillis();
- do {
- if (bundle.getState() == Bundle.ACTIVE)
- waiting = false;
-
- sleepWhenPolling();
- checkTimeout(begin, "Start of bundle " + bundle.getSymbolicName()
- + " timed out. Bundle state = " + bundle.getState());
- } while (waiting);
-
- if (log.isTraceEnabled())
- log.debug("Bundle " + bundle.getSymbolicName() + " started.");
- }
-
- /** Stops bundle synchronously. Does nothing if already started. */
- protected void stopSynchronous(Bundle bundle) throws BundleException {
- int originalState = bundle.getState();
- if (originalState != Bundle.ACTIVE)
- return;
-
- bundle.stop();
- boolean waiting = true;
-
- long begin = System.currentTimeMillis();
- do {
- if (bundle.getState() != Bundle.ACTIVE
- && bundle.getState() != Bundle.STOPPING)
- waiting = false;
-
- sleepWhenPolling();
- checkTimeout(begin, "Stop of bundle " + bundle.getSymbolicName()
- + " timed out. Bundle state = " + bundle.getState());
- } while (waiting);
-
- if (log.isTraceEnabled())
- log.debug("Bundle " + bundle.getSymbolicName() + " stopped.");
- }
-
- /** Refresh bundle synchronously. Does nothing if already started. */
- protected void refreshSynchronous(Bundle bundle) throws BundleException {
- ServiceReference<PackageAdmin> packageAdminRef = bundleContext
- .getServiceReference(PackageAdmin.class);
- PackageAdmin packageAdmin = (PackageAdmin) bundleContext
- .getService(packageAdminRef);
- Bundle[] bundles = { bundle };
-
- long begin = System.currentTimeMillis();
- synchronized (refreshedPackageSem) {
- packagesRefreshed = false;
- packageAdmin.refreshPackages(bundles);
- try {
- refreshedPackageSem.wait(defaultTimeout);
- } catch (InterruptedException e) {
- // silent
- }
- if (!packagesRefreshed) {
- long now = System.currentTimeMillis();
- throw new SlcException("Packages not refreshed after "
- + (now - begin) + "ms");
- } else {
- packagesRefreshed = false;
- }
- }
-
- if (log.isTraceEnabled())
- log.debug("Bundle " + bundle.getSymbolicName() + " refreshed.");
- }
-
- public void frameworkEvent(FrameworkEvent event) {
- if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
- synchronized (refreshedPackageSem) {
- packagesRefreshed = true;
- refreshedPackageSem.notifyAll();
- }
- }
- }
-
- public <S> Collection<ServiceReference<S>> getServiceRefSynchronous(
- Class<S> clss, String filter) throws InvalidSyntaxException {
- if (log.isTraceEnabled())
- log.debug("Filter: '" + filter + "'");
- Collection<ServiceReference<S>> sfs = null;
- boolean waiting = true;
- long begin = System.currentTimeMillis();
- do {
- sfs = bundleContext.getServiceReferences(clss, filter);
-
- if (sfs != null)
- waiting = false;
-
- sleepWhenPolling();
- checkTimeout(begin, "Search of services " + clss + " with filter "
- + filter + " timed out.");
- } while (waiting);
-
- return sfs;
- }
-
- protected void checkTimeout(long begin, String msg) {
- long now = System.currentTimeMillis();
- if (now - begin > defaultTimeout)
- throw new SlcException(msg + " (timeout after " + (now - begin)
- + "ms)");
-
- }
-
- protected void sleepWhenPolling() {
- try {
- Thread.sleep(pollingPeriod);
- } catch (InterruptedException e) {
- throw new SlcException("Polling interrupted");
- }
- }
-
- /** Creates and open a new service tracker. */
- public <S> ServiceTracker<S, S> newTracker(Class<S> clss) {
- ServiceTracker<S, S> st = new ServiceTracker<S, S>(bundleContext, clss,
- null);
- st.open();
- return st;
- }
-
- public <T> T getSingleService(Class<T> clss, String filter,
- Boolean synchronous) {
- if (filter != null)
- Assert.isTrue(OsgiFilterUtils.isValidFilter(filter), "valid filter");
- Collection<ServiceReference<T>> sfs;
- try {
- if (synchronous)
- sfs = getServiceRefSynchronous(clss, filter);
- else
- sfs = bundleContext.getServiceReferences(clss, filter);
- } catch (InvalidSyntaxException e) {
- throw new SlcException("Cannot retrieve service reference for "
- + filter, e);
- }
-
- if (sfs == null || sfs.size() == 0)
- return null;
- else if (sfs.size() > 1)
- throw new SlcException("More than one execution flow found for "
- + filter);
- return (T) bundleContext.getService(sfs.iterator().next());
- }
-
- public <T> T getSingleServiceStrict(Class<T> clss, String filter,
- Boolean synchronous) {
- T service = getSingleService(clss, filter, synchronous);
- if (service == null)
- throw new SlcException("No execution flow found for " + filter);
- else
- return service;
- }
-
- public OsgiBundle findRelatedBundle(String moduleName, String moduleVersion) {
- OsgiBundle osgiBundle = new OsgiBundle(moduleName, moduleVersion);
- if (osgiBundle.getVersion() == null) {
- Bundle bundle = findRelatedBundle(osgiBundle);
- osgiBundle = new OsgiBundle(bundle);
- }
- return osgiBundle;
- }
-
- /**
- * @param osgiBundle
- * cannot be null
- * @return the related bundle or null if not found
- * @throws SlcException
- * if osgiBundle argument is null
- */
- public Bundle findRelatedBundle(OsgiBundle osgiBundle) {
- if (osgiBundle == null)
- throw new SlcException("OSGi bundle cannot be null");
-
- Bundle bundle = null;
- if (osgiBundle.getInternalBundleId() != null) {
- bundle = bundleContext.getBundle(osgiBundle.getInternalBundleId());
- Assert.isTrue(
- osgiBundle.getName().equals(bundle.getSymbolicName()),
- "symbolic name consistent");
- if (osgiBundle.getVersion() != null)
- Assert.isTrue(
- osgiBundle.getVersion().equals(
- bundle.getHeaders().get(
- Constants.BUNDLE_VERSION)),
- "version consistent");
- } else if (osgiBundle.getVersion() == null
- || osgiBundle.getVersion().equals("0.0.0")) {
- bundle = OsgiBundleUtils.findBundleBySymbolicName(bundleContext,
- osgiBundle.getName());
- } else {// scan all bundles
- bundles: for (Bundle b : bundleContext.getBundles()) {
- if (b.getSymbolicName() == null) {
- log.warn("Bundle " + b + " has no symbolic name defined.");
- continue bundles;
- }
-
- if (b.getSymbolicName().equals(osgiBundle.getName())) {
- if (osgiBundle.getVersion() == null) {
- bundle = b;
- break bundles;
- }
-
- if (b.getHeaders().get(Constants.BUNDLE_VERSION)
- .equals(osgiBundle.getVersion())) {
- bundle = b;
- osgiBundle.setInternalBundleId(b.getBundleId());
- break bundles;
- }
- }
- }
- }
- return bundle;
- }
-
- /** Find a single bundle based on a symbolic name pattern. */
- public OsgiBundle findFromPattern(String pattern) {
- OsgiBundle osgiBundle = null;
- for (Bundle b : bundleContext.getBundles()) {
- if (b.getSymbolicName().contains(pattern)) {
- osgiBundle = new OsgiBundle(b);
- break;
- }
- }
- return osgiBundle;
- }
-
- public OsgiBundle getBundle(Long bundleId) {
- Bundle bundle = bundleContext.getBundle(bundleId);
- return new OsgiBundle(bundle);
- }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- public void afterPropertiesSet() throws Exception {
- bundleContext.addFrameworkListener(this);
- }
-
- public void destroy() throws Exception {
- bundleContext.removeFrameworkListener(this);
- }
-
- public void setDefaultTimeout(Long defaultTimeout) {
- this.defaultTimeout = defaultTimeout;
- }
-
- /**
- * Use with caution since it may interfer with some cached information
- * within this object
- */
- public BundleContext getBundleContext() {
- return bundleContext;
- }
-
- public void setPollingPeriod(Long pollingPeriod) {
- this.pollingPeriod = pollingPeriod;
- }
-
- public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
- if (event instanceof OsgiBundleContextRefreshedEvent) {
- log.debug("App context refreshed: " + event);
- } else if (event instanceof OsgiBundleContextFailedEvent) {
- log.debug("App context failed: " + event);
- }
- if (event instanceof OsgiBundleContextClosedEvent) {
- log.debug("App context closed: " + event);
- }
-
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.io.File;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-import java.util.jar.JarFile;
-import java.util.jar.Manifest;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.api.cms.CmsLog;
-import org.osgi.framework.Constants;
-
-/** <b>Experimental</b> */
-public class FileSystemBundleRegister implements BundleRegister {
- private final static CmsLog log = CmsLog
- .getLog(FileSystemBundleRegister.class);
- private Properties packagesBundles = null;
-
- public String bundleProvidingPackage(String pkg, String version) {
- if (packagesBundles == null)
- return null;
- return packagesBundles.getProperty(pkg);
- }
-
- protected void scan(File baseDirectory) {
- long begin = System.currentTimeMillis();
- int bundleCount = 0;
- int packageCount = 0;
-
- packagesBundles = new Properties();
-
- File[] files = baseDirectory.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
-
- } else {
- JarFile jarFile = null;
- try {
- jarFile = new JarFile(file);
- Manifest manifest = jarFile.getManifest();
- String symbolicName = manifest.getMainAttributes()
- .getValue(Constants.BUNDLE_SYMBOLICNAME);
- String exportPackage = manifest.getMainAttributes()
- .getValue(Constants.EXPORT_PACKAGE);
-
- // List exported packages
- Set<String> exportedPackages = exportPackageToPackageNames(exportPackage);
-
- for (String exportedPackage : exportedPackages) {
- packagesBundles.put(exportedPackage, symbolicName);
- packageCount++;
- if (log.isTraceEnabled())
- log.trace("Register " + exportedPackage + "="
- + symbolicName);
- }
- bundleCount++;
- } catch (Exception e) {
- log.warn("Cannot scan " + file, e);
- if (log.isTraceEnabled())
- e.printStackTrace();
- } finally {
- IOUtils.closeQuietly(jarFile);
- }
- }
- }
- if (log.isDebugEnabled())
- log.debug("Scanned " + bundleCount + " bundles with "
- + packageCount + " packages in "
- + (System.currentTimeMillis() - begin) + " ms");
- }
-
- protected Set<String> exportPackageToPackageNames(String exportPackage) {
- Set<String> exportedPackages = new HashSet<String>();
- if (exportPackage == null)
- return exportedPackages;
- char[] arr = exportPackage.toCharArray();
-
- StringBuffer currentPkg = new StringBuffer("");
- boolean skip = false;
- boolean inQuote = false;
- for (char c : arr) {
- if (c == ' ' || c == '\n') {
- // ignore
- } else if (c == ';') {
- if (!skip)
- skip = true;
- } else if (c == ',') {
- if (skip && !inQuote) {
- skip = false;
- // add new package
- exportedPackages.add(currentPkg.toString());
- currentPkg = new StringBuffer("");
- }
- } else if (c == '\"') {
- inQuote = inQuote ? false : true;
- } else {
- if (!skip)
- currentPkg.append(c);
- }
- }
-
- return exportedPackages;
- }
-
- public static void main(String[] args) {
- FileSystemBundleRegister fsbr = new FileSystemBundleRegister();
- fsbr.scan(new File(
- "/home/mbaudier/dev/src/slc/dist/org.argeo.slc.sdk/target/lib"));
-
- }
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.argeo.api.cms.CmsLog;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationEvent;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.core.Ordered;
-
-/** Publishes beans of the application context as OSGi services. */
-@SuppressWarnings(value = { "unchecked", "rawtypes" })
-public class MultipleServiceExporterPostProcessor implements
- ApplicationListener, Ordered {
- private final static CmsLog log = CmsLog
- .getLog(MultipleServiceExporterPostProcessor.class);
-
- private List<Class> interfaces = new ArrayList<Class>();
-
- private int order = Ordered.LOWEST_PRECEDENCE;
-
- private BundleContext bundleContext = null;
-
- // private Class osgiServiceFactoryClass = OsgiServiceFactoryBean.class;
- // private Boolean useServiceProviderContextClassLoader = false;
-
- public void onApplicationEvent(ApplicationEvent event) {
- Map<String, Object> beans = new HashMap<String, Object>();
- if (event instanceof ContextRefreshedEvent) {
- if (bundleContext != null) {
- for (Class clss : interfaces) {
- ApplicationContext ac = ((ContextRefreshedEvent) event)
- .getApplicationContext();
- beans.putAll(ac.getBeansOfType(clss, false, false));
- }
-
- int count = 0;
- for (String beanName : beans.keySet()) {
- Object bean = beans.get(beanName);
- List<String> classes = new ArrayList<String>();
- for (Class clss : interfaces) {
- if (clss.isAssignableFrom(bean.getClass())) {
- classes.add(clss.getName());
- }
- }
- Properties props = new Properties();
- Bundle bundle = bundleContext.getBundle();
- props.put(Constants.BUNDLE_SYMBOLICNAME,
- bundle.getSymbolicName());
- props.put(Constants.BUNDLE_VERSION, bundle.getVersion());
- // retrocompatibility with pre-1.0:
- props.put("org.eclipse.gemini.blueprint.bean.name", beanName);
- bundleContext.registerService(
- classes.toArray(new String[classes.size()]), bean,
- new Hashtable(props));
- count++;
- }
- if (log.isTraceEnabled())
- log.trace("Published " + count + " " + interfaces
- + " as OSGi services from bundle "
- + bundleContext.getBundle().getSymbolicName() + " "
- + bundleContext.getBundle().getVersion());
- // note: the services will be automatically unregistered when
- // the bundle will be stopped
- }
- }
- }
-
- // public void postProcessBeanFactory(
- // ConfigurableListableBeanFactory beanFactory) throws BeansException {
- // if (!(beanFactory instanceof BeanDefinitionRegistry)) {
- // throw new SlcException("Can only work on "
- // + BeanDefinitionRegistry.class);
- // }
- //
- // long begin = System.currentTimeMillis();
- //
- // // Merge all beans implementing these interfaces
- // Set<String> beanNames = new HashSet<String>();
- // for (Class clss : interfaces) {
- // String[] strs = beanFactory.getBeanNamesForType(clss, true, false);
- // beanNames.addAll(Arrays.asList(strs));
- // }
- //
- // // Register service factory beans for them
- // for (String beanName : beanNames) {
- // MutablePropertyValues mpv = new MutablePropertyValues();
- // mpv.addPropertyValue("interfaces", interfaces.toArray());
- // mpv.addPropertyValue("targetBeanName", beanName);
- // if (useServiceProviderContextClassLoader)
- // mpv.addPropertyValue("contextClassLoader",
- // ExportContextClassLoader.SERVICE_PROVIDER);
- // RootBeanDefinition bd = new RootBeanDefinition(
- // osgiServiceFactoryClass, mpv);
- //
- // String exporterBeanName = "osgiService." + beanName;
- // if (log.isTraceEnabled())
- // log.debug("Registering OSGi service exporter "
- // + exporterBeanName);
- // ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(
- // exporterBeanName, bd);
- // }
- //
- // long end = System.currentTimeMillis();
- // if (log.isTraceEnabled())
- // log.debug("Multiple services exported in " + (end - begin)
- // + " ms in bundle.");
- //
- // }
-
- public void setInterfaces(List<Class> interfaces) {
- this.interfaces = interfaces;
- }
-
- // public void setOsgiServiceFactoryClass(Class osgiServiceFactoryClass) {
- // this.osgiServiceFactoryClass = osgiServiceFactoryClass;
- // }
-
- public int getOrder() {
- return order;
- }
-
- public void setOrder(int order) {
- this.order = order;
- }
-
- // public void setUseServiceProviderContextClassLoader(
- // Boolean useServiceProviderContextClassLoader) {
- // this.useServiceProviderContextClassLoader =
- // useServiceProviderContextClassLoader;
- // }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.core.build.ResourceDistribution;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.Module;
-import org.argeo.slc.deploy.ModuleDescriptor;
-import org.argeo.slc.deploy.TargetData;
-import org.argeo.slc.execution.RealizedFlow;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-import org.springframework.core.io.Resource;
-
-/** A deployed OSGi bundle. */
-public class OsgiBundle extends DefaultNameVersion implements Module {
- private ResourceDistribution distribution;
-
- private Long internalBundleId;
-
- private String title;
- private String description;
-
- public OsgiBundle() {
-
- }
-
- public OsgiBundle(String name, String version) {
- super(name, version);
- }
-
- public OsgiBundle(NameVersion nameVersion) {
- super(nameVersion);
- }
-
- public OsgiBundle(Bundle bundle) {
- super(bundle.getSymbolicName(), getVersionSafe(bundle));
- internalBundleId = bundle.getBundleId();
- }
-
- /**
- * Initialize from a {@link RealizedFlow}.
- *
- * @deprecated introduce an unnecessary dependency. TODO: create a separate
- * helper.
- */
- public OsgiBundle(RealizedFlow realizedFlow) {
- super(realizedFlow.getModuleName(), realizedFlow.getModuleVersion());
- }
-
- /** Utility to avoid NPE. */
- private static String getVersionSafe(Bundle bundle) {
- Object versionObj = bundle.getHeaders().get(Constants.BUNDLE_VERSION);
- if (versionObj != null)
- return versionObj.toString();
- else
- return null;
- }
-
- /** Unique deployed system id. TODO: use internal bundle id when available? */
- public String getDeployedSystemId() {
- return getName() + ":" + getVersion();
- }
-
- /**
- * OSGi bundle are self-contained and do not require additional deployment
- * data.
- *
- * @return always null
- */
- public DeploymentData getDeploymentData() {
- return null;
- }
-
- /** The related distribution. */
- public Distribution getDistribution() {
- return distribution;
- }
-
- /**
- * The related distribution, a jar file with OSGi metadata referenced by a
- * {@link Resource}.
- */
- public ResourceDistribution getResourceDistribution() {
- return distribution;
- }
-
- /** TODO: reference the {@link OsgiRuntime} as target data? */
- public TargetData getTargetData() {
- throw new UnsupportedOperationException();
- }
-
- public void setResourceDistribution(ResourceDistribution distribution) {
- this.distribution = distribution;
- }
-
- /**
- * Bundle ID used by the OSGi runtime. To be used for optimization when
- * looking in the bundle context. Can therefore be null.
- */
- public Long getInternalBundleId() {
- return internalBundleId;
- }
-
- /** Only package access for the time being. e.g. from {@link BundlesManager} */
- void setInternalBundleId(Long internalBundleId) {
- this.internalBundleId = internalBundleId;
- }
-
- /** Value of the <code>Bundle-Name</code> directive. */
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String label) {
- this.title = label;
- }
-
- /** Value of the <code>Bundle-Description</code> directive. */
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public ModuleDescriptor getModuleDescriptor() {
- ModuleDescriptor moduleDescriptor = new ModuleDescriptor();
- moduleDescriptor.setName(getName());
- moduleDescriptor.setVersion(getVersion());
- moduleDescriptor.setDescription(description);
- moduleDescriptor.setTitle(title);
- return moduleDescriptor;
- }
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.core.execution.AbstractSpringExecutionModule;
-import org.argeo.slc.execution.ExecutionContext;
-
-@Deprecated
-public class OsgiExecutionModule extends AbstractSpringExecutionModule {
- private final static CmsLog log = CmsLog.getLog(OsgiExecutionModule.class);
-
- public OsgiExecutionModule() {
- log.error("######## ERROR - DEPRECATED APPROACH USED ########");
- log.error(OsgiExecutionModule.class.getName() + " is deprecated. ");
- log
- .error("It will be removed in the next release. Remove its bean definition.");
- log
- .error("And replace: <service interface=\"org.argeo.slc.execution.ExecutionModule\" ref=\"executionModule\" />");
- log
- .error("by: <beans:import resource=\"classpath:org/argeo/slc/osgi/execution/spring.xml\" /> ");
- log.error("in osgi.xml.\n\n");
- }
-
- public void setExecutionContext(ExecutionContext executionContext) {
- // do nothing, just for compatibility
- }
-
- /*
- * private BundleContext bundleContext;
- *
- * @Override public void execute(ExecutionFlowDescriptor
- * executionFlowDescriptor) { if (descriptorConverter != null)
- * executionContext.addVariables(descriptorConverter
- * .convertValues(executionFlowDescriptor));
- *
- * ExecutionFlow flow = findExecutionFlow(getName(), getVersion(),
- * executionFlowDescriptor.getName()); flow.run(); }
- *
- * @Override protected Map<String, ExecutionFlow> listFlows() { String
- * filter = "(org.argeo.slc.execution.module.name=" + getName() + ")";
- * ServiceReference[] sfs; try { sfs =
- * bundleContext.getServiceReferences(ExecutionFlow.class .getName(),
- * filter); } catch (InvalidSyntaxException e) { throw new SlcException(
- * "Cannot retrieve service reference for flow " + filter, e); }
- *
- * Map<String, ExecutionFlow> flows = new HashMap<String, ExecutionFlow>();
- * for (ServiceReference sf : sfs) { ExecutionFlow flow = (ExecutionFlow)
- * bundleContext.getService(sf); flows.put(flow.getName(), flow); } return
- * flows; }
- *
- * public String getName() { return
- * bundleContext.getBundle().getSymbolicName(); }
- *
- * public String getVersion() { return
- * bundleContext.getBundle().getHeaders().get("Bundle-Version") .toString();
- * }
- *
- * public void setBundleContext(BundleContext bundleContext) {
- * this.bundleContext = bundleContext; }
- *
- * protected ExecutionFlow findExecutionFlow(String moduleName, String
- * moduleVersion, String flowName) { String filter =
- * "(&(org.argeo.slc.execution.module.name=" + moduleName +
- * ")(org.argeo.slc.execution.flow.name=" + flowName + "))";
- * log.debug("OSGi filter: " + filter);
- *
- * Assert.isTrue(OsgiFilterUtils.isValidFilter(filter), "valid filter");
- * ServiceReference[] sfs; try { sfs =
- * bundleContext.getServiceReferences(ExecutionFlow.class .getName(),
- * filter); } catch (InvalidSyntaxException e) { throw new
- * SlcException("Cannot retrieve service reference for " + filter, e); }
- *
- * if (sfs == null || sfs.length == 0) throw new
- * SlcException("No execution flow found for " + filter); else if
- * (sfs.length > 1) throw new
- * SlcException("More than one execution flow found for " + filter); return
- * (ExecutionFlow) bundleContext.getService(sfs[0]); }
- */
-
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.lang.management.ManagementFactory;
-import java.util.ArrayList;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.StandardMBean;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.DefaultExecutionFlowDescriptorConverter;
-import org.argeo.slc.deploy.Module;
-import org.argeo.slc.deploy.ModuleDescriptor;
-import org.argeo.slc.execution.ExecutionContext;
-import org.argeo.slc.execution.ExecutionFlow;
-import org.argeo.slc.execution.ExecutionFlowDescriptor;
-import org.argeo.slc.execution.ExecutionFlowDescriptorConverter;
-import org.argeo.slc.execution.ExecutionModuleDescriptor;
-import org.argeo.slc.execution.ExecutionModulesListener;
-import org.argeo.slc.execution.RealizedFlow;
-import org.argeo.slc.runtime.AbstractExecutionModulesManager;
-import org.eclipse.gemini.blueprint.service.importer.OsgiServiceLifecycleListener;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.BundleListener;
-import org.osgi.framework.Constants;
-import org.osgi.framework.launch.Framework;
-import org.springframework.context.ApplicationContext;
-
-/** Execution modules manager implementation based on an OSGi runtime. */
-public class OsgiExecutionModulesManager extends
- AbstractExecutionModulesManager implements
- OsgiServiceLifecycleListener, BundleListener {
-
- private final static CmsLog log = CmsLog
- .getLog(OsgiExecutionModulesManager.class);
-
- private BundlesManager bundlesManager;
- private Map<OsgiBundle, ExecutionContext> executionContexts = new HashMap<OsgiBundle, ExecutionContext>();
- private Map<OsgiBundle, ExecutionFlowDescriptorConverter> executionFlowDescriptorConverters = new HashMap<OsgiBundle, ExecutionFlowDescriptorConverter>();
- private Map<OsgiBundle, Set<ExecutionFlow>> executionFlows = new HashMap<OsgiBundle, Set<ExecutionFlow>>();
- private ExecutionFlowDescriptorConverter defaultDescriptorConverter = new DefaultExecutionFlowDescriptorConverter();
-
- private List<ExecutionModulesListener> executionModulesListeners = new ArrayList<ExecutionModulesListener>();
-
- private Boolean registerFlowsToJmx = false;
-
- public void init() throws Exception {
- bundlesManager.getBundleContext().addBundleListener(this);
-
- final String module = System.getProperty(UNIQUE_LAUNCH_MODULE_PROPERTY);
- final String flow = System.getProperty(UNIQUE_LAUNCH_FLOW_PROPERTY);
- if (module != null) {
- // launch a flow and stops
- new Thread("Unique Flow") {
- @Override
- public void run() {
- executeFlowAndExit(module, null, flow);
- }
- }.start();
- }
- }
-
- public void destroy() {
- bundlesManager.getBundleContext().removeBundleListener(this);
- }
-
- /** Executes a single flow and <b>stops the JVM</b> */
- protected void executeFlowAndExit(final String module,
- final String version, final String flow) {
- if (log.isDebugEnabled())
- log.debug("Launch unique flow " + flow + " from module " + module);
- try {
- OsgiBundle osgiBundle = bundlesManager.findFromPattern(module);
- if (osgiBundle == null)
- throw new SlcException("No OSGi bundle found for " + module);
- // Bundle moduleBundle =
- // bundlesManager.findRelatedBundle(osgiBundle);
- start(osgiBundle);
-
- RealizedFlow lastLaunch = findRealizedFlow(module, flow);
- if (lastLaunch == null)
- throw new SlcException("Cannot find launch for " + module + " "
- + flow);
- execute(lastLaunch);
- } catch (Exception e) {
- log.error(
- "Error in unique flow " + flow + " from module " + module,
- e);
- } finally {
- if (log.isDebugEnabled())
- log.debug("Shutdown OSGi runtime...");
- Framework framework = (Framework) bundlesManager.getBundleContext()
- .getBundle(0);
- try {
- // shutdown framework
- framework.stop();
- // wait 1 min for shutdown
- framework.waitForStop(60 * 1000);
- // close VM
- System.exit(0);
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
- }
-
- // public void startExectionModule(String moduleName, String moduleVersion)
- // {
- // try {
- // ServiceReference[] sr = bundlesManager.getServiceRefSynchronous(
- // ApplicationContext.class.getName(),
- // "org.springframework.context.service.name=" + moduleName);
- // // bundlesManager.startSynchronous(moduleBundle);
- // if (sr == null || sr.length == 0)
- // throw new SlcException(
- // "Cannot find execution module application context "
- // + moduleName);
- // } catch (InvalidSyntaxException e) {
- // throw new SlcException("Cannot start exeuction module "
- // + moduleName, e);
- // }
- // }
-
- public synchronized ExecutionModuleDescriptor getExecutionModuleDescriptor(
- String moduleName, String version) {
- ExecutionModuleDescriptor md = new ExecutionModuleDescriptor();
- OsgiBundle osgiBundle = null;
- DefaultNameVersion nameVersion = new DefaultNameVersion(moduleName,
- version);
- bundles: for (Iterator<OsgiBundle> iterator = executionContexts
- .keySet().iterator(); iterator.hasNext();) {
- OsgiBundle ob = iterator.next();
- if (nameVersion.getVersion() != null) {
- if (ob.equals(nameVersion)) {
- osgiBundle = ob;
- break bundles;
- }
- } else {
- if (ob.getName().equals(nameVersion.getName())) {
- osgiBundle = ob;
- break bundles;
- }
- }
- }
- if (osgiBundle == null)
- throw new SlcException("No execution module registered for "
- + nameVersion);
- md.setName(osgiBundle.getName());
- md.setVersion(osgiBundle.getVersion());
- md.setTitle(osgiBundle.getTitle());
- md.setDescription(osgiBundle.getDescription());
-
- ExecutionFlowDescriptorConverter executionFlowDescriptorConverter = getExecutionFlowDescriptorConverter(
- moduleName, version);
- if (executionFlowDescriptorConverter == null)
- throw new SlcException("No flow converter found.");
- executionFlowDescriptorConverter.addFlowsToDescriptor(md,
- listFlows(moduleName, version));
- return md;
- }
-
- public synchronized List<ExecutionModuleDescriptor> listExecutionModules() {
- List<ExecutionModuleDescriptor> descriptors = new ArrayList<ExecutionModuleDescriptor>();
-
- for (Iterator<OsgiBundle> iterator = executionContexts.keySet()
- .iterator(); iterator.hasNext();) {
- OsgiBundle osgiBundle = iterator.next();
- ExecutionModuleDescriptor md = new ExecutionModuleDescriptor();
- setMetadataFromBundle(md,
- bundlesManager.findRelatedBundle(osgiBundle));
- descriptors.add(md);
- }
- return descriptors;
- }
-
- protected synchronized Map<String, ExecutionFlow> listFlows(
- String moduleName, String moduleVersion) {
-
- Map<String, ExecutionFlow> flows = new HashMap<String, ExecutionFlow>();
- OsgiBundle key = bundlesManager.findRelatedBundle(moduleName,
- moduleVersion);
- if (!executionFlows.containsKey(key))
- return flows;
- Set<ExecutionFlow> flowsT = executionFlows.get(key);
- for (ExecutionFlow flow : flowsT)
- flows.put(flow.getName(), flow);
- return flows;
- }
-
- protected ExecutionFlow findExecutionFlow(String moduleName,
- String moduleVersion, String flowName) {
- String filter = moduleVersion == null || moduleVersion.equals("0.0.0") ? "(&(Bundle-SymbolicName="
- + moduleName
- + ")(org.eclipse.gemini.blueprint.bean.name="
- + flowName + "))"
- : "(&(Bundle-SymbolicName=" + moduleName + ")(Bundle-Version="
- + moduleVersion
- + ")(org.eclipse.gemini.blueprint.bean.name="
- + flowName + "))";
- return bundlesManager.getSingleServiceStrict(ExecutionFlow.class,
- filter, true);
- }
-
- protected ExecutionContext findExecutionContext(String moduleName,
- String moduleVersion) {
- String filter = moduleFilter(moduleName, moduleVersion);
- return bundlesManager.getSingleServiceStrict(ExecutionContext.class,
- filter, true);
- }
-
- protected ExecutionFlowDescriptorConverter findExecutionFlowDescriptorConverter(
- String moduleName, String moduleVersion) {
- String filter = moduleFilter(moduleName, moduleVersion);
- return bundlesManager.getSingleService(
- ExecutionFlowDescriptorConverter.class, filter, false);
- }
-
- /** Only based on symbolic name if version is null or "0.0.0" */
- protected String moduleFilter(String moduleName, String moduleVersion) {
- return moduleVersion == null || moduleVersion.equals("0.0.0") ? "(Bundle-SymbolicName="
- + moduleName + ")"
- : "(&(Bundle-SymbolicName=" + moduleName + ")(Bundle-Version="
- + moduleVersion + "))";
-
- }
-
- /**
- * Builds a minimal realized flow, based on the provided information
- * (typically from the command line).
- *
- * @param module
- * a bundle id, or a pattern contained in a bundle symbolic name
- * @param module
- * the execution flow name
- * @return a minimal realized flow, to be used in an execution
- */
- public RealizedFlow findRealizedFlow(String module, String executionName) {
- // First check whether we have a bundleId
- Long bundleId = null;
- try {
- bundleId = Long.parseLong(module);
- } catch (NumberFormatException e) {
- // silent
- }
-
- // Look for bundle names containing pattern
- OsgiBundle bundle = null;
- if (bundleId != null) {
- bundle = bundlesManager.getBundle(bundleId);
- } else {
- bundle = bundlesManager.findFromPattern(module);
- }
-
- if (bundle != null) {
- RealizedFlow launch = new RealizedFlow();
- launch.setModuleName(bundle.getName());
- launch.setModuleVersion(bundle.getVersion());
- ExecutionFlowDescriptor descriptor = new ExecutionFlowDescriptor();
- descriptor.setName(executionName);
- launch.setFlowDescriptor(descriptor);
- return launch;
- } else {
- log.warn("Could not find any execution module matching these requirements.");
- return null;
- }
- }
-
- public void upgrade(NameVersion nameVersion) {
- OsgiBundle osgiBundle = new OsgiBundle(nameVersion);
- bundlesManager.upgradeSynchronous(osgiBundle);
- }
-
- protected synchronized ExecutionFlowDescriptorConverter getExecutionFlowDescriptorConverter(
- String moduleName, String moduleVersion) {
- return findExecutionFlowDescriptorConverter(moduleName, moduleVersion);
- // OsgiBundle osgiBundle = new OsgiBundle(moduleName, moduleVersion);
- // return getExecutionFlowDescriptorConverter(osgiBundle);
- }
-
- protected synchronized ExecutionFlowDescriptorConverter getExecutionFlowDescriptorConverter(
- OsgiBundle osgiBundle) {
- if (executionFlowDescriptorConverters.containsKey(osgiBundle))
- return executionFlowDescriptorConverters.get(osgiBundle);
- else
- return defaultDescriptorConverter;
- }
-
- public ModuleDescriptor getModuleDescriptor(String moduleName,
- String version) {
- return getExecutionModuleDescriptor(moduleName, version);
- }
-
- public List<ModuleDescriptor> listModules() {
- Bundle[] bundles = bundlesManager.getBundleContext().getBundles();
- List<ModuleDescriptor> lst = new ArrayList<ModuleDescriptor>();
- for (Bundle bundle : bundles) {
- ModuleDescriptor moduleDescriptor = new ModuleDescriptor();
- setMetadataFromBundle(moduleDescriptor, bundle);
- lst.add(moduleDescriptor);
- }
- return lst;
- }
-
- public void start(NameVersion nameVersion) {
- try {
- Bundle bundle = bundlesManager.findRelatedBundle(new OsgiBundle(
- nameVersion));
- if (bundle == null)
- throw new SlcException("Could not find bundle for "
- + nameVersion);
-
- bundlesManager.startSynchronous(bundle);
- if (isSpringInstrumented(bundle)) {
- // Wait for Spring application context to be ready
- String filter = "(Bundle-SymbolicName="
- + bundle.getSymbolicName() + ")";
- try {
- bundlesManager.getServiceRefSynchronous(
- ApplicationContext.class, filter);
- } catch (Exception e) {
- // stop if application context not found
- bundle.stop();
- throw e;
- }
- }
- } catch (Exception e) {
- throw new SlcException("Cannot start " + nameVersion, e);
- }
- }
-
- /** Do it calmly in order to avoid NPE */
- private Boolean isSpringInstrumented(Bundle bundle) {
- Dictionary<?, ?> headers = bundle.getHeaders();
- if (headers != null && headers.get("Spring-Context") != null)
- return true;
- Enumeration<?> springEntryPaths = bundle
- .getEntryPaths("/META-INF/spring");
- if (springEntryPaths != null && springEntryPaths.hasMoreElements())
- return true;
- return false;
- }
-
- public void stop(NameVersion nameVersion) {
- try {
- Bundle bundle = bundlesManager.findRelatedBundle(new OsgiBundle(
- nameVersion));
- bundlesManager.stopSynchronous(bundle);
- } catch (BundleException e) {
- throw new SlcException("Cannot stop " + nameVersion, e);
- }
- }
-
- protected void setMetadataFromBundle(ModuleDescriptor md, Bundle bundle) {
- Bundle bdl = bundle;
- if (bdl == null) {
- if (md.getName() == null || md.getVersion() == null)
- throw new SlcException("Name and version not available.");
-
- Bundle[] bundles = bundlesManager.getBundleContext().getBundles();
- for (Bundle b : bundles) {
- if (b.getSymbolicName().equals(md.getName())
- && md.getVersion().equals(
- getHeaderSafe(b, Constants.BUNDLE_VERSION))) {
- bdl = b;
- break;
- }
- }
-
- }
-
- if (bdl == null)
- throw new SlcException("Cannot find bundle.");
-
- md.setName(bdl.getSymbolicName());
- md.setVersion(getHeaderSafe(bdl, Constants.BUNDLE_VERSION));
- md.setTitle(getHeaderSafe(bdl, Constants.BUNDLE_NAME));
- md.setDescription(getHeaderSafe(bdl, Constants.BUNDLE_DESCRIPTION));
-
- // copy manifets header to meta data
- Dictionary<?, ?> headers = bundle.getHeaders();
- Enumeration<?> keys = headers.keys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- Object value = headers.get(key);
- if (value != null)
- md.getMetadata().put(key.toString(), value.toString());
- }
-
- // check if started
- if (bundle.getState() == Bundle.ACTIVE
- || bundle.getState() == Bundle.STARTING)
- md.setStarted(true);
- else
- md.setStarted(false);
- }
-
- private String getHeaderSafe(Bundle bundle, Object key) {
- Object obj = bundle.getHeaders().get(key);
- if (obj == null)
- return null;
- else
- return obj.toString();
- }
-
- /*
- * REGISTRATION
- */
-
- /** Registers an execution context. */
- public synchronized void register(ExecutionContext executionContext,
- Map<String, String> properties) {
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- Bundle bundle = bundlesManager.findRelatedBundle(osgiBundle);
- osgiBundle.setTitle(getHeaderSafe(bundle, Constants.BUNDLE_NAME));
- osgiBundle.setDescription(getHeaderSafe(bundle,
- Constants.BUNDLE_DESCRIPTION));
- executionContexts.put(osgiBundle, executionContext);
- if (log.isTraceEnabled())
- log.trace("Registered execution context from " + osgiBundle);
- // Notify
- ModuleDescriptor md = osgiBundle.getModuleDescriptor();
- md.setStarted(true);
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionModuleAdded(md);
- }
-
- /** Unregisters an execution context. */
- public synchronized void unregister(ExecutionContext executionContext,
- Map<String, String> properties) {
- // FIXME why are properties null?
- if (properties == null)
- return;
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- if (executionContexts.containsKey(osgiBundle)) {
- executionContexts.remove(osgiBundle);
- if (log.isTraceEnabled())
- log.trace("Removed execution context from " + osgiBundle);
- // Notify
- ModuleDescriptor md = osgiBundle.getModuleDescriptor();
- md.setStarted(false);
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionModuleRemoved(md);
- }
- }
-
- /** Registers an execution flow. */
- public synchronized void register(ExecutionFlow executionFlow,
- Map<String, String> properties) {
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- if (!executionFlows.containsKey(osgiBundle)) {
- executionFlows.put(osgiBundle, new HashSet<ExecutionFlow>());
- }
- executionFlows.get(osgiBundle).add(executionFlow);
- if (log.isTraceEnabled())
- log.trace("Registered " + executionFlow + " from " + osgiBundle);
-
- // notifications
- if (registerFlowsToJmx)
- registerMBean(osgiBundle, executionFlow);
- ExecutionFlowDescriptorConverter efdc = getExecutionFlowDescriptorConverter(osgiBundle);
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionFlowAdded(osgiBundle.getModuleDescriptor(),
- efdc.getExecutionFlowDescriptor(executionFlow));
- }
-
- /** Unregisters an execution flow. */
- public synchronized void unregister(ExecutionFlow executionFlow,
- Map<String, String> properties) {
- // FIXME why are properties null?
- if (properties == null)
- return;
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- if (executionFlows.containsKey(osgiBundle)) {
- Set<ExecutionFlow> flows = executionFlows.get(osgiBundle);
- flows.remove(executionFlow);
- if (log.isTraceEnabled())
- log.trace("Removed " + executionFlow + " from " + osgiBundle);
- if (flows.size() == 0) {
- executionFlows.remove(osgiBundle);
- if (log.isTraceEnabled())
- log.trace("Removed flows set from " + osgiBundle);
- }
-
- // notifications
- if (registerFlowsToJmx)
- unregisterMBean(osgiBundle, executionFlow);
- ExecutionFlowDescriptorConverter efdc = getExecutionFlowDescriptorConverter(osgiBundle);
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionFlowRemoved(osgiBundle.getModuleDescriptor(),
- efdc.getExecutionFlowDescriptor(executionFlow));
- }
- }
-
- /** Registers an execution module listener. */
- public synchronized void register(
- ExecutionModulesListener executionModulesListener,
- Map<String, String> properties) {
- // sync with current state
- for (OsgiBundle osgiBundle : executionContexts.keySet()) {
- executionModulesListener.executionModuleAdded(osgiBundle
- .getModuleDescriptor());
- }
- for (OsgiBundle osgiBundle : executionFlows.keySet()) {
- ExecutionFlowDescriptorConverter efdc = getExecutionFlowDescriptorConverter(osgiBundle);
- for (ExecutionFlow executionFlow : executionFlows.get(osgiBundle))
- executionModulesListener.executionFlowAdded(
- osgiBundle.getModuleDescriptor(),
- efdc.getExecutionFlowDescriptor(executionFlow));
- }
- executionModulesListeners.add(executionModulesListener);
- }
-
- /** Unregisters an execution module listener. */
- public synchronized void unregister(
- ExecutionModulesListener executionModulesListener,
- Map<String, String> properties) {
- executionModulesListeners.remove(executionModulesListener);
- }
-
- /*
- * INTERFACE IMPLEMENTATIONS
- */
-
- public void bundleChanged(BundleEvent evt) {
- Bundle bundle = evt.getBundle();
- if (bundle.getHeaders().get(
- ExecutionModuleDescriptor.SLC_EXECUTION_MODULE) != null) {
- OsgiBundle osgiBundle = new OsgiBundle(bundle);
- if (evt.getType() == BundleEvent.INSTALLED)
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionModuleAdded(osgiBundle
- .getModuleDescriptor());
- else if (evt.getType() == BundleEvent.UNINSTALLED)
- for (ExecutionModulesListener listener : executionModulesListeners)
- listener.executionModuleRemoved(osgiBundle
- .getModuleDescriptor());
- }
-
- }
-
- @SuppressWarnings({ "rawtypes" })
- public synchronized void bind(Object service, Map properties)
- throws Exception {
- if (service instanceof ExecutionFlowDescriptorConverter) {
- ExecutionFlowDescriptorConverter executionFlowDescriptorConverter = (ExecutionFlowDescriptorConverter) service;
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- executionFlowDescriptorConverters.put(osgiBundle,
- executionFlowDescriptorConverter);
- if (log.isTraceEnabled())
- log.debug("Registered execution flow descriptor converter from "
- + osgiBundle);
- } else {
- // ignore
- }
- }
-
- @SuppressWarnings("rawtypes")
- public synchronized void unbind(Object service, Map properties)
- throws Exception {
- if (service instanceof ExecutionFlowDescriptorConverter) {
- OsgiBundle osgiBundle = asOsgiBundle(properties);
- if (executionFlowDescriptorConverters.containsKey(osgiBundle)) {
- executionFlowDescriptorConverters.remove(osgiBundle);
- if (log.isTraceEnabled())
- log.debug("Removed execution flow descriptor converter from "
- + osgiBundle);
- }
- } else {
- // ignore
- }
- }
-
- /*
- * JMX
- */
- protected MBeanServer getMBeanServer() {
- return ManagementFactory.getPlatformMBeanServer();
- }
-
- public void registerMBean(Module module, ExecutionFlow executionFlow) {
- try {
- StandardMBean mbean = new StandardMBean(executionFlow,
- ExecutionFlow.class);
- getMBeanServer().registerMBean(mbean,
- flowMBeanName(module, executionFlow));
- } catch (Exception e) {
- String msg = "Cannot register execution flow " + executionFlow
- + " as mbean";
- throw new SlcException(msg, e);
- }
- }
-
- public void unregisterMBean(Module module, ExecutionFlow executionFlow) {
- try {
- getMBeanServer().unregisterMBean(
- flowMBeanName(module, executionFlow));
- } catch (Exception e) {
- String msg = "Cannot unregister execution flow " + executionFlow
- + " as mbean";
- throw new SlcException(msg, e);
- }
- }
-
- protected ObjectName flowMBeanName(Module module,
- ExecutionFlow executionFlow) {
- String executionModulesPrefix = "SLCExecutionModules";
- // String path = executionFlow.getPath();
- String name = executionFlow.getName();
- // if (path == null && name.indexOf('/') >= 0) {
- // path = name.substring(0, name.lastIndexOf('/'));
- // name = name.substring(name.lastIndexOf('/'));
- // }
-
- StringBuffer buf = new StringBuffer(executionModulesPrefix + ":"
- + "module=" + module.getName() + " [" + module.getVersion()
- + "],");
-
- // if (path != null && !path.equals("")) {
- // int depth = 0;
- // for (String token : path.split("/")) {
- // if (!token.equals("")) {
- // buf.append("path").append(depth).append('=');
- // // in order to have directories first
- // buf.append('/');
- // buf.append(token).append(',');
- // depth++;
- // }
- // }
- // }
- buf.append("name=").append(name);
- try {
- return new ObjectName(buf.toString());
- } catch (Exception e) {
- throw new SlcException("Cannot generate object name based on "
- + buf, e);
- }
- }
-
- /*
- * UTILITIES
- */
- @SuppressWarnings("rawtypes")
- private OsgiBundle asOsgiBundle(Map properties) {
- String bundleSymbolicName = checkAndGet(Constants.BUNDLE_SYMBOLICNAME,
- properties);
- String bundleVersion = checkAndGet(Constants.BUNDLE_VERSION, properties);
- return new OsgiBundle(bundleSymbolicName, bundleVersion);
- }
-
- @SuppressWarnings("rawtypes")
- private String checkAndGet(Object key, Map properties) {
- if (!properties.containsKey(key) || properties.get(key) == null)
- throw new SlcException(key + " not set in " + properties);
- else
- return properties.get(key).toString();
- }
-
- public void setBundlesManager(BundlesManager bundlesManager) {
- this.bundlesManager = bundlesManager;
- }
-
- public void setDefaultDescriptorConverter(
- ExecutionFlowDescriptorConverter defaultDescriptorConverter) {
- this.defaultDescriptorConverter = defaultDescriptorConverter;
- }
-
- public void setRegisterFlowsToJmx(Boolean registerFlowsToJmx) {
- this.registerFlowsToJmx = registerFlowsToJmx;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.core.execution.FileExecutionResources;
-import org.eclipse.gemini.blueprint.context.BundleContextAware;
-import org.eclipse.gemini.blueprint.io.OsgiBundleResource;
-import org.osgi.framework.BundleContext;
-import org.springframework.core.io.Resource;
-
-/** Write access to resources in an OSGi context */
-public class OsgiExecutionResources extends FileExecutionResources implements
- BundleContextAware {
- private final static CmsLog log = CmsLog
- .getLog(OsgiExecutionResources.class);
-
- private BundleContext bundleContext;
-
- @Override
- protected File fileFromResource(Resource resource) {
- File file = super.fileFromResource(resource);
- if (file != null)
- return file;
-
- if (!(resource instanceof OsgiBundleResource))
- return null;
-
- OsgiBundleResource osgiBundleResource = (OsgiBundleResource) resource;
- try {
- return osgiBundleResource.getFile();
- } catch (IOException e) {
- if (log.isTraceEnabled())
- log.trace("Resource " + resource
- + " is not available on the file system: " + e);
- }
-
- // TODO: ability to access resources in other bundles
- String location = bundleContext.getBundle().getLocation();
- String base = null;
- if (location.startsWith("reference:file:"))
- base = location.substring("reference:file:".length());
- else if (location.startsWith("initial@reference:file:")) {
- // TODO: Equinox specific?
- String relPath = location.substring("initial@reference:file:"
- .length());
- // if (relPath.startsWith("../"))// relative to the framework jar
- // relPath = relPath.substring("../".length());
- // String framework =
- // System.getProperty("osgi.framework").substring(
- // "file:".length());
- // log.debug(framework);
- String installArea = System.getProperty("osgi.install.area")
- .substring("file:".length());
- // log.debug(installArea);
- base = installArea + '/' + relPath;
- // int sepIndex = framework.lastIndexOf(File.separatorChar);
- // framework = framework.substring(0, sepIndex);
- // base = framework + '/' + relPath;
- } else {
- return null;
- }
-
- String path = base + '/' + osgiBundleResource.getPathWithinContext();
- try {
- file = new File(path).getCanonicalFile();
- } catch (IOException e) {
- throw new SlcException("Cannot determine canonical path for "
- + path, e);
- }
-
- if (!file.exists())
- throw new SlcException(file
- + " was retrieved in bundle located at '" + location
- + "' for resource " + resource + " but it does not exist");
-
- if (log.isTraceEnabled())
- log.debug("OSGi local resource: " + file + " from " + resource);
- return file;
- }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.StreamReadable;
-import org.argeo.slc.UnsupportedException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.core.build.VersionedResourceDistribution;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.DynamicRuntime;
-import org.argeo.slc.deploy.TargetData;
-import org.eclipse.gemini.blueprint.context.BundleContextAware;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleException;
-import org.springframework.context.ResourceLoaderAware;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.ResourceLoader;
-
-public class OsgiRuntime implements BundleContextAware, ResourceLoaderAware,
- DynamicRuntime<OsgiBundle> {
- private String uuid = UUID.randomUUID().toString();
- private BundleContext bundleContext;
- private ResourceLoader resourceLoader;
-
- public List<OsgiBundle> listModules() {
- List<OsgiBundle> modules = new ArrayList<OsgiBundle>();
- Bundle[] bundles = bundleContext.getBundles();
- for (Bundle bundle : bundles) {
- OsgiBundle osgiBundle = new OsgiBundle(bundle);
- modules.add(osgiBundle);
- String location = bundle.getLocation();
- if (location != null) {
- Resource resource = resourceLoader.getResource(location);
- osgiBundle
- .setResourceDistribution(new VersionedResourceDistribution(
- osgiBundle.getName(), osgiBundle.getVersion(),
- resource));
- }
- }
- return modules;
- }
-
- public OsgiBundle installModule(Distribution distribution) {
- if (!(distribution instanceof StreamReadable))
- throw new UnsupportedException("distribution", distribution);
-
- StreamReadable sr = (StreamReadable) distribution;
- Bundle bundle;
- try {
- bundle = bundleContext.installBundle(sr.toString(), sr
- .getInputStream());
- } catch (BundleException e) {
- throw new SlcException(
- "Cannot install OSGi bundle " + distribution, e);
- }
- return new OsgiBundle(bundle);
- }
-
- public void updateModule(NameVersion nameVersion) {
- Bundle bundle = findBundle(nameVersion);
- try {
- bundle.update();
- } catch (BundleException e) {
- throw new SlcException("Cannot update " + bundle, e);
- }
- }
-
- public void uninstallModule(NameVersion nameVersion) {
- Bundle bundle = findBundle(nameVersion);
- try {
- bundle.uninstall();
- } catch (BundleException e) {
- throw new SlcException("Cannot uninstall " + bundle, e);
- }
- }
-
- public void startModule(NameVersion nameVersion) {
- Bundle bundle = findBundle(nameVersion);
- try {
- bundle.start();
- // TODO: use bundle manager
- } catch (BundleException e) {
- throw new SlcException("Cannot uninstall " + bundle, e);
- }
- }
-
- protected Bundle findBundle(NameVersion nameVersion) {
- Bundle[] bundles = bundleContext.getBundles();
- for (Bundle bundle : bundles) {
- OsgiBundle osgiBundle = new OsgiBundle(bundle);
- if (osgiBundle.equals(nameVersion)) {
- return bundle;
- }
- }
- throw new SlcException("Could not find bundle " + nameVersion);
- }
-
- public void shutdown() {
- // FIXME use framework
- throw new UnsupportedException();
- }
-
- public String getDeployedSystemId() {
- return uuid;
- }
-
- public DeploymentData getDeploymentData() {
- throw new UnsupportedException();
- }
-
- public Distribution getDistribution() {
- throw new UnsupportedException();
- }
-
- public TargetData getTargetData() {
- throw new UnsupportedException();
- }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- public void setResourceLoader(ResourceLoader resourceLoader) {
- this.resourceLoader = resourceLoader;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.UnsupportedException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.build.ModularDistribution;
-import org.eclipse.gemini.blueprint.context.BundleContextAware;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.springframework.beans.factory.InitializingBean;
-
-public abstract class AbstractOsgiModularDistribution implements
- ModularDistribution, BundleContextAware, InitializingBean {
- private final static CmsLog log = CmsLog
- .getLog(AbstractOsgiModularDistribution.class);
-
- private BundleContext bundleContext;
- private EclipseUpdateSite eclipseUpdateSite;
-
- /** Initialized by the object itself. */
- private SortedMap<NameVersion, Distribution> distributions = new TreeMap<NameVersion, Distribution>();
-
- protected abstract void fillDistributions(
- SortedMap<NameVersion, Distribution> distributions)
- throws Exception;
-
- public Distribution getModuleDistribution(String moduleName,
- String moduleVersion) {
- return distributions.get(new DefaultNameVersion(moduleName,
- moduleVersion));
- }
-
- public String getDistributionId() {
- return bundleContext.getBundle().getSymbolicName()
- + "-"
- + bundleContext.getBundle().getHeaders()
- .get(Constants.BUNDLE_VERSION);
- }
-
- public Set<NameVersion> listModulesNameVersions() {
- return distributions.keySet();
- }
-
- public Iterator<NameVersion> nameVersions() {
- return distributions.keySet().iterator();
- }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- public void afterPropertiesSet() throws Exception {
- fillDistributions(distributions);
- if (log.isDebugEnabled())
- log.debug("Distribution " + getName() + ":" + getVersion()
- + " loaded (" + distributions.size() + " modules)");
- }
-
- protected String findVersion(String name) {
- Set<String> versions = new HashSet<String>();
- for (NameVersion key : distributions.keySet()) {
- if (key.getName().equals(name))
- versions.add(key.getVersion());
- }
-
- if (versions.size() == 0)
- throw new SlcException("Cannot find version for name " + name);
- else if (versions.size() > 1)
- throw new SlcException("Found more than one version for name "
- + name + ": " + versions);
- else
- return versions.iterator().next();
-
- }
-
- public Object getModulesDescriptor(String descriptorType) {
- if (descriptorType.equals("eclipse"))
- return writeEclipseUpdateSite();
- else
- throw new UnsupportedException("descriptorType", descriptorType);
- }
-
- protected Set<NameVersion> writePlainUrlList() {
- return distributions.keySet();
- }
-
- protected String writeEclipseUpdateSite() {
- if (eclipseUpdateSite == null)
- throw new SlcException("No eclipse update site declared.");
-
- StringBuffer buf = new StringBuffer("");
- buf.append("<site>");
-
- List<EclipseUpdateSiteCategory> usedCategories = new ArrayList<EclipseUpdateSiteCategory>();
- for (EclipseUpdateSiteFeature feature : eclipseUpdateSite.getFeatures()) {
-
- String featureId = feature.getName();
- String featureVersion = findVersion(featureId);
- buf.append("<feature");
- buf.append(" url=\"features/").append(featureId).append('_')
- .append(featureVersion).append(".jar\"");
- buf.append(" id=\"").append(featureId).append("\"");
- buf.append(" version=\"").append(featureVersion).append("\"");
- buf.append(">\n");
-
- for (EclipseUpdateSiteCategory category : feature.getCategories()) {
- usedCategories.add(category);
- buf.append(" <category name=\"").append(category.getName())
- .append("\"/>\n");
- }
- buf.append("</feature>\n\n");
- }
-
- for (EclipseUpdateSiteCategory category : usedCategories) {
- buf.append("<category-def");
- buf.append(" name=\"").append(category.getName()).append("\"");
- buf.append(" label=\"").append(category.getLabel()).append("\"");
- buf.append(">\n");
- buf.append(" <description>").append(category.getDescription())
- .append("</description>\n");
- buf.append("</category-def>\n\n");
- }
-
- buf.append("</site>");
- return buf.toString();
- }
-
- public String getName() {
- return bundleContext.getBundle().getSymbolicName();
- }
-
- public String getVersion() {
- return bundleContext.getBundle().getHeaders()
- .get(Constants.BUNDLE_VERSION).toString();
- }
-
- @Override
- public String toString() {
- return new DefaultNameVersion(this).toString();
- }
-
- public void setEclipseUpdateSite(EclipseUpdateSite eclipseUpdateSite) {
- this.eclipseUpdateSite = eclipseUpdateSite;
- }
-
- public BundleContext getBundleContext() {
- return bundleContext;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.SortedMap;
-import java.util.StringTokenizer;
-import java.util.jar.JarInputStream;
-import java.util.jar.Manifest;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.DefaultNameVersion;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.core.build.VersionedResourceDistribution;
-import org.osgi.framework.Constants;
-import org.springframework.context.ResourceLoaderAware;
-import org.springframework.core.io.ResourceLoader;
-
-public class BundleModularDistribution extends AbstractOsgiModularDistribution
- implements ResourceLoaderAware {
- private ResourceLoader resourceLoader;
-
- private String libDirectory = "/lib";
-
- protected void fillDistributions(
- SortedMap<NameVersion, Distribution> distributions)
- throws Exception {
- Enumeration<URL> urls = (Enumeration<URL>) getBundleContext()
- .getBundle().findEntries(libDirectory, "*.jar", false);
- while (urls.hasMoreElements()) {
- URL url = urls.nextElement();
- JarInputStream in = null;
- try {
- in = new JarInputStream(url.openStream());
- Manifest mf = in.getManifest();
- String name = mf.getMainAttributes().getValue(
- Constants.BUNDLE_SYMBOLICNAME);
- // Skip additional specs such as
- // ; singleton:=true
- if (name.indexOf(';') > -1) {
- name = new StringTokenizer(name, " ;").nextToken();
- }
-
- String version = mf.getMainAttributes().getValue(
- Constants.BUNDLE_VERSION);
- DefaultNameVersion nameVersion = new DefaultNameVersion(name,
- version);
- distributions.put(nameVersion,
- new VersionedResourceDistribution(name, version,
- resourceLoader.getResource(url.toString())));
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
- }
-
- public void setLibDirectory(String libDirectory) {
- this.libDirectory = libDirectory;
- }
-
- public void setResourceLoader(ResourceLoader resourceLoader) {
- this.resourceLoader = resourceLoader;
- }
-
- /*
- * @SuppressWarnings(value = { "unchecked" }) protected URL
- * findModule(String moduleName, String version) { Enumeration<URL> urls =
- * (Enumeration<URL>) bundleContext.getBundle() .findEntries(libDirectory,
- * moduleName + "*", false);
- *
- * if (!urls.hasMoreElements()) throw new SlcException("Cannot find module "
- * + moduleName);
- *
- * URL url = urls.nextElement();
- *
- * // TODO: check version as well if (urls.hasMoreElements()) throw new
- * SlcException("More than one module with name " + moduleName); return url;
- * }
- */
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class EclipseUpdateSite {
- private List<EclipseUpdateSiteFeature> features = new ArrayList<EclipseUpdateSiteFeature>();
-
- public List<EclipseUpdateSiteFeature> getFeatures() {
- return features;
- }
-
- public void setFeatures(List<EclipseUpdateSiteFeature> features) {
- this.features = features;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-public class EclipseUpdateSiteCategory {
- private String name;
- private String label;
- private String description;
-
- public String getLabel() {
- return label;
- }
-
- public void setLabel(String label) {
- this.label = label;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class EclipseUpdateSiteFeature {
- private String name;
- private List<EclipseUpdateSiteCategory> categories = new ArrayList<EclipseUpdateSiteCategory>();
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public List<EclipseUpdateSiteCategory> getCategories() {
- return categories;
- }
-
- public void setCategories(List<EclipseUpdateSiteCategory> categories) {
- this.categories = categories;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.osgi.build;
-
-import java.net.URL;
-import java.util.SortedMap;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.core.build.VersionedResourceDistribution;
-import org.argeo.slc.osgi.OsgiBundle;
-import org.eclipse.gemini.blueprint.util.OsgiBundleUtils;
-import org.osgi.framework.Bundle;
-import org.springframework.context.ResourceLoaderAware;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.ResourceLoader;
-
-public class OsgiRuntimeModularDistribution extends
- AbstractOsgiModularDistribution implements ResourceLoaderAware {
- private final static CmsLog log = CmsLog
- .getLog(OsgiRuntimeModularDistribution.class);
-
- private ResourceLoader resourceLoader;
-
- protected void fillDistributions(
- SortedMap<NameVersion, Distribution> distributions)
- throws Exception {
-
- String frameworkUrl = System.getProperty("osgi.framework");
- String frameworkBaseUrl = null;
- if (frameworkUrl != null)
- frameworkBaseUrl = frameworkUrl.substring(0, frameworkUrl
- .lastIndexOf('/'));
- bundles: for (Bundle bundle : getBundleContext().getBundles()) {
- OsgiBundle osgiBundle = new OsgiBundle(bundle);
-
- String originalLocation = bundle.getLocation();
-
- if (OsgiBundleUtils.isSystemBundle(bundle)) {
- continue bundles;
- }
-
- String location = originalLocation;
- if (originalLocation.startsWith("reference:file:"))
- location = originalLocation.substring("reference:".length());
-
- if (frameworkBaseUrl != null
- && originalLocation.startsWith("initial@reference:file:")) {
- location = frameworkBaseUrl
- + '/'
- + originalLocation.substring("initial@reference:file:"
- .length());
- }
-
- try {
- URL url = new URL(location);
- Resource res = resourceLoader.getResource(url.toString());
- distributions.put(osgiBundle,
- new VersionedResourceDistribution(osgiBundle, res));
-
- if (log.isTraceEnabled())
- log.debug("Added url " + url + " from original location "
- + originalLocation);
- } catch (Exception e) {
- log.warn("Cannot interpret location " + location
- + " of bundle " + bundle + ": " + e);
- }
- }
- }
-
- public void setResourceLoader(ResourceLoader resourceLoader) {
- this.resourceLoader = resourceLoader;
- }
-}
+++ /dev/null
-package org.argeo.slc.osgi.deploy;
-
-import org.argeo.slc.core.deploy.DefaultResourceSet;
-import org.eclipse.gemini.blueprint.context.BundleContextAware;
-import org.eclipse.gemini.blueprint.io.OsgiBundleResourceLoader;
-import org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver;
-import org.eclipse.gemini.blueprint.util.OsgiBundleUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.springframework.core.io.ResourceLoader;
-
-/**
- * Retrieves ressources from an OSGi bundle either the active one or another one
- * referenced by its symbolic name.
- */
-public class OsgiResourceSet extends DefaultResourceSet implements
- BundleContextAware {
- private BundleContext bundleContext;
- private Bundle bundle = null;
- private String bundleSymbolicName = null;
-
- private OsgiBundleResourceLoader osgiBundleResourceLoader = null;
-
- @Override
- public void afterPropertiesSet() throws Exception {
- osgiBundleResourceLoader = new OsgiBundleResourceLoader(getBundle());
- if (getResourcePatternResolver() == null)
- setResourcePatternResolver(new OsgiBundleResourcePatternResolver(
- osgiBundleResourceLoader));
- super.afterPropertiesSet();
- }
-
- public Bundle getBundle() {
- if (bundle != null)
- return bundle;
- else if (bundleSymbolicName != null)// do not cache
- return OsgiBundleUtils.findBundleBySymbolicName(bundleContext,
- bundleSymbolicName);
- else
- // containing bundle
- return bundleContext.getBundle();
- }
-
- public void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- @Override
- public ResourceLoader getResourceLoaderToUse() {
- return osgiBundleResourceLoader;
- }
-
- public void setBundle(Bundle bundle) {
- this.bundle = bundle;
- }
-
- public void setBundleSymbolicName(String bundleSymbolicName) {
- this.bundleSymbolicName = bundleSymbolicName;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 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. -->
-<!-- Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org> 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. -->
-
-<beans xmlns:osgi="http://www.springframework.org/schema/osgi"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
- xsi:schemaLocation="http://www.springframework.org/schema/osgi
- http://www.springframework.org/schema/osgi/spring-osgi-1.1.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
-
- <osgi:service interface="org.argeo.slc.execution.ExecutionContext"
- ref="executionContext" />
- <osgi:service
- interface="org.argeo.slc.execution.ExecutionFlowDescriptorConverter"
- ref="executionFlowDescriptorConverter" />
-
- <osgi:reference id="callbackHandler"
- interface="javax.security.auth.callback.CallbackHandler" cardinality="0..1" />
-
- <bean class="org.argeo.slc.osgi.MultipleServiceExporterPostProcessor">
- <property name="interfaces">
- <list>
- <value><![CDATA[org.argeo.slc.execution.ExecutionFlow]]></value>
- </list>
- </property>
- <property name="bundleContext" ref="bundleContext" />
- </bean>
-
- <bean id="osgiExecutionResources" class="org.argeo.slc.osgi.OsgiExecutionResources">
- <property name="executionContext" ref="executionContext" />
- </bean>
-</beans>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.spring;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-
-/** Provides base method for executing code with system authorization. */
-abstract class AbstractSystemExecution {
- private final static CmsLog log = CmsLog.getLog(AbstractSystemExecution.class);
- private final Subject subject = new Subject();
-
- /** Authenticate the calling thread */
- protected void authenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.login();
- } catch (LoginException e) {
- throw new SlcException("Cannot login as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- if (log.isTraceEnabled())
- log.trace("System authenticated");
- }
-
- protected void deauthenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.logout();
- } catch (LoginException e) {
- throw new SlcException("Cannot logout as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- }
-
- protected Subject getSubject() {
- return subject;
- }
-}
+++ /dev/null
-package org.argeo.slc.spring;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.support.AbstractBeanFactory;
-import org.springframework.beans.factory.support.SecurityContextProvider;
-import org.springframework.beans.factory.support.SimpleSecurityContextProvider;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-/**
- * Executes with a system authentication the instantiation and initialization
- * methods of the application context where it has been defined.
- */
-public class AuthenticatedApplicationContextInitialization extends
- AbstractSystemExecution implements
- DependencyInitializationAwareBeanPostProcessor, ApplicationContextAware {
- /** If non empty, restricts to these beans */
- private List<String> beanNames = new ArrayList<String>();
-
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- authenticateAsSystem();
- return bean;
- }
-
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- deauthenticateAsSystem();
- return bean;
- }
-
- public void setBeanNames(List<String> beanNames) {
- this.beanNames = beanNames;
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- if (applicationContext.getAutowireCapableBeanFactory() instanceof AbstractBeanFactory) {
- final AbstractBeanFactory beanFactory = ((AbstractBeanFactory) applicationContext
- .getAutowireCapableBeanFactory());
- // retrieve subject's access control context
- // and set it as the bean factory security context
- Subject.doAs(getSubject(), new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- SecurityContextProvider scp = new SimpleSecurityContextProvider(
- AccessController.getContext());
- beanFactory.setSecurityContextProvider(scp);
- return null;
- }
- });
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.auth;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-
-/** Provides base method for executing code with system authorization. */
-abstract class AbstractSystemExecution {
- private final static CmsLog log = CmsLog.getLog(AbstractSystemExecution.class);
- private final Subject subject = new Subject();
-
- /** Authenticate the calling thread */
- protected void authenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.login();
- } catch (LoginException e) {
- throw new SlcException("Cannot login as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- if (log.isTraceEnabled())
- log.trace("System authenticated");
- }
-
- protected void deauthenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(CmsAuth.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.logout();
- } catch (LoginException e) {
- throw new SlcException("Cannot logout as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- }
-
- protected Subject getSubject() {
- return subject;
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.auth;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.support.AbstractBeanFactory;
-import org.springframework.beans.factory.support.SecurityContextProvider;
-import org.springframework.beans.factory.support.SimpleSecurityContextProvider;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-/**
- * Executes with a system authentication the instantiation and initialization
- * methods of the application context where it has been defined.
- */
-public class AuthenticatedApplicationContextInitialization extends
- AbstractSystemExecution implements
- DependencyInitializationAwareBeanPostProcessor, ApplicationContextAware {
- /** If non empty, restricts to these beans */
- private List<String> beanNames = new ArrayList<String>();
-
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- authenticateAsSystem();
- return bean;
- }
-
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- deauthenticateAsSystem();
- return bean;
- }
-
- public void setBeanNames(List<String> beanNames) {
- this.beanNames = beanNames;
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- if (applicationContext.getAutowireCapableBeanFactory() instanceof AbstractBeanFactory) {
- final AbstractBeanFactory beanFactory = ((AbstractBeanFactory) applicationContext
- .getAutowireCapableBeanFactory());
- // retrieve subject's access control context
- // and set it as the bean factory security context
- Subject.doAs(getSubject(), new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- SecurityContextProvider scp = new SimpleSecurityContextProvider(
- AccessController.getContext());
- beanFactory.setSecurityContextProvider(scp);
- return null;
- }
- });
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.auth;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.osgi.transaction.WorkTransaction;
-import org.argeo.slc.SlcException;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.UserAdmin;
-
-/**
- * Register one or many roles via a user admin service. Does nothing if the role
- * is already registered.
- */
-public class SimpleRoleRegistration implements Runnable {
- private final static CmsLog log = CmsLog.getLog(SimpleRoleRegistration.class);
-
- private String role;
- private List<String> roles = new ArrayList<String>();
- private UserAdmin userAdmin;
- private WorkTransaction userTransaction;
-
- @Override
- public void run() {
- try {
- userTransaction.begin();
- if (role != null && !roleExists(role))
- newRole(toDn(role));
-
- for (String r : roles)
- if (!roleExists(r))
- newRole(toDn(r));
- userTransaction.commit();
- } catch (Exception e) {
- try {
- userTransaction.rollback();
- } catch (Exception e1) {
- log.error("Cannot rollback", e1);
- }
- throw new SlcException("Cannot add roles", e);
- }
- }
-
- private boolean roleExists(String role) {
- return userAdmin.getRole(toDn(role).toString()) != null;
- }
-
- protected void newRole(LdapName r) {
- userAdmin.createRole(r.toString(), Role.GROUP);
- log.info("Added role " + r + " required by application.");
- }
-
- public void register(UserAdmin userAdminService, Map<?, ?> properties) {
- this.userAdmin = userAdminService;
- run();
- }
-
- protected LdapName toDn(String name) {
- try {
- return new LdapName("cn=" + name + ",ou=roles,ou=node");
- } catch (InvalidNameException e) {
- throw new SlcException("Badly formatted role name " + name, e);
- }
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public void setRoles(List<String> roles) {
- this.roles = roles;
- }
-
- public void setUserAdmin(UserAdmin userAdminService) {
- this.userAdmin = userAdminService;
- }
-
- public void setUserTransaction(WorkTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.spring.repo.osgi;
-
-import org.argeo.api.cms.CmsLog;
-import org.springframework.beans.factory.BeanNameAware;
-
-public class BndWrapper extends org.argeo.slc.repo.osgi.BndWrapper implements BeanNameAware {
- private final static CmsLog log = CmsLog.getLog(BndWrapper.class);
-
- @Override
- public void setBeanName(String name) {
- if (getName() == null) {
- setName(name);
- } else {
- if (!name.contains("#"))
- log.warn("Using explicitely set name " + getName() + " and not bean name " + name);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.spring.repo.osgi;
-
-import org.argeo.api.cms.CmsLog;
-import org.springframework.beans.factory.BeanNameAware;
-
-public class MavenWrapper extends org.argeo.slc.repo.osgi.MavenWrapper implements BeanNameAware {
- private final static CmsLog log = CmsLog.getLog(MavenWrapper.class);
-
- @Override
- public void setBeanName(String name) {
- if (getName() == null) {
- setName(name);
- } else {
- if (!name.contains("#"))
- log.warn("Using explicitely set name " + getName() + " and not bean name " + name);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.spring.repo.osgi;
-
-import org.argeo.api.cms.CmsLog;
-import org.springframework.beans.factory.BeanNameAware;
-
-public class UriWrapper extends org.argeo.slc.repo.osgi.UriWrapper implements BeanNameAware {
- private final static CmsLog log = CmsLog.getLog(UriWrapper.class);
-
- @Override
- public void setBeanName(String name) {
- if (getName() == null) {
- setName(name);
- } else {
- if (!name.contains("#"))
- log.warn("Using explicitely set name " + getName() + " and not bean name " + name);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.spring.unit;
-
-import org.argeo.slc.execution.ExecutionFlow;
-
-public abstract class AbstractExecutionFlowTestcase extends AbstractSpringTestCase {
- @SuppressWarnings(value = { "unchecked" })
- protected <T extends ExecutionFlow> T executeFlow(String flowName) {
- ExecutionFlow flow = getBean(flowName);
- flow.run();
- return (T) flow;
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.unit;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.init.osgi.OsgiBoot;
-import org.argeo.slc.SlcException;
-import org.eclipse.core.runtime.adaptor.EclipseStarter;
-import org.eclipse.gemini.blueprint.util.OsgiStringUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.springframework.context.ApplicationContext;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("restriction")
-public abstract class AbstractOsgiRuntimeTestCase extends TestCase {
- private final static CmsLog log = CmsLog
- .getLog(AbstractOsgiRuntimeTestCase.class);
-
- protected OsgiBoot osgiBoot = null;
-
- protected void installBundles() throws Exception {
-
- }
-
- public void setUp() throws Exception {
- // To avoid xerces from the classpath being detected as the provider
- System
- .setProperty("javax.xml.parsers.DocumentBuilderFactory",
- "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
- System.setProperty("javax.xml.parsers.SAXParserFactory",
- "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
-
- BundleContext bundleContext = startRuntime();
- osgiBoot = new OsgiBoot(bundleContext);
- log.info("OSGi runtime started.");
-
- installBundles();
-
- List<String> bundlesToStart = getBundlesToStart();
- osgiBoot.startBundles(bundlesToStart);
- waitAllBundlesOk(bundlesToStart);
- if (log.isTraceEnabled())
- listInstalledBundles();
- }
-
- public void tearDown() throws Exception {
- osgiBoot = null;
- stopRuntime();
- log.info("OSGi runtime stopped.");
- }
-
- protected BundleContext startRuntime() throws Exception {
- String[] args = { "-console", "-clean" };
- BundleContext bundleContext = EclipseStarter.startup(args, null);
- return bundleContext;
- }
-
- protected void stopRuntime() throws Exception {
- EclipseStarter.shutdown();
- }
-
- protected List<String> getBundlesToStart() {
- return new ArrayList<String>();
- }
-
- protected void listInstalledBundles() {
- BundleContext bundleContext = osgiBoot.getBundleContext();
- Bundle[] bundles = bundleContext.getBundles();
- for (int i = 0; i < bundles.length; i++) {
- System.out.println(OsgiStringUtils.nullSafeSymbolicName(bundles[i])
- + " [" + OsgiStringUtils.bundleStateAsString(bundles[i])
- + "] " + bundles[i].getLocation());
- }
-
- }
-
- protected Map<Bundle, ApplicationContext> getOsgiApplicationContexts()
- throws Exception {
- Map<Bundle, ApplicationContext> map = new HashMap<Bundle, ApplicationContext>();
- BundleContext bundleContext = osgiBoot.getBundleContext();
- ServiceReference[] srs = bundleContext.getServiceReferences(
- ApplicationContext.class.getName(), null);
- for (ServiceReference sr : srs) {
- ApplicationContext context = (ApplicationContext) bundleContext
- .getService(sr);
- map.put(sr.getBundle(), context);
- }
- return map;
- }
-
- /** Wait for all bundles to be either RESOLVED or ACTIVE. */
- protected void waitAllBundlesOk(List<String> bundlesToStart) {
- BundleContext bundleContext = osgiBoot.getBundleContext();
- long begin = System.currentTimeMillis();
- long duration = 0;
- boolean allBundlesOk = true;
- StringBuffer badBundles = null;
- while (duration < getResolvedTimeout()) {
- badBundles = new StringBuffer();
- for (Bundle bundle : bundleContext.getBundles()) {
- if (bundle.getSymbolicName() != null
- && bundle.getSymbolicName().startsWith(
- "org.eclipse.jdt")) {
- // don't check Eclipse SDK bundles
- continue;
- }
-
- if (bundle.getState() == Bundle.INSTALLED) {
- allBundlesOk = false;
- badBundles
- .append(OsgiStringUtils
- .nullSafeSymbolicName(bundle)
- + " ["
- + OsgiStringUtils
- .bundleStateAsString(bundle) + "]");
- }
-
- if (bundlesToStart.contains(bundle.getSymbolicName())
- && bundle.getState() != Bundle.ACTIVE) {
- allBundlesOk = false;
- badBundles.append(OsgiStringUtils
- .nullSafeSymbolicName(bundle)
- + " ["
- + OsgiStringUtils.bundleStateAsString(bundle)
- + "]\n");
- }
- }
-
- if (allBundlesOk)
- break;// while
-
- sleep(1000);
-
- duration = System.currentTimeMillis() - begin;
- }
-
- if (!allBundlesOk) {
- listInstalledBundles();
- throw new SlcException(
- "Some bundles are not at the proper status:\n" + badBundles);
- }
- }
-
- /**
- * Make sure that the application context of the started bundles starting
- * with this prefix are properly initialized
- */
- protected void assertStartedBundlesApplicationContext(
- String bundleSymbolicNamesPrefix) {
- List<String> bundlesToStart = getBundlesToStart();
- for (String bundleSName : bundlesToStart) {
- if (bundleSName.startsWith(bundleSymbolicNamesPrefix))
- assertBundleApplicationContext(bundleSName);
- }
- }
-
- /**
- * Make sure that the application context of this bundle is properly
- * initialized
- */
- protected void assertBundleApplicationContext(String bundleSymbolicName) {
- String filter = "(Bundle-SymbolicName=" + bundleSymbolicName + ")";
- // Wait for application context to be ready
- try {
- ServiceReference[] srs = getServiceRefSynchronous(
- ApplicationContext.class.getName(), filter);
- if (srs == null)
- throw new SlcException("No application context for "
- + bundleSymbolicName);
- } catch (InvalidSyntaxException e) {
- throw new SlcException(
- "Unexpected exception when looking for application context for bundle "
- + bundleSymbolicName, e);
- }
- log.info("Application context of bundle " + bundleSymbolicName
- + " is initalized.");
- }
-
- protected ServiceReference[] getServiceRefSynchronous(String clss,
- String filter) throws InvalidSyntaxException {
- // FIXME: factorize
- if (log.isTraceEnabled())
- log.debug("Filter: '" + filter + "'");
- ServiceReference[] sfs = null;
- boolean waiting = true;
- long begin = System.currentTimeMillis();
- do {
- sfs = getBundleContext().getServiceReferences(clss, filter);
-
- if (sfs != null)
- waiting = false;
-
- sleep(100);
- if (System.currentTimeMillis() - begin > getDefaultTimeout())
- throw new SlcException("Search of services " + clss
- + " with filter " + filter + " timed out.");
- } while (waiting);
-
- return sfs;
- }
-
- protected BundleContext getBundleContext() {
- return osgiBoot.getBundleContext();
- }
-
- /** Default is 30s */
- protected long getResolvedTimeout() {
- return 30 * 1000l;
- }
-
- /** Default is 10s */
- protected long getDefaultTimeout() {
- return 10 * 1000l;
- }
-
- final protected void sleep(long duration) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // silent
- }
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.unit;
-
-import java.util.Map;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.springframework.beans.factory.BeanFactoryUtils;
-import org.springframework.beans.factory.ListableBeanFactory;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-import junit.framework.TestCase;
-
-/** Helper for tests using a Spring application co,text. */
-public abstract class AbstractSpringTestCase extends TestCase {
- protected final CmsLog log = CmsLog.getLog(getClass());
- private ConfigurableApplicationContext context;
-
- /**
- * Gets (and create if necessary) the application context to use. Default
- * implementation uses a class path xml application context and calls
- * {@link #getApplicationContextLocation()}.
- */
- protected ConfigurableApplicationContext getContext() {
- if (context == null) {
- context = new ClassPathXmlApplicationContext(
- getApplicationContextLocation());
- if (getIsStartContext())
- context.start();
- }
- return context;
- }
-
- @Override
- protected void tearDown() throws Exception {
- if (context != null && context.isActive())
- context.close();
- super.tearDown();
- }
-
- /** Whether the context should be started after being created. */
- protected Boolean getIsStartContext() {
- return false;
- }
-
- /** Returns a bean from the underlying context */
- @SuppressWarnings(value = { "unchecked" })
- protected <T> T getBean(String beanId) {
- return (T) getContext().getBean(beanId);
- }
-
- protected <T> T getBean(Class<? extends T> clss) {
- T bean = loadSingleFromContext(getContext(), clss);
- if (bean == null) {
- throw new SlcException("Cannot retrieve a unique bean of type "
- + clss);
- } else {
- return bean;
- }
- }
-
- /**
- * Th location of the application to load. The default implementation
- * returns <i>applicationContext.xml</i> found in the same package as the
- * test.
- */
- protected String getApplicationContextLocation() {
- return inPackage("applicationContext.xml");
- }
-
- /**
- * Prefixes the package of the class after converting the '.' to '/' in
- * order to have a resource path.
- */
- protected String inPackage(String suffix) {
- String prefix = getClass().getPackage().getName().replace('.', '/');
- return prefix + '/' + suffix;
- }
-
- @SuppressWarnings(value = { "unchecked" })
- protected <T> T loadSingleFromContext(ListableBeanFactory context,
- Class<T> clss) {
- Map<String, T> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, clss, false, false);
- if (beans.size() == 1) {
- return beans.values().iterator().next();
- } else if (beans.size() > 1) {
- if (log.isDebugEnabled()) {
- log
- .debug(("Found more that on bean for type " + clss
- + ": " + beans.keySet()));
- }
- return null;
- } else {
- return null;
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.spring.unit;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.slc.core.execution.DefaultExecutionSpec;
-import org.argeo.slc.execution.ExecutionFlowDescriptor;
-import org.argeo.slc.execution.ExecutionSpecAttribute;
-import org.argeo.slc.execution.RefSpecAttribute;
-import org.argeo.slc.execution.RefValue;
-import org.argeo.slc.execution.RefValueChoice;
-import org.argeo.slc.primitive.PrimitiveAccessor;
-import org.argeo.slc.primitive.PrimitiveSpecAttribute;
-import org.argeo.slc.primitive.PrimitiveValue;
-import org.argeo.slc.runtime.test.BasicTestData;
-
-public class ExecutionFlowDescriptorTestUtils {
- public static ExecutionFlowDescriptor createSimpleExecutionFlowDescriptor() {
- ExecutionFlowDescriptor flowDescriptor = new ExecutionFlowDescriptor();
- flowDescriptor.setName("simpleFlow");
- flowDescriptor.setDescription("my description");
-
- Map<String, Object> values = new HashMap<String, Object>();
- values.put("primitiveInteger", new PrimitiveValue(
- PrimitiveAccessor.TYPE_INTEGER, 100));
-
- RefValue refValue = new RefValue("002");
- values.put("ref1", refValue);
- flowDescriptor.setValues(values);
-
- flowDescriptor.setExecutionSpec(createRelatedSimpleSpec());
- return flowDescriptor;
- }
-
- protected static DefaultExecutionSpec createRelatedSimpleSpec() {
- DefaultExecutionSpec spec = new DefaultExecutionSpec();
- spec.setBeanName("simpleSpec");
- Map<String, ExecutionSpecAttribute> attributes = new HashMap<String, ExecutionSpecAttribute>();
-
- PrimitiveSpecAttribute primitiveInteger = new PrimitiveSpecAttribute();
- primitiveInteger.setType(PrimitiveAccessor.TYPE_INTEGER);
- primitiveInteger.setValue(50);
- attributes.put("primitiveInteger", primitiveInteger);
-
- RefSpecAttribute ref1 = new RefSpecAttribute();
- ref1.setTargetClass(BasicTestData.class);
- ref1.setChoices(new ArrayList<RefValueChoice>());
- ref1.getChoices().add(new RefValueChoice("001", "desc"));
- ref1.getChoices().add(new RefValueChoice("002", null));
- ref1.getChoices().add(new RefValueChoice("003", null));
- attributes.put("ref1", ref1);
-
- spec.setAttributes(attributes);
-
- return spec;
- }
-}
+++ /dev/null
-package org.argeo.slc.spring.unit;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-
-public abstract class UnitUtils {
- public static void assertDateSec(Date expected, Date reached) {
- if (expected == null) {
- assertNull(reached);
- return;
- } else {
- assertNotNull(reached);
- }
-
- Calendar expectedCal = new GregorianCalendar();
- expectedCal.setTime(expected);
- Calendar reachedCal = new GregorianCalendar();
- reachedCal.setTime(reached);
- assertEquals(expectedCal.get(Calendar.YEAR), reachedCal
- .get(Calendar.YEAR));
- assertEquals(expectedCal.get(Calendar.MONTH), reachedCal
- .get(Calendar.MONTH));
- assertEquals(expectedCal.get(Calendar.DATE), reachedCal
- .get(Calendar.DATE));
- assertEquals(expectedCal.get(Calendar.HOUR_OF_DAY), reachedCal
- .get(Calendar.HOUR_OF_DAY));
- assertEquals(expectedCal.get(Calendar.MINUTE), reachedCal
- .get(Calendar.MINUTE));
- assertEquals(expectedCal.get(Calendar.SECOND), reachedCal
- .get(Calendar.SECOND));
- }
-
- private UnitUtils() {
-
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src"/>
- <classpathentry kind="src" path="ext/test"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-/bin/
-/target/
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.slc.support</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-Import-Package: org.apache.commons.logging,\
-org.dbunit.*;resolution:="optional",\
-junit.framework;resolution:="optional",\
-javax.mail.*;resolution:="optional",\
-org.apache.commons.vfs.*,\
-javax.swing.plaf.metal,\
-org.osgi.*;version=0.0.0,\
-*
\ No newline at end of file
+++ /dev/null
-# 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
+++ /dev/null
-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);
- }
- }
-}
+++ /dev/null
-<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>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </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.runtime</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.spring</artifactId>
- <version>2.3-SNAPSHOT</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.diff;
-
-/**
- * Converts data into a format better adapted for comparison. It is typically
- * used to convert <code>String</code> into typed format such as
- * <code>BigDecimal</code>
- */
-public interface DataInterpreter {
- /**
- * Converts data
- *
- * @param key
- * any object used to differentiate the type of data (e.g.
- * column, path)
- * @param value
- * the data to convert
- * @return the converted object
- */
- public Object convert(Object key, Object value);
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-import org.springframework.core.io.Resource;
-
-/** A comparator providing structured information about the differences found. */
-public interface Diff {
- /** Performs the comparison. */
- public void compare(Resource expected, Resource reached,
- DiffResult diffResult);
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/** The root class for issues which happened during a diff. */
-public abstract class DiffIssue implements Comparable<DiffIssue> {
- /** The position of this issue. */
- // Was final and is not anymore in order to persist in hibernate
- protected DiffPosition position;
-
- // hibernate
- private long id;
-
- /** Constructor */
- public DiffIssue(DiffPosition position) {
- super();
- this.position = position;
- }
-
- public int compareTo(DiffIssue o) {
- return position.compareTo(o.position);
- }
-
- /** The position of this issue within the test file */
- public DiffPosition getPosition() {
- return position;
- }
-
- // Hibernate
- @SuppressWarnings("unused")
- private void setId(long id) {
- this.id = id;
- }
-
- @SuppressWarnings("unused")
- private long getId() {
- return id;
- }
-
- @SuppressWarnings("unused")
- private void setPosition(DiffPosition position) {
- this.position = position;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/** Intermediate class that can hold the key to be displayed. */
-public abstract class DiffIssueKey extends DiffIssue {
- /** The position of this issue. */
- protected DiffKey key;
-
- /** Constructor without key */
- public DiffIssueKey(DiffPosition position) {
- super(position);
- }
-
- /** Constructor with key */
- public DiffIssueKey(DiffPosition position, DiffKey key) {
- super(position);
- this.key = key;
- }
-
- public Object getKey() {
- return key;
- }
-
- @Override
- public String toString() {
- if (key != null) {
- return key.toString();
- } else {
- return "";
- }
- }
-
- // Hibernate
- @SuppressWarnings("unused")
- private void setKey(DiffKey key) {
- this.key = key;
- }
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/**
- * Object able to uniquely identify an atomic diff part. Used to identify
- * missings and left-overs.
- */
-public interface DiffKey {
- public String toString();
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/**
- * A value missing in one of the file. If its position is related to expected,
- * this means it is a left over in the reached, if its position is related to
- * the reached it means that it is missing from the reached. If the value is
- * null it means that the entire line is missing.
- */
-public class DiffMissing extends DiffIssueKey {
-
- public DiffMissing(DiffPosition position, DiffKey key) {
- super(position);
- super.key = key;
- }
-
- @Override
- public String toString() {
- if (position.relatedFile == RelatedFile.EXPECTED) {
- return position + ": left over " + super.toString();
- } else if (position.relatedFile == RelatedFile.REACHED) {
- return position + ": missing " + super.toString();
- }
- return super.toString();
- }
-
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/**
- * <code>DiffMissing</code> using the XPath of the position as
- * <code>DiffKey</code>
- */
-public class DiffMissingXml extends DiffMissing {
-
- public DiffMissingXml(XPathDiffPosition position) {
- super(position, new DiffKeyXml(position.getXPath()));
- }
-
- /** Implementation of <code>DiffKey</code> based on an XPath string. */
- protected static class DiffKeyXml implements DiffKey {
- private final String xPath;
-
- public DiffKeyXml(String xPath) {
- this.xPath = xPath;
- }
-
- public String getXPath() {
- return xPath;
- }
-
- @Override
- public String toString() {
- return xPath;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof DiffKeyXml))
- return false;
- return xPath.equals(((DiffKeyXml) obj).xPath);
- }
-
- @Override
- public int hashCode() {
- return xPath.hashCode();
- }
-
- }
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-import org.argeo.slc.SlcException;
-
-/** Diff issue where reached and expected values are different. */
-public class DiffNotMatched extends DiffIssueKey {
-
- // To enable hibernate persistance, these object cannot be final
- // private final Object expected;
- // private final Object reached;
-
- private Object expected;
- private Object reached;
-
- public DiffNotMatched(DiffPosition position, Object expected, Object reached) {
- super(position);
- this.expected = expected;
- this.reached = reached;
- }
-
- public DiffNotMatched(DiffPosition position, Object expected,
- Object reached, DiffKey key) {
- super(position, key);
- this.expected = expected;
- this.reached = reached;
- }
-
- public Object getExpected() {
- return expected;
- }
-
- public Object getReached() {
- return reached;
- }
-
- @Override
- public String toString() {
- String result = position + ": not matched " + expected + " <> "
- + reached;
- if (super.key != null) {
- result = result + " - Key: " + super.toString();
- }
-
- return result;
- }
-
- @SuppressWarnings("unused")
- private String getExpectedStr() {
- if (expected instanceof String)
- return (String) expected;
- else
- throw new SlcException(
- "Object 'expected' is of wrong type. Must be a String");
- }
-
- @SuppressWarnings("unused")
- private String getReachedStr() {
- if (reached instanceof String)
- return (String) reached;
- else
- throw new SlcException(
- "Object 'reached' is of wrong type. Must be a String");
- }
-
- @SuppressWarnings("unused")
- private void setReachedStr(String reachedStr) {
- this.reached = reachedStr;
- }
-
- @SuppressWarnings("unused")
- private void setExpectedStr(String expectedStr) {
- this.expected = expectedStr;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/** The position of a diff issue within the test resource. */
-public abstract class DiffPosition implements Comparable<DiffPosition> {
- protected RelatedFile relatedFile;
-
- public DiffPosition(RelatedFile relatedFile) {
- super();
- this.relatedFile = relatedFile;
- }
-
- // For Hibernate
- DiffPosition() {
- }
-
- public RelatedFile getRelatedFile() {
- return relatedFile;
- }
-
- // Added to enable the new data model for persisting TabularDiffTestResult
- @SuppressWarnings("unused")
- private Boolean getIsReached() {
- return relatedFile.equals(RelatedFile.REACHED);
- }
-
- @SuppressWarnings("unused")
- private void setIsReached(Boolean isReached) {
- this.relatedFile = (isReached ? RelatedFile.REACHED
- : RelatedFile.EXPECTED);
- }
-
-}
+++ /dev/null
-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);
-
-}
+++ /dev/null
-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();
-}
+++ /dev/null
-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, "");
- }
-
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/** Enumeration of the types of resource tested. */
-public enum RelatedFile {
- /** The expected resource */
- EXPECTED,
- /** The reached resource */
- REACHED
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-import org.argeo.slc.UnsupportedException;
-
-/**
- * A diff position within a table structure such a CSV file or an SQL result
- * set.
- */
-public class TableDiffPosition extends DiffPosition {
- private Integer line;
- /** Can be null */
- private Integer column;
- /** Can be null */
- private String columnName;
-
- public TableDiffPosition(RelatedFile relatedFile, Integer line,
- Integer column, String columnName) {
- super(relatedFile);
- this.line = line;
- this.column = column;
- this.columnName = columnName;
- }
-
- @SuppressWarnings("unused")
- private TableDiffPosition() {
- }
-
- public Integer getLine() {
- return line;
- }
-
- public Integer getColumn() {
- return column;
- }
-
- public String getColumnName() {
- return columnName;
- }
-
- public int compareTo(DiffPosition dp) {
- if (!(dp instanceof TableDiffPosition))
- throw new UnsupportedException("position", dp);
-
- TableDiffPosition o = (TableDiffPosition) dp;
- if (relatedFile.equals(o.relatedFile)) {
- if (line == o.line) {
- return column.compareTo(o.column);
- } else {
- return line.compareTo(o.line);
- }
- } else {
- return relatedFile.compareTo(o.relatedFile);
- }
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer("");
- buf.append(relatedFile).append('[').append(line);
- if (column != null) {
- buf.append(',').append(column);
- if (columnName != null) {
- buf.append('-').append(columnName);
- }
- }
- buf.append(']');
- return buf.toString();
- }
-
- // Hibernate
- @SuppressWarnings("unused")
- private void setLine(Integer line) {
- this.line = line;
- }
-
- @SuppressWarnings("unused")
- private void setColumn(Integer column) {
- this.column = column;
- }
-
- @SuppressWarnings("unused")
- private void setColumnName(String columnName) {
- this.columnName = columnName;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-/** Compares objects, eventually using tolerance mechanisms. */
-public interface Tolerance {
- /**
- * Compares objects
- *
- * @param key
- * any object used to differentiate the type of data (e.g.
- * column, path)
- * @param expected
- * the expected value
- * @param reached
- * the reached value
- * @return the converted object
- */
- public Boolean compare(Object key, Object expected, Object reached);
-}
+++ /dev/null
-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();
-}
+++ /dev/null
-package org.argeo.slc.diff;
-
-import org.argeo.slc.UnsupportedException;
-
-/** A diff position within an Xml file. <b>NOT YET IMPLEMENTED</b>. */
-public class XPathDiffPosition extends DiffPosition {
-
- private String xPath;
-
- public XPathDiffPosition(RelatedFile relatedFile, String path) {
- super(relatedFile);
- xPath = path;
- }
-
- public int compareTo(DiffPosition dp) {
- if (!(dp instanceof XPathDiffPosition))
- throw new UnsupportedException("position", dp);
-
- XPathDiffPosition o = (XPathDiffPosition) dp;
- if (relatedFile.equals(o.relatedFile)) {
- return xPath.compareTo(o.xPath);
- } else {
- return relatedFile.compareTo(o.relatedFile);
- }
- }
-
- public String getXPath() {
- return xPath;
- }
-
- @Override
- public String toString() {
- return xPath;
- }
-}
+++ /dev/null
-<html>\r
-<head></head>\r
-<body>\r
-Abstraction of diff comparison with structured results.\r
-</body>\r
-</html>
\ No newline at end of file
+++ /dev/null
-package org.argeo.slc.jsch;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.PrivilegedAction;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Logger;
-import com.jcraft.jsch.Session;
-import com.jcraft.jsch.UserAuthGSSAPIWithMIC;
-
-public abstract class AbstractJschTask implements Runnable {
- private final CmsLog log = CmsLog.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.setConfig("userauth.gssapi-with-mic", UserAuthGSSAPIWithMIC.class.getName());
- 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;
- }
-
- PrivilegedAction<Void> asPrivilegedAction() {
- return new PrivilegedAction<Void>() {
- public Void run() {
- AbstractJschTask.this.run();
- return null;
- }
- };
- }
-
- static {
- JSch.setLogger(new JschLogger());
- }
-
- private static class JschLogger implements Logger {
- private final CmsLog log = CmsLog.getLog(JschLogger.class);
-
- // TODO better support levels
- @Override
- public boolean isEnabled(int level) {
- if (log.isTraceEnabled())
- return true;
- return false;
- }
-
- @Override
- public void log(int level, String message) {
- log.trace(message);
- }
-
- }
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.jsch;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-
-class GetMachineId {
-
- public static void main(String[] args) {
- URL url = GetMachineId.class.getResource("jaas.cfg");
- System.setProperty("java.security.auth.login.config", url.toExternalForm());
-
- String hostname = args[0];
- try {
- LoginContext lc = new LoginContext("SINGLE_USER");
- lc.login();
-
- SshTarget sshTarget = new SshTarget();
- sshTarget.setHost(hostname);
- RemoteExec remoteExec = new RemoteExec();
- remoteExec.setCommand("cat /etc/machine-id");
- remoteExec.setSshTarget(sshTarget);
- List<String> lines = new ArrayList<>();
- remoteExec.setStdOutLines(lines);
-
- Subject.doAs(lc.getSubject(), remoteExec.asPrivilegedAction());
-
- String machineId = lines.get(0);
- System.out.println(hostname + ": " + machineId);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
-}
+++ /dev/null
-package org.argeo.slc.jsch;
-
-import org.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.jsch;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-import java.util.Arrays;
-
-import org.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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);
- }
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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;
- }
-}
+++ /dev/null
-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;
- }
-
- }
-
-}
+++ /dev/null
-SINGLE_USER {
- com.sun.security.auth.module.Krb5LoginModule optional
- principal="${user.name}"
- useTicketCache=true;
-};
+++ /dev/null
-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.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.api.cms.CmsLog;
-import org.argeo.cms.jcr.CmsJcrUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-
-/** Backups a JCR repository */
-public class JcrRepositoryBackup implements Runnable {
- private final static CmsLog log = CmsLog.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 = CmsJcrUtils.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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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();
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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);
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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
+++ /dev/null
-#!/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
+++ /dev/null
-<?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
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.lib.vbox;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-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 CmsLog log = CmsLog.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;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.io.File;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeployEnvironment;
-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 HttpdApplicationDeployment implements Deployment {
- private static final CmsLog log = CmsLog
- .getLog(HttpdApplicationDeployment.class);
-
- private HttpdApplicationTargetData targetData;
- private DeploymentData deploymentData;
- private SimpleHttpdApplication deployedSystem;
- private Distribution distribution;
-
- private DeployEnvironment deployEnvironment;
-
- public void run() {
- try {
- deployEnvironment.unpackTo(distribution, targetData
- .getTargetRootLocation(), null);
-
- // FIXME: make it generic
- String deployDataPath = targetData.getTargetRootLocation()
- .getCanonicalPath();
-
- deployEnvironment.unpackTo(deploymentData,
- new File(deployDataPath), null);
- deployedSystem = new SimpleHttpdApplication();
- deployedSystem.setTargetData(targetData);
-
- log.info("Deployed " + distribution + " to " + targetData);
- } catch (Exception e) {
- throw new SlcException("Cannot deploy " + distribution + " to "
- + targetData, e);
- }
-
- }
-
- public void setTargetData(TargetData targetData) {
- this.targetData = (HttpdApplicationTargetData) targetData;
- }
-
- public void setDeploymentData(DeploymentData deploymentData) {
- this.deploymentData = deploymentData;
- }
-
- public DeployedSystem getDeployedSystem() {
- return deployedSystem;
- }
-
- public void setDistribution(Distribution distribution) {
- this.distribution = distribution;
- }
-
- public void setDeployEnvironment(DeployEnvironment deployEnvironment) {
- this.deployEnvironment = deployEnvironment;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.deploy.TargetData;
-
-public class HttpdApplicationTargetData implements TargetData {
- private HttpdServer webServer;
- private String relativePath;
- private String targetRootPath;
-
- public HttpdServer getWebServer() {
- return webServer;
- }
-
- public void setWebServer(HttpdServer webServer) {
- this.webServer = webServer;
- }
-
- public String getRelativePath() {
- return relativePath;
- }
-
- /**
- * If targetRootLocation not set, used to build the targetRootLocation,
- * relative to the webserver base.
- */
- public void setRelativePath(String relativePath) {
- this.relativePath = relativePath;
- }
-
- public String getTargetRootPath() {
- return targetRootPath;
- }
-
- public void setTargetRootPath(String targetRootPath) {
- this.targetRootPath = targetRootPath;
- }
-
- public URL getTargetBaseUrl() {
- try {
- URL wsUrl = getWebServer().getBaseUrl();
- // TODO: use URI
- return new URL(wsUrl, wsUrl.getFile() + '/' + relativePath);
- } catch (MalformedURLException e) {
- throw new SlcException("Cannot get base url for " + relativePath, e);
- }
- }
-
- public File getTargetRootLocation() {
- if (targetRootPath != null && !targetRootPath.equals("")) {
- return new File(targetRootPath);
- } else {
- HttpdServerTargetData targetData = (HttpdServerTargetData) getWebServer()
- .getTargetData();
- String path = targetData.getServerRoot() + File.separator
- + getRelativePath();
- return new File(path);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.io.IOException;
-import java.net.URL;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeploymentData;
-import org.argeo.slc.deploy.TargetData;
-
-public class HttpdServer implements WebServer {
- private HttpdServerTargetData targetData;
- private HttpdServerDeploymentData deploymentData;
-
- public URL getBaseUrl() {
- try {
- return new URL("http://localhost:" + targetData.getPort());
- } catch (IOException e) {
- throw new SlcException("Cannot get url for Httpd server "
- + getDeployedSystemId(), e);
- }
- }
-
- public String getDeployedSystemId() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Distribution getDistribution() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public DeploymentData getDeploymentData() {
- return deploymentData;
- }
-
- public TargetData getTargetData() {
- return targetData;
- }
-
- public void setTargetData(TargetData targetData) {
- this.targetData = (HttpdServerTargetData)targetData;
- }
-
- public void setDeploymentData(DeploymentData deploymentData) {
- this.deploymentData = (HttpdServerDeploymentData)deploymentData;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-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.argeo.api.cms.CmsLog;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.deploy.DeployedSystemManager;
-
-public class HttpdServerManager implements DeployedSystemManager<HttpdServer> {
- private final static CmsLog log = CmsLog.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();
- }
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.io.File;
-import java.net.URL;
-
-import org.argeo.slc.build.Distribution;
-import org.argeo.slc.deploy.DeploymentData;
-
-public class SimpleHttpdApplication implements WebApplication {
- private HttpdApplicationTargetData targetData;
- private Distribution distribution;
-
- public void setDistribution(Distribution distribution) {
- this.distribution = distribution;
- }
-
- public URL getBaseUrl() {
- return targetData.getTargetBaseUrl();
- }
-
- public File getRootLocation() {
- return targetData.getTargetRootLocation();
- }
-
- public String getDeployedSystemId() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public HttpdApplicationTargetData getTargetData() {
- return targetData;
- }
-
- public void setTargetData(HttpdApplicationTargetData targetData) {
- this.targetData = targetData;
- }
-
- public Distribution getDistribution() {
- return distribution;
- }
-
- public DeploymentData getDeploymentData() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.io.File;
-import java.net.URL;
-
-import org.argeo.slc.deploy.DeployedSystem;
-
-public interface WebApplication extends DeployedSystem {
- public URL getBaseUrl();
-
- public File getRootLocation();
-}
+++ /dev/null
-package org.argeo.slc.support.deploy;
-
-import java.net.URL;
-
-import org.argeo.slc.deploy.DeployedSystem;
-
-public interface WebServer extends DeployedSystem {
- public URL getBaseUrl();
-}
+++ /dev/null
-package org.argeo.slc.support.deploy.db;
-
-import java.sql.Connection;
-
-public interface DbModel {
- public void createSchema(Connection connection);
-}
+++ /dev/null
-package org.argeo.slc.support.deploy.db;
-
-import javax.sql.DataSource;
-
-public interface JdbcAware {
- public DataSource getDataSource();
-}
+++ /dev/null
-package org.argeo.slc.support.deploy.db;
-
-import javax.sql.DataSource;
-
-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 SimpleJdbcDatabase implements DeployedSystem, JdbcAware {
- private DataSource dataSource;
-
- public String getDeployedSystemId() {
- return dataSource.toString();
- }
-
- public DataSource getDataSource() {
- return dataSource;
- }
-
- public void setDataSource(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- @Override
- public Distribution getDistribution() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public DeploymentData getDeploymentData() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public TargetData getTargetData() {
- throw new UnsupportedOperationException();
- }
-}
+++ /dev/null
-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;
- }
-}
+++ /dev/null
-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();
- }
-
- }
-
-}
+++ /dev/null
-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;
- }
-
-}
+++ /dev/null
-<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>
- <artifactId>argeo-slc</artifactId>
- <version>2.3-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>legacy</artifactId>
- <version>2.3-SNAPSHOT</version>
- <packaging>pom</packaging>
- <name>SLC Legacy Argeo Software</name>
- <modules>
- <!-- Legacy UI -->
- <module>org.argeo.legacy.fake.java8</module>
- <module>argeo-commons</module>
-
- <!-- Legacy Runtime -->
- <module>org.argeo.slc.spring</module>
- <module>org.argeo.slc.support</module>
- <module>org.argeo.slc.launcher</module>
-
- <!-- Legacy Modules -->
- <module>org.argeo.slc.agent</module>
- <module>org.argeo.slc.agent.jcr</module>
- <module>org.argeo.slc.server.repo</module>
-
- <!-- Legacy UI -->
- <module>org.argeo.slc.client.ui</module>
- <module>org.argeo.slc.client.ui.dist</module>
- <module>org.argeo.slc.client.rap</module>
-
- <!-- To be imported by Spring-based modules -->
- <module>lib</module>
-
- <!-- Spring-based modules demo -->
-<!-- <module>org.argeo.slc.demo.ant</module> -->
-<!-- <module>org.argeo.slc.demo.basic</module> -->
-<!-- <module>org.argeo.slc.demo.minimal</module> -->
-
- <module>dep</module>
- </modules>
-</project>
\ No newline at end of file
<!-- Distribution -->
<module>dep</module>
<module>ide</module>
-
- <!-- Legacy -->
- <module>legacy</module>
</modules>
<url>http://projects.argeo.org/slc/</url>
<scm>