--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src/main/java"/>
+ <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="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
+#Thu Apr 14 17:49:18 CEST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.5
--- /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 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 RAP</beans:description>\r
+\r
+ <reference id="nodeRepository" interface="javax.jcr.Repository"\r
+ filter="(argeo.jcr.repository.alias=node)" />\r
+\r
+ <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
+ <reference id="keyring" interface="org.argeo.security.crypto.CryptoKeyring" />\r
+\r
+</beans:beans>
\ 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
+ parameter="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>plugins</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ <relativePath>..</relativePath>
+ </parent>
+ <artifactId>org.argeo.slc.client.rap</artifactId>
+ <name>SLC Client RAP</name>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.argeo.slc.client.rap.SlcRapPlugin</Bundle-Activator>
+ <Require-Bundle>org.eclipse.rap.ui;resolution:=optional</Require-Bundle>
+ <Import-Package>
+ javax.jcr.nodetype,
+ javax.servlet,
+ javax.servlet.http,
+ org.argeo.eclipse.spring,
+ org.argeo.slc.repo.core,
+ *
+ </Import-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <!-- SLC -->
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.repo</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+
+ <!-- Argeo common distribution for RAP projects -->
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.dep.rap</artifactId>
+ <version>${version.argeo-commons}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>org.mortbay.jetty.server</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>org.mortbay.jetty.server.util</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.eclipse.equinox</groupId>
+ <artifactId>org.eclipse.equinox.http.jetty</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <!-- Argeo common distribution for Secured UI -->
+ <dependency>
+ <groupId>org.argeo.commons.security</groupId>
+ <artifactId>org.argeo.security.ui.rap</artifactId>
+ <version>${version.argeo-commons}</version>
+ </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.HttpServletResponse;
+
+import org.apache.commons.io.IOUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.eclipse.rwt.RWT;
+import org.eclipse.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() 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.rap;
+
+import org.argeo.security.ui.rap.RapWindowAdvisor;
+import org.argeo.security.ui.rap.RapWorkbenchAdvisor;
+import org.argeo.security.ui.rap.SecureEntryPoint;
+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 SecureEntryPoint {
+
+ @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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.client.rap.SlcRapPlugin;
+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.rwt.RWT;
+import org.eclipse.rwt.service.IServiceHandler;
+import org.eclipse.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);
+ 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("?");
+ 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/main/java"/>
+ <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
+<?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
+#Wed Dec 08 08:27:02 CET 2010
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.5
--- /dev/null
+#Wed Dec 08 08:27:02 CET 2010
+eclipse.preferences.version=1
+pluginProject.extensions=false
+resolve.requirebundle=false
--- /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="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </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="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </bean>
+
+ <bean id="normalizeWorkspace"
+ class="org.argeo.slc.client.ui.dist.commands.NormalizeWorkspace">
+ <property name="repositoryFactory" ref="repositoryFactory" />
+ <property name="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </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="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </bean>
+
+ <bean id="copyWorkspace" class="org.argeo.slc.client.ui.dist.commands.CopyWorkspace">
+ <property name="repositoryFactory" ref="repositoryFactory" />
+ <property name="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </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="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </bean>
+
+ <bean id="deleteWorkspace" class="org.argeo.slc.client.ui.dist.commands.DeleteWorkspace">
+ <property name="repositoryFactory" ref="repositoryFactory" />
+ <property name="nodeRepository" ref="nodeRepository" />
+ <property name="keyring" ref="keyring" />
+ </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="org.argeo.slc.client.ui.dist.genericJcrQueryEditor"
+ class="org.argeo.eclipse.ui.jcr.editors.GenericJcrQueryEditor" scope="prototype">
+ <property name="session" ref="slcSession" />
+ </bean>
+
+ <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>
--- /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="slcSession" class="org.argeo.jcr.spring.ThreadBoundSession">
+ <property name="repository" ref="javaRepository" />
+ <property name="workspace" value="org.argeo.tp-1.3.1" />
+ </bean>
+
+ <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>
--- /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="(argeo.jcr.repository.alias=java)" />\r
+\r
+ <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
+ <reference id="keyring" interface="org.argeo.security.crypto.CryptoKeyring" />\r
+\r
+ <reference id="nodeRepository" interface="javax.jcr.Repository"\r
+ filter="(argeo.jcr.repository.alias=node)" />\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>
--- /dev/null
+source.. = src/main/java/
+output.. = target/classes/
+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>plugins</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ <relativePath>..</relativePath>
+ </parent>
+ <artifactId>org.argeo.slc.client.ui.dist</artifactId>
+ <name>SLC Client UI Distribution</name>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.argeo.slc.client.ui.dist.DistPlugin</Bundle-Activator>
+ <Require-Bundle>
+ org.eclipse.ui;resolution:=optional,
+ org.eclipse.rap.ui;resolution:=optional,
+ org.eclipse.core.runtime;resolution:=optional,
+ org.eclipse.rap.ui.workbench;resolution:=optional
+ </Require-Bundle>
+ <Import-Package>
+ org.argeo.eclipse.spring,
+ javax.jcr.nodetype,
+ javax.jcr.security,
+ aQute.lib.*;resolution:=optional,
+ org.argeo.slc.client.ui.specific,
+ *
+ </Import-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+
+ <!-- Single sourcing - we build against RCP -->
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.client.rcp</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Commons UI -->
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui.jcr</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui.rcp</artifactId>
+ <version>${version.argeo-commons}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- SLC repo -->
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.specs</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.repo</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.server.repo</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.argeo.tp</groupId>
+ <artifactId>biz.aQute.bndlib</artifactId>
+ </dependency>
+
+ <!-- Argeo Base dependencies -->
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.util</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+
+ </dependencies>
+</project>
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist;
+
+import org.argeo.slc.jcr.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist;
+
+public class DistLabels {
+
+ public static String getLabel(String jcrName){
+ String label = null;
+
+
+ return label;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+public class DistPlugin extends AbstractUIPlugin {
+ public final static String 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(ID, path);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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;
+
+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;
+import org.springframework.security.Authentication;
+import org.springframework.security.context.SecurityContextHolder;
+
+/**
+ * Propagate authentication to an eclipse job. Typically to execute a privileged
+ * action outside the UI thread
+ */
+public abstract class PrivilegedJob extends Job {
+
+ private final Authentication authentication;
+ private Subject subject;
+
+ public PrivilegedJob(String jobName) {
+ super(jobName);
+ authentication = SecurityContextHolder.getContext().getAuthentication();
+ subject = Subject.getSubject(AccessController.getContext());
+ }
+
+ @Override
+ protected IStatus run(final IProgressMonitor progressMonitor) {
+ PrivilegedAction<IStatus> privilegedAction = new PrivilegedAction<IStatus>() {
+ public IStatus run() {
+ SecurityContextHolder.getContext().setAuthentication(
+ authentication);
+ return doRun(progressMonitor);
+ }
+ };
+ return Subject.doAs(subject, privilegedAction);
+ }
+
+ /** Implement here what should be executed with default context authentication*/
+ protected abstract IStatus doRun(IProgressMonitor progressMonitor);
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.lib.osgi.Builder;
+import aQute.lib.osgi.Constants;
+import aQute.lib.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+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.PrivilegedJob;
+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 Log log = LogFactory
+ .getLog(CopyLocalJavaWorkspace.class);
+
+ public final static String ID = DistPlugin.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();
+
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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 ArgeoException(
+ "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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+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.PrivilegedJob;
+import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(CopyWorkspace.class);
+
+ public final static String ID = DistPlugin.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();
+
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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 ArgeoException(
+ "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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.commands;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.eclipse.ui.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 Log log = LogFactory
+ .getLog(CreateLocalJavaWorkspace.class);
+
+ // Exposes commands meta-info
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.eclipse.ui.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.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(CreateWorkspace.class);
+
+ // Exposes commands meta-info
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.commands;
+
+import java.util.Iterator;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.argeo.ArgeoException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory.getLog(DeleteWorkspace.class);
+
+ public final static String ID = DistPlugin.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 ArgeoException(
+ "Unexpected error while deleting artifacts.", re);
+ }
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(DeleteWorkspace.class);
+
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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;
+
+/**
+ * Utilitary command used to enable sub menus in various toolbars. Does nothing
+ */
+public class DoNothing extends AbstractHandler {
+ public final static String ID = DistPlugin.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.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.argeo.slc.repo.RepoSync;
+import org.argeo.util.security.Keyring;
+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 {@link RepoSync} as an Eclipse command. Open a wizard that enable
+ * definition of the fetch process parameters
+ */
+public class Fetch extends AbstractHandler {
+ // private final static Log log = LogFactory.getLog(Fetch.class);
+
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.commands;
+
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.argeo.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+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.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.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 ArgeoException("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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+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.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(MergeWorkspaces.class);
+
+ public final static String ID = DistPlugin.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...");
+
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(eclipseMonitor);
+ eclipseMonitor
+ .beginTask("Copy files", expectedCount.intValue());
+
+ Long count = JcrUtils.copyFiles(sourceSession.getRootNode(),
+ targetSession.getRootNode(), true, monitor);
+
+ 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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.NameVersion;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.aether.AetherUtils;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.ArtifactIndexer;
+import org.argeo.slc.repo.JarFileIndexer;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+import org.argeo.slc.repo.osgi.NormalizeGroup;
+import org.argeo.util.security.Keyring;
+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;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/** Legacy - Make sure than Maven and OSGi metadata are consistent */
+public class NormalizeDistribution extends AbstractHandler implements SlcNames {
+ private final static Log log = LogFactory
+ .getLog(NormalizeDistribution.class);
+
+ public final static String ID = DistPlugin.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 {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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.ID,
+ "Cannot normalize distribution "
+ + session.getWorkspace().getName(), e);
+ } finally {
+ JcrUtils.logoutQuietly(session);
+ }
+ return Status.OK_STATUS;
+ }
+
+ }
+
+ private class NormalizingTraverser extends TraversingItemVisitor {
+ ArgeoMonitor monitor;
+
+ public NormalizingTraverser(ArgeoMonitor 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 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+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.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(NormalizeWorkspace.class);
+
+ public final static String ID = DistPlugin.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 {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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.ID,
+ "Cannot normalize distribution "
+ + session.getWorkspace().getName(), e);
+ } finally {
+ JcrUtils.logoutQuietly(session);
+ }
+ return Status.OK_STATUS;
+ }
+ }
+
+ private class NormalizingTraverser extends TraversingItemVisitor {
+ ArgeoMonitor monitor;
+
+ public NormalizingTraverser(ArgeoMonitor 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());
+ pdeSourceIndexer.index(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());
+ 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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 Log log = LogFactory.getLog(DeleteWorkspace.class);
+
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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.jcr.SlcTypes;
+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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.commands;
+
+import javax.jcr.Node;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.argeo.jcr.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.DistWorkspaceEditor;
+import org.argeo.slc.client.ui.dist.editors.DistWkspEditorInput;
+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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcConstants;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+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 Log log = LogFactory.getLog(PublishWorkspace.class);
+
+ public final static String ID = DistPlugin.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();
+ 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 ArgeoException(
+ "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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.commands;
+
+import javax.jcr.Repository;
+import javax.jcr.RepositoryFactory;
+
+import org.argeo.jcr.ArgeoNames;
+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.argeo.slc.jcr.SlcNames;
+import org.argeo.util.security.Keyring;
+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
+ */
+public class RegisterRepository extends AbstractHandler implements ArgeoNames,
+ SlcNames {
+
+ public final static String ID = DistPlugin.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;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.eclipse.ui.ErrorFeedback;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.core.execution.tasks.JvmProcess;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+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;
+import org.sonatype.aether.artifact.Artifact;
+
+/** <b>UNDER DEVELOPMENT</b>. Download and prepare an OSGi runtime */
+public class RunInOsgi extends AbstractHandler implements SlcNames {
+ private final static Log log = LogFactory.getLog(RunInOsgi.class);
+
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.ArgeoTypes;
+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;
+
+/**
+ * Unregisters 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 Log log = LogFactory
+ // .getLog(UnregisterRemoteRepo.class);
+
+ public final static String ID = DistPlugin.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.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();
+ 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;
+
+/**
+ * Enables 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 {
+
+ // 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.client.ui.dist.DistImages;
+import org.argeo.slc.jcr.SlcTypes;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.graphics.Image;
+
+public class ArtifactLabelProvider extends ColumnLabelProvider implements
+ DistConstants, SlcTypes {
+
+ // 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 ArgeoException(
+ "Unexepected error while getting property values", re);
+ }
+ return null;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.eclipse.ui.jcr.utils.JcrItemsComparator;
+import org.argeo.slc.jcr.SlcTypes;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+public class ArtifactsTreeContentProvider implements ITreeContentProvider,
+ SlcTypes {
+
+ // 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 ArgeoException(
+ "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 ArgeoException(
+ "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.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+
+/**
+ * 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 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.eclipse.ui.TreeParent;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.ArgeoTypes;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.jcr.UserJcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.model.RepoElem;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.util.security.Keyring;
+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 Session nodeSession;
+ List<RepoElem> repositories = new ArrayList<RepoElem>();
+
+ /* DEPENDENCY INJECTION */
+ private RepositoryFactory repositoryFactory;
+ private Keyring keyring;
+
+ public Object[] getElements(Object input) {
+ Repository nodeRepository = (Repository) input;
+ try {
+ if (nodeSession != null)
+ dispose();
+ nodeSession = nodeRepository.login();
+
+ String reposPath = UserJcrUtils.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 = UserJcrUtils.getUserHome(nodeSession);
+ if (homeNode == null) // anonymous
+ throw new SlcException("User must be authenticated.");
+
+ // make sure base directory is available
+ Node repos = JcrUtils.mkdirs(nodeSession, homeNode.getPath()
+ + RepoConstants.REPOSITORIES_BASE_PATH);
+ nodeSession.save();
+
+ // register default local java repository
+ String alias = RepoConstants.DEFAULT_JAVA_REPOSITORY_ALIAS;
+ Repository javaRepository = ArgeoJcrUtils.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.eclipse.ui.utils.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.eclipse.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;
+
+/**
+ * Manages icons and labels for the Distributions tree browser
+ */
+public class DistTreeLabelProvider extends ColumnLabelProvider {
+ @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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.argeo.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+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;
+
+/**
+ * Base editor to manage an artifact in a multiple repository environment
+ */
+public class ArtifactVersionEditor extends FormEditor implements SlcNames {
+ // private final static Log log =
+ // LogFactory.getLog(ArtifactEditor.class);
+ public final static String ID = DistPlugin.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 ArgeoException("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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ErrorFeedback;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.client.ui.dist.DistImages;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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);
+ // /gd.heightHint = 200;
+ 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() {
+ @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() {
+
+ 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() {
+ @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() {
+ @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() {
+ @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() {
+ @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() {
+ @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() {
+ @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 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.utils.CommandUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.build.License;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.client.ui.dist.utils.AbstractHyperlinkListener;
+import org.argeo.slc.client.ui.specific.OpenJcrFile;
+import org.argeo.slc.client.ui.specific.OpenJcrFileCmdId;
+import org.argeo.slc.jcr.SlcNames;
+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 the details for a given bundle.
+ */
+public class BundleDetailPage extends FormPage implements SlcNames {
+ private final static Log log = LogFactory.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 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(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 AbstractHyperlinkListener {
+ final private String path;
+
+ public OpenFileLinkListener(String path) {
+ this.path = path;
+ }
+
+ @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, 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 ArgeoException(
+ "unexpected error while generating maven snippet");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.slc.client.ui.dist.DistImages;
+import org.argeo.slc.client.ui.dist.utils.DistUiHelpers;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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;
+
+/**
+ * Lists 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 {
+
+ 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 ArgeoException(
+ "unexpected error while getting artifact information",
+ e);
+ }
+ }
+ }
+
+ private class TreeContentProvider implements ITreeContentProvider {
+ 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 ArgeoException(
+ "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 ArgeoException(
+ "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 ArgeoException(
+ "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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+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.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory
+ // .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() {
+ @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() {
+
+ 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+import org.argeo.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.client.ui.dist.PrivilegedJob;
+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.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory
+ // .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 {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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.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() {
+ 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() {
+ @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() {
+ @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() {
+ @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() {
+ 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() {
+ @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 {
+ // 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+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 final static Log log =
+ // LogFactory.getLog(DistributionEditor.class);
+ public final static String ID = DistPlugin.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 ArgeoException("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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.argeo.ArgeoException;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.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 ArgeoException(
+ "unexpected error while generating maven snippet");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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 final static Log log =
+ // LogFactory.getLog(ModularDistVersionEditor.class);
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.EclipseUiUtils;
+import org.argeo.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+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.AbstractHyperlinkListener;
+import org.argeo.slc.client.ui.dist.utils.DistNodeViewerComparator;
+import org.argeo.slc.client.ui.specific.OpenJcrFile;
+import org.argeo.slc.client.ui.specific.OpenJcrFileCmdId;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.slc.repo.maven.MavenConventionsUtils;
+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;
+import org.sonatype.aether.artifact.Artifact;
+import org.sonatype.aether.util.artifact.DefaultArtifact;
+
+/**
+ * Show all modules contained in a given modular distribution as filter-able
+ * table
+ */
+public class ModularDistVersionOverviewPage extends FormPage implements
+ SlcNames {
+
+ 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 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 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 AbstractHyperlinkListener {
+ final private String path;
+
+ public OpenFileLinkListener(String path) {
+ this.path = path;
+ }
+
+ @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, 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() {
+ public void modifyText(ModifyEvent event) {
+ refresh();
+ }
+ });
+
+ Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
+ resetBtn.setImage(DistImages.IMG_CLEAR);
+ resetBtn.addSelectionListener(new SelectionAdapter() {
+ 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() {
+ @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() {
+ @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() {
+ @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() {
+ @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() {
+ @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 {
+ // 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPersistableElement;
+
+/**
+ * An 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.editors;
+
+import javax.jcr.Node;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.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() {
+ @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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.jcr.AsyncUiEventListener;
+import org.argeo.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+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.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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() {
+ public void modifyText(ModifyEvent event) {
+ refresh();
+ }
+ });
+
+ Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
+ resetBtn.setImage(DistImages.IMG_REPO_READONLY);
+ resetBtn.addSelectionListener(new SelectionAdapter() {
+ 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() {
+ @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() {
+ @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() {
+ 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.refreshParametrizedCommand(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() {
+ @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 {
+ // 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.ArgeoException;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.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 ArgeoException("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.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.slc.repo.RepoUtils;
+import org.argeo.util.security.Keyring;
+
+/**
+ * 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 Log log = LogFactory.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 = ArgeoJcrUtils.getRepositoryByUri(
+ repositoryFactory, uri);
+ else {
+ repository = RepoUtils.getRepository(repositoryFactory,
+ keyring, repoNode);
+ credentials = RepoUtils.getRepositoryCredentials(keyring,
+ repoNode);
+ }
+
+ try {
+ defaultSession = repository.login(credentials);
+ 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 {
+ 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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+
+/**
+ * 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 ArgeoException("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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.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 ArgeoException(
+ "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 ArgeoException(
+ "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
+/*
+ * Argeo Connect - Data management and communications
+ * Copyright (C) 2012 Argeo GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ * Additional permission under GNU GPL version 3 section 7
+ *
+ * If you modify this Program, or any covered work, by linking or combining it
+ * with software covered by the terms of the Eclipse Public License, the
+ * licensors of this Program grant you additional permission to convey the
+ * resulting work. Corresponding Source for a non-source form of such a
+ * combination shall include the source code for the parts of such software
+ * which are used as well as that of the covered work.
+ */
+package org.argeo.slc.client.ui.dist.utils;
+
+import org.eclipse.ui.forms.events.HyperlinkEvent;
+import org.eclipse.ui.forms.events.IHyperlinkListener;
+
+public abstract class AbstractHyperlinkListener implements IHyperlinkListener {
+
+ public void linkEntered(HyperlinkEvent e) {
+ }
+
+ public void linkExited(HyperlinkEvent e) {
+ }
+
+ /** Must be overriden **/
+ public abstract void linkActivated(HyperlinkEvent e);
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.eclipse.ui.GenericTableComparator;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory
+ // .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() {
+ @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() {
+ public String getText(Object element) {
+ return null;
+ }
+
+ public Image getImage(Object element) {
+ return null;
+ }
+ };
+ } else
+ return new ColumnLabelProvider() {
+ public String getText(Object element) {
+ Row row = (Row) element;
+ try {
+ return row.getValue(columnName).getString();
+ } catch (RepositoryException e) {
+ throw new ArgeoException("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 {
+
+ 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 ArgeoException("comparator for object type "
+ + v1.getType() + " is not yet implemented");
+ } catch (Exception e) {
+ throw new ArgeoException("rows cannot be compared ", e);
+ }
+ } else
+ throw new ArgeoException("Unsupported row type");
+ // If descending order, flip the direction
+ if (direction == DESCENDING) {
+ rc = -rc;
+ }
+ return rc;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.argeo.ArgeoException;
+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 ArgeoException(
+ "Unexepected exception while opening node editor", e);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.GenericTableComparator;
+import org.eclipse.jface.viewers.Viewer;
+
+/** Add ability to order by name version and version */
+public class DistNodeViewerComparator extends GenericTableComparator {
+ private final static Log log = LogFactory
+ .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 ArgeoException(
+ "Unimplemented comparaison for PropertyType "
+ + propertyType);
+ }
+
+ // If descending order, flip the direction
+ if (direction == DESCENDING) {
+ rc = -rc;
+ }
+
+ } catch (RepositoryException re) {
+ throw new ArgeoException("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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.slc.client.ui.dist.DistConstants;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+
+public class DistUiHelpers implements DistConstants, SlcTypes, SlcNames {
+ private final static Log log = LogFactory.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 ArgeoException("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.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 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 {
+
+ @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;
+
+/**
+ * Centralizes 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.GenericTableComparator;
+import org.argeo.slc.client.ui.dist.utils.ArtifactsTableConfigurer;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory
+ .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 ArgeoException("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 {
+
+ 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 {
+ 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.views;
+
+import org.argeo.jcr.ArgeoNames;
+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.argeo.slc.jcr.SlcNames;
+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 Log log = LogFactory
+ // .getLog(AnonymousDistributionsView.class);
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+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.jcr.SlcTypes;
+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 Log log = LogFactory.getLog(ArtifactsBrowser.class);
+ public final static String ID = DistPlugin.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 ArgeoException("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 {
+
+ // 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 ArgeoException(
+ "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 ArgeoException(
+ // "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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.views;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+
+import org.argeo.eclipse.ui.TreeParent;
+import org.argeo.eclipse.ui.utils.CommandUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.slc.SlcException;
+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.argeo.slc.jcr.SlcNames;
+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.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() {
+ 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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(menuManager, window,
+ DeleteWorkspace.ID, DeleteWorkspace.DEFAULT_LABEL,
+ DeleteWorkspace.DEFAULT_ICON, isDistribElem
+ && singleElement && !isReadOnly, params);
+
+ // Advanced submenu
+ MenuManager submenu = new MenuManager("Advanced", DistPlugin.ID
+ + ".advancedSubmenu");
+ IContributionItem ici = menuManager.find(DistPlugin.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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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 repository) {
+ this.nodeRepository = repository;
+ }
+
+ public void setTreeContentProvider(
+ DistTreeContentProvider treeContentProvider) {
+ this.treeContentProvider = treeContentProvider;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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;
+
+/**
+ *
+ * Displays some info about the distribution
+ *
+ */
+public class HelpView extends ViewPart {
+ public final static String ID = DistPlugin.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.views;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+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 Log log = LogFactory.getLog(QueryArtifactsForm.class);
+ public static final String ID = DistPlugin.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() {
+ 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 ArgeoException(
+ "Cannot generate where statement to get artifacts", e);
+ }
+ }
+
+ @Override
+ public void setFocus() {
+ executeBtn.setFocus();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.views;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+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.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() {
+ 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.views;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 Log log = LogFactory.getLog(QueryBundlesForm.class);
+ public static final String ID = DistPlugin.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() {
+ 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 ArgeoException(
+ "Cannot generate where statement to get artifacts", e);
+ }
+ }
+
+ @Override
+ public void setFocus() {
+ executeBtn.setFocus();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.wizards;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.argeo.ArgeoException;
+import org.argeo.jcr.JcrUtils;
+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 ArgeoException("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 ArgeoException(
+ "Unexpected error while setting privileges", re);
+ }
+ return true;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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 {
+
+ // 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.ArgeoTypes;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.jcr.UserJcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.dist.DistPlugin;
+import org.argeo.slc.client.ui.dist.PrivilegedJob;
+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.argeo.util.security.Keyring;
+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 Log log = LogFactory.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 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() {
+ 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() {
+ 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() {
+ @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 WkspComparator());
+ }
+ }
+
+ private class AdvancedFetchPage extends WizardPage {
+
+ 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 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() {
+ @Override
+ public String getText(Object element) {
+ return ((WkspObject) element).srcName;
+ }
+ });
+
+ column = ViewerUtils.createTableViewerColumn(recapViewer,
+ "targets", SWT.NONE, 250);
+ column.setLabelProvider(new ColumnLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ return ((WkspObject) element).targetName;
+ }
+ });
+
+ recapViewer.setContentProvider(new IStructuredContentProvider() {
+
+ 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 WkspComparator());
+ 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 {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(progressMonitor);
+ repoSync.setMonitor(monitor);
+ repoSync.run();
+ } catch (Exception e) {
+ return new Status(IStatus.ERROR, DistPlugin.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 {
+ // 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();
+ session = currSourceRepo.login(currSourceCred);
+ // 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(UserJcrUtils.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+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.PrivilegedJob;
+import org.argeo.slc.client.ui.dist.utils.ViewerUtils;
+import org.argeo.slc.jcr.SlcTypes;
+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.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;
+import org.sonatype.aether.artifact.Artifact;
+
+/**
+ * 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 Log log = LogFactory
+ .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 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() {
+ @Override
+ public String getText(Object element) {
+ return ((Artifact) element).getArtifactId();
+ }
+ });
+
+ column = ViewerUtils.createTableViewerColumn(recapViewer,
+ "Version", SWT.NONE, 250);
+ column.setLabelProvider(new ColumnLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ return ((Artifact) element).getBaseVersion();
+ }
+ });
+
+ recapViewer.setContentProvider(new IStructuredContentProvider() {
+ 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 {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(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.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.dist.wizards;
+
+import java.net.URI;
+import java.util.Hashtable;
+
+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.eclipse.ui.ErrorFeedback;
+import org.argeo.jcr.ArgeoJcrConstants;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.ArgeoTypes;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.jcr.UserJcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.repo.RepoConstants;
+import org.argeo.util.security.Keyring;
+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 = "http://repo.argeo.org/data/pub/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();
+ String reposPath = UserJcrUtils.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 {
+
+ 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() {
+ 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() {
+ 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();
+ Hashtable<String, String> params = new Hashtable<String, String>();
+ params.put(ArgeoJcrConstants.JCR_REPOSITORY_URI, checkedUriStr);
+ Repository repository = ArgeoJcrUtils.getRepositoryByUri(
+ repositoryFactory, checkedUriStr);
+ if (username.getText().trim().equals("")) {// anonymous
+ session = repository.login();
+ } 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);
+ }
+ } else {// alias
+ Repository repository = ArgeoJcrUtils.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/main/java"/>
+ <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
+<?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
+#Wed Aug 04 16:31:36 CEST 2010
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.5
--- /dev/null
+#Tue Jul 27 14:24:51 CEST 2010
+eclipse.preferences.version=1
+resolve.requirebundle=false
--- /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="(argeo.jcr.repository.alias=slc)" />\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
+source.. = src/main/java
+output.. = target/classes
+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="ROLE_SLC" />
+ </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>plugins</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ <relativePath>..</relativePath>
+ </parent>
+ <artifactId>org.argeo.slc.client.ui</artifactId>
+ <name>SLC Client UI</name>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.argeo.slc.client.ui.ClientUiPlugin</Bundle-Activator>
+ <Require-Bundle>
+ org.eclipse.ui;resolution:=optional,
+ org.eclipse.core.runtime;resolution:=optional,
+ org.eclipse.rap.ui;resolution:=optional,
+ org.eclipse.rap.ui.workbench;resolution:=optional
+ </Require-Bundle>
+ <Import-Package>
+ org.argeo.eclipse.spring,
+ org.argeo.security.ui,
+ *
+ </Import-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <!-- Single sourcing - we build against RCP -->
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.client.rcp</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- SLC -->
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.core</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.slc</groupId>
+ <artifactId>org.argeo.slc.support.jcr</artifactId>
+ <version>2.1.1-SNAPSHOT</version>
+ </dependency>
+
+ <!-- Argeo Commons -->
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui.jcr</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.commons.security</groupId>
+ <artifactId>org.argeo.security.ui</artifactId>
+ <version>${version.argeo-commons}</version>
+ </dependency>
+
+ <!-- Eclipse and RCP only dependency, needed at compile time -->
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.ui.rcp</artifactId>
+ <version>${version.argeo-commons}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.commons.base</groupId>
+ <artifactId>org.argeo.eclipse.dep.rcp</artifactId>
+ <version>${version.argeo-commons}</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+</project>
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.deploy.ModulesManager;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui;
+
+import org.argeo.security.ui.SecurityUiPlugin;
+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.3f, 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.commands;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.argeo.eclipse.ui.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
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.client.ui.commands;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+import javax.jcr.Node;\r
+import javax.jcr.RepositoryException;\r
+import javax.jcr.Session;\r
+\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.client.ui.ClientUiPlugin;\r
+import org.argeo.slc.client.ui.model.ResultFolder;\r
+import org.argeo.slc.client.ui.model.ResultParent;\r
+import org.argeo.slc.client.ui.model.ResultParentUtils;\r
+import org.argeo.slc.client.ui.model.SingleResultNode;\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+\r
+/** Deletes one or many results */\r
+public class DeleteItems extends AbstractHandler {\r
+ public final static String ID = ClientUiPlugin.ID + ".deleteItems";\r
+ public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin\r
+ .getImageDescriptor("icons/removeAll.png");\r
+ public final static String DEFAULT_LABEL = "Delete selected item(s)";\r
+\r
+ public Object execute(final ExecutionEvent event) throws ExecutionException {\r
+ final ISelection selection = HandlerUtil\r
+ .getActiveWorkbenchWindow(event).getActivePage().getSelection();\r
+\r
+ // confirmation\r
+ StringBuilder buf = new StringBuilder("");\r
+ Iterator<?> lst = ((IStructuredSelection) selection).iterator();\r
+ while (lst.hasNext()) {\r
+ Object obj = lst.next();\r
+ if (obj instanceof ResultParent) {\r
+ ResultParent rp = ((ResultParent) obj);\r
+ buf.append(rp.getName()).append(", ");\r
+ }\r
+ }\r
+\r
+ String msg = "Nothing to delete";\r
+ // remove last separator\r
+ if (buf.lastIndexOf(", ") > -1) {\r
+ msg = "Do you want to delete following objects (and their children): "\r
+ + buf.substring(0, buf.lastIndexOf(", ")) + "?";\r
+ }\r
+ Boolean ok = MessageDialog.openConfirm(\r
+ HandlerUtil.getActiveShell(event), "Confirm deletion", msg);\r
+\r
+ if (!ok)\r
+ return null;\r
+\r
+ Job job = new Job("Delete results") {\r
+ @Override\r
+ protected IStatus run(IProgressMonitor monitor) {\r
+ if (selection != null\r
+ && selection instanceof IStructuredSelection) {\r
+ Map<String, Node> nodes = new HashMap<String, Node>();\r
+ Iterator<?> it = ((IStructuredSelection) selection)\r
+ .iterator();\r
+ Object obj = null;\r
+ try {\r
+\r
+ while (it.hasNext()) {\r
+ obj = it.next();\r
+ if (obj instanceof ResultFolder) {\r
+ Node node = ((ResultFolder) obj).getNode();\r
+ nodes.put(node.getPath(), node);\r
+ } else if (obj instanceof SingleResultNode) {\r
+ Node node = ((SingleResultNode) obj).getNode();\r
+ nodes.put(node.getPath(), node);\r
+ }\r
+ }\r
+ if (!nodes.isEmpty()) {\r
+ Session session = null;\r
+ monitor.beginTask("Delete results", nodes.size());\r
+ for (String path : nodes.keySet()) {\r
+ if (session == null)\r
+ session = nodes.get(path).getSession();\r
+\r
+ // check if the item has not already been\r
+ // deleted while deleting one of its ancestor\r
+ if (session.itemExists(path)) {\r
+ Node parent = nodes.get(path).getParent();\r
+ nodes.get(path).remove();\r
+ ResultParentUtils.updatePassedStatus(\r
+ parent, true);\r
+ }\r
+ monitor.worked(1);\r
+ }\r
+ session.save();\r
+ }\r
+\r
+ } catch (RepositoryException e) {\r
+ throw new SlcException(\r
+ "Unexpected error while deleteting node(s)", e);\r
+ }\r
+ monitor.done();\r
+ }\r
+ return Status.OK_STATUS;\r
+ }\r
+\r
+ };\r
+ job.setUser(true);\r
+ job.schedule();\r
+ return null;\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.client.ui.commands;\r
+\r
+import java.util.Iterator;\r
+\r
+import org.argeo.slc.client.ui.ClientUiPlugin;\r
+import org.argeo.slc.client.ui.model.ResultParent;\r
+import org.argeo.slc.client.ui.views.JcrResultTreeView;\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.jface.resource.ImageDescriptor;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+\r
+/**\r
+ * Force refresh the ResultTreeView. This command is only intended to be called\r
+ * by either the toolbar menu of the view or by the popup menu. Refresh due to\r
+ * data changes must be triggered by Observers\r
+ */\r
+public class RefreshJcrResultTreeView extends AbstractHandler {\r
+ public final static String ID = ClientUiPlugin.ID\r
+ + ".refreshJcrResultTreeView";\r
+ public final static String PARAM_REFRESH_TYPE = ClientUiPlugin.ID\r
+ + ".param.refreshType";\r
+ public final static String PARAM_REFRESH_TYPE_FULL = "fullRefresh";\r
+ public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin\r
+ .getImageDescriptor("icons/refresh.png");\r
+ public final static String DEFAULT_LABEL = "Refresh selected";\r
+\r
+ public Object execute(final ExecutionEvent event) throws ExecutionException {\r
+ String refreshType = event.getParameter(PARAM_REFRESH_TYPE);\r
+ JcrResultTreeView view = (JcrResultTreeView) HandlerUtil\r
+ .getActiveWorkbenchWindow(event).getActivePage()\r
+ .getActivePart();\r
+\r
+ // force full refresh without preserving selection from the tool bar\r
+ if (PARAM_REFRESH_TYPE_FULL.equals(refreshType))\r
+ view.refresh(null);\r
+ else {\r
+ IStructuredSelection selection = (IStructuredSelection) HandlerUtil\r
+ .getActiveWorkbenchWindow(event).getActivePage()\r
+ .getSelection();\r
+ @SuppressWarnings("rawtypes")\r
+ Iterator it = selection.iterator();\r
+ while (it.hasNext()) {\r
+ Object obj = it.next();\r
+ if (obj instanceof ResultParent) {\r
+ view.refresh((ResultParent) obj);\r
+ }\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+}\r
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.client.ui.commands;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+import javax.jcr.Node;\r
+\r
+import org.apache.commons.logging.Log;\r
+import org.apache.commons.logging.LogFactory;\r
+import org.argeo.slc.BasicNameVersion;\r
+import org.argeo.slc.NameVersion;\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.deploy.ModulesManager;\r
+import org.argeo.slc.jcr.SlcNames;\r
+import org.argeo.slc.jcr.SlcTypes;\r
+import org.eclipse.core.commands.AbstractHandler;\r
+import org.eclipse.core.commands.ExecutionEvent;\r
+import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.jobs.Job;\r
+import org.eclipse.jface.viewers.ISelection;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.ui.handlers.HandlerUtil;\r
+\r
+/** Deletes one or many results */\r
+public class UpdateModule extends AbstractHandler {\r
+ private final static Log log = LogFactory.getLog(UpdateModule.class);\r
+\r
+ private ModulesManager modulesManager;\r
+\r
+ public Object execute(ExecutionEvent event) throws ExecutionException {\r
+ final ISelection selection = HandlerUtil\r
+ .getActiveWorkbenchWindow(event).getActivePage().getSelection();\r
+ if (selection != null && selection instanceof IStructuredSelection) {\r
+ UpdateJob job = new UpdateJob(selection);\r
+ job.setUser(true);\r
+ job.schedule();\r
+ }\r
+ return null;\r
+ }\r
+\r
+ private class UpdateJob extends Job {\r
+ private final IStructuredSelection selection;\r
+\r
+ public UpdateJob(ISelection selection) {\r
+ super("Update modules");\r
+ this.selection = ((IStructuredSelection) selection);\r
+ }\r
+\r
+ @Override\r
+ protected IStatus run(IProgressMonitor monitor) {\r
+ Iterator<?> it = selection.iterator();\r
+ Object obj = null;\r
+ try {\r
+ Map<String, Node> nodes = new HashMap<String, Node>();\r
+ nodes: while (it.hasNext()) {\r
+ obj = it.next();\r
+ if (obj instanceof Node) {\r
+ Node node = (Node) obj;\r
+ Node executionModuleNode = null;\r
+ while (executionModuleNode == null) {\r
+ if (node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE)) {\r
+ executionModuleNode = node;\r
+ }\r
+ node = node.getParent();\r
+ if (node.getPath().equals("/"))// root\r
+ continue nodes;\r
+ }\r
+\r
+ if (!nodes.containsKey(executionModuleNode.getPath()))\r
+ nodes.put(executionModuleNode.getPath(),\r
+ executionModuleNode);\r
+ }\r
+ }\r
+\r
+ monitor.beginTask("Update modules", nodes.size());\r
+ for (Node executionModuleNode : nodes.values()) {\r
+ monitor.subTask("Update " + executionModuleNode.getName());\r
+ NameVersion nameVersion = new BasicNameVersion(\r
+ executionModuleNode.getProperty(SlcNames.SLC_NAME)\r
+ .getString(), executionModuleNode\r
+ .getProperty(SlcNames.SLC_VERSION)\r
+ .getString());\r
+ modulesManager.upgrade(nameVersion);\r
+ monitor.worked(1);\r
+ log.info("Module " + nameVersion + " updated");\r
+ if (monitor.isCanceled())\r
+ return Status.CANCEL_STATUS;\r
+ }\r
+ return Status.OK_STATUS;\r
+ } catch (Exception e) {\r
+ throw new SlcException("Cannot update module " + obj, e);\r
+ // return Status.CANCEL_STATUS;\r
+ }\r
+ }\r
+\r
+ @Override\r
+ protected void canceling() {\r
+ getThread().interrupt();\r
+ super.canceling();\r
+ }\r
+\r
+ }\r
+\r
+ public void setModulesManager(ModulesManager modulesManager) {\r
+ this.modulesManager = modulesManager;\r
+ }\r
+\r
+}\r
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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.argeo.slc.jcr.SlcNames;
+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 Log log = LogFactory
+ // .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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+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.ArgeoException;
+import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+import org.argeo.slc.client.ui.SlcImages;
+import org.argeo.slc.core.execution.PrimitiveAccessor;
+import org.argeo.slc.core.execution.PrimitiveUtils;
+import org.argeo.slc.execution.ExecutionProcess;
+import org.argeo.slc.jcr.SlcJcrUtils;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 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;
+ }
+
+ @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 ArgeoException("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 = processNode.getSession().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 ArgeoException("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 ArgeoException("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);
+ 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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.ErrorFeedback;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+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.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+import org.eclipse.core.runtime.IProgressMonitor;
+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 {
+ public final static String ID = ClientUiPlugin.ID + ".processEditor";
+
+ private Session session;
+ private Node processNode;
+ private ProcessController processController;
+
+ private ProcessBuilderPage builderPage;
+
+ private ExecutionModulesManager modulesManager;
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ super.init(site, input);
+ ProcessEditorInput pei = (ProcessEditorInput) input;
+ String processPath = pei.getProcessPath();
+ try {
+ if (processPath != null) {
+ if (!session.itemExists(processPath))
+ throw new SlcException("Process " + processPath
+ + " does not exist");
+ processNode = session.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(session,
+ uuid);
+ Node processNode = JcrUtils.mkdirs(session, 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(session);
+ 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 = flowNode.getSession().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);
+ session.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 updateStatus(ExecutionProcess process, String oldStatus,
+ // String newStatus) {
+ // }
+ //
+ // public void addSteps(ExecutionProcess process, List<ExecutionStep> steps)
+ // {
+ // }
+
+ /** Expects one session per editor. */
+ @Deprecated
+ public void setSession(Session session) {
+ this.session = session;
+ }
+
+ public void setRepository(Repository repository) {
+ try {
+ session = repository.login();
+ } catch (RepositoryException re) {
+ throw new SlcException("Unable to log in Repository " + repository,
+ re);
+ }
+ }
+
+ public void setProcessController(ProcessController processController) {
+ this.processController = processController;
+ }
+
+ public void setModulesManager(ExecutionModulesManager modulesManager) {
+ this.modulesManager = modulesManager;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.execution.ExecutionStep;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.jcr.SlcNames;
+import org.argeo.slc.jcr.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 Log log = LogFactory.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.model;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.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.jcr.SlcNames;
+import org.argeo.slc.jcr.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.jcr.SlcJcrResultUtils;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+
+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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.jcr.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.client.ui.model;
+
+import java.util.List;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.argeo.slc.SlcException;
+import org.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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 Log log = LogFactory
+ // .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
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+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.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.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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.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 Log log = LogFactory
+ .getLog(JcrExecutionModulesView.class);
+
+ public static final String ID = ClientUiPlugin.ID
+ + ".jcrExecutionModulesView";
+
+ private TreeViewer viewer;
+
+ /* DEPENDENCY INJECTION */
+ private Session session;
+ private ExecutionModulesManager modulesManager;
+
+ public void createPartControl(Composite parent) {
+ 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 {
+
+ 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 ArgeoException("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 {
+
+ @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 {
+
+ // 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);
+ super.dispose();
+ }
+
+ // DEPENDENCY INJECTION
+
+ public void setModulesManager(ExecutionModulesManager modulesManager) {
+ this.modulesManager = modulesManager;
+ }
+
+ @Deprecated
+ public void setSession(Session session) {
+ this.session = session;
+ }
+
+ public void setRepository(Repository repository) {
+ try {
+ session = repository.login();
+ } catch (RepositoryException re) {
+ throw new SlcException("Unable to log in Repository " + repository,
+ re);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.eclipse.ui.jcr.AsyncUiEventListener;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.slc.SlcException;
+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.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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.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 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) {
+ 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);
+ }
+ }
+
+ }
+
+ @Deprecated
+ public void setSession(Session session) {
+ this.session = session;
+ }
+
+ public void dispose() {
+ JcrUtils.unregisterQuietly(session.getWorkspace(), processesObserver);
+ JcrUtils.logoutQuietly(session);
+ super.dispose();
+ }
+
+ public void setRepository(Repository repository) {
+ try {
+ session = repository.login();
+ } catch (RepositoryException re) {
+ throw new SlcException("Unable to log in Repository " + repository,
+ re);
+ }
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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.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.argeo.slc.jcr.SlcNames;
+import org.argeo.slc.jcr.SlcTypes;
+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 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) {
+
+ 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 {
+
+ 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 {
+
+ 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();
+ }
+ }
+
+ @Deprecated
+ public void setSession(Session session) {
+ this.session = session;
+ }
+
+ public void dispose() {
+ JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);
+ JcrUtils.logoutQuietly(session);
+ super.dispose();
+ }
+
+ public void setRepository(Repository repository) {
+ try {
+ session = repository.login();
+ } catch (RepositoryException re) {
+ throw new SlcException("Unable to log in Repository " + repository,
+ re);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2007-2012 Argeo GmbH\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package org.argeo.slc.client.ui.views;\r
+\r
+import java.text.DateFormat;\r
+import java.text.SimpleDateFormat;\r
+import java.util.ArrayList;\r
+import java.util.Calendar;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+import javax.jcr.Node;\r
+import javax.jcr.NodeIterator;\r
+import javax.jcr.Property;\r
+import javax.jcr.Repository;\r
+import javax.jcr.RepositoryException;\r
+import javax.jcr.Session;\r
+import javax.jcr.nodetype.NodeType;\r
+import javax.jcr.observation.Event;\r
+import javax.jcr.observation.EventListener;\r
+import javax.jcr.observation.ObservationManager;\r
+\r
+import org.argeo.ArgeoException;\r
+import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;\r
+import org.argeo.eclipse.ui.utils.CommandUtils;\r
+import org.argeo.jcr.JcrUtils;\r
+import org.argeo.slc.SlcException;\r
+import org.argeo.slc.client.ui.ClientUiPlugin;\r
+import org.argeo.slc.client.ui.SlcUiConstants;\r
+import org.argeo.slc.client.ui.commands.AddResultFolder;\r
+import org.argeo.slc.client.ui.commands.DeleteItems;\r
+import org.argeo.slc.client.ui.commands.RefreshJcrResultTreeView;\r
+import org.argeo.slc.client.ui.commands.RenameResultFolder;\r
+import org.argeo.slc.client.ui.commands.RenameResultNode;\r
+import org.argeo.slc.client.ui.editors.ProcessEditor;\r
+import org.argeo.slc.client.ui.editors.ProcessEditorInput;\r
+import org.argeo.slc.client.ui.model.ParentNodeFolder;\r
+import org.argeo.slc.client.ui.model.ResultFolder;\r
+import org.argeo.slc.client.ui.model.ResultItemsComparator;\r
+import org.argeo.slc.client.ui.model.ResultItemsComparer;\r
+import org.argeo.slc.client.ui.model.ResultParent;\r
+import org.argeo.slc.client.ui.model.ResultParentUtils;\r
+import org.argeo.slc.client.ui.model.SingleResultNode;\r
+import org.argeo.slc.client.ui.model.VirtualFolder;\r
+import org.argeo.slc.client.ui.providers.ResultTreeContentProvider;\r
+import org.argeo.slc.client.ui.providers.ResultTreeLabelProvider;\r
+import org.argeo.slc.jcr.SlcJcrResultUtils;\r
+import org.argeo.slc.jcr.SlcNames;\r
+import org.argeo.slc.jcr.SlcTypes;\r
+import org.eclipse.jface.action.IMenuListener;\r
+import org.eclipse.jface.action.IMenuManager;\r
+import org.eclipse.jface.action.MenuManager;\r
+import org.eclipse.jface.dialogs.MessageDialog;\r
+import org.eclipse.jface.viewers.ColumnLabelProvider;\r
+import org.eclipse.jface.viewers.DecoratingLabelProvider;\r
+import org.eclipse.jface.viewers.DoubleClickEvent;\r
+import org.eclipse.jface.viewers.IDoubleClickListener;\r
+import org.eclipse.jface.viewers.ILabelDecorator;\r
+import org.eclipse.jface.viewers.ISelectionChangedListener;\r
+import org.eclipse.jface.viewers.IStructuredContentProvider;\r
+import org.eclipse.jface.viewers.IStructuredSelection;\r
+import org.eclipse.jface.viewers.SelectionChangedEvent;\r
+import org.eclipse.jface.viewers.TableViewer;\r
+import org.eclipse.jface.viewers.TableViewerColumn;\r
+import org.eclipse.jface.viewers.TreePath;\r
+import org.eclipse.jface.viewers.TreeViewer;\r
+import org.eclipse.jface.viewers.Viewer;\r
+import org.eclipse.jface.viewers.ViewerDropAdapter;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.custom.SashForm;\r
+import org.eclipse.swt.dnd.DND;\r
+import org.eclipse.swt.dnd.DragSourceEvent;\r
+import org.eclipse.swt.dnd.DragSourceListener;\r
+import org.eclipse.swt.dnd.TextTransfer;\r
+import org.eclipse.swt.dnd.Transfer;\r
+import org.eclipse.swt.dnd.TransferData;\r
+import org.eclipse.swt.layout.FillLayout;\r
+import org.eclipse.swt.layout.GridData;\r
+import org.eclipse.swt.layout.GridLayout;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Display;\r
+import org.eclipse.swt.widgets.Menu;\r
+import org.eclipse.ui.ISharedImages;\r
+import org.eclipse.ui.IWorkbenchPage;\r
+import org.eclipse.ui.IWorkbenchWindow;\r
+import org.eclipse.ui.PlatformUI;\r
+import org.eclipse.ui.part.ViewPart;\r
+\r
+/** SLC generic JCR Result tree view. */\r
+public class JcrResultTreeView extends ViewPart {\r
+ public final static String ID = ClientUiPlugin.ID + ".jcrResultTreeView";\r
+\r
+ private final static DateFormat dateFormat = new SimpleDateFormat(\r
+ SlcUiConstants.DEFAULT_DISPLAY_DATE_TIME_FORMAT);\r
+\r
+ // private final static Log log =\r
+ // LogFactory.getLog(JcrResultTreeView.class);\r
+\r
+ /* DEPENDENCY INJECTION */\r
+ private Session session;\r
+\r
+ // This page widgets\r
+ private TreeViewer resultTreeViewer;\r
+ private TableViewer propertiesViewer;\r
+\r
+ private EventListener myResultsObserver = null;\r
+ private EventListener allResultsObserver = null;\r
+\r
+ // under My Results\r
+ private final static String[] observedNodeTypesUnderMyResult = {\r
+ SlcTypes.SLC_TEST_RESULT, SlcTypes.SLC_RESULT_FOLDER,\r
+ SlcTypes.SLC_MY_RESULT_ROOT_FOLDER };\r
+\r
+ private final static String[] observedNodeTypesUnderAllResults = {\r
+ SlcTypes.SLC_TEST_RESULT, NodeType.NT_UNSTRUCTURED };\r
+\r
+ private boolean isResultFolder = false;\r
+\r
+ /**\r
+ * To be overridden to adapt size of form and result frames.\r
+ */\r
+ protected int[] getWeights() {\r
+ return new int[] { 70, 30 };\r
+ }\r
+\r
+ @Override\r
+ public void createPartControl(Composite parent) {\r
+ parent.setLayout(new FillLayout());\r
+ // Main layout\r
+ SashForm sashForm = new SashForm(parent, SWT.VERTICAL);\r
+ sashForm.setSashWidth(4);\r
+ sashForm.setLayout(new FillLayout());\r
+\r
+ // Create the tree on top of the view\r
+ Composite top = new Composite(sashForm, SWT.NONE);\r
+ GridLayout gl = new GridLayout(1, false);\r
+ top.setLayout(gl);\r
+ resultTreeViewer = createResultsTreeViewer(top);\r
+\r
+ // Create the property viewer on the bottom\r
+ Composite bottom = new Composite(sashForm, SWT.NONE);\r
+ bottom.setLayout(new GridLayout(1, false));\r
+ propertiesViewer = createPropertiesViewer(bottom);\r
+\r
+ sashForm.setWeights(getWeights());\r
+\r
+ setOrderedInput(resultTreeViewer);\r
+\r
+ // Initialize observer\r
+ try {\r
+ ObservationManager observationManager = session.getWorkspace()\r
+ .getObservationManager();\r
+ myResultsObserver = new MyResultsObserver(resultTreeViewer\r
+ .getTree().getDisplay());\r
+ allResultsObserver = new AllResultsObserver(resultTreeViewer\r
+ .getTree().getDisplay());\r
+\r
+ // observe tree changes under MyResults\r
+ observationManager.addEventListener(myResultsObserver,\r
+ Event.NODE_ADDED | Event.NODE_REMOVED,\r
+ SlcJcrResultUtils.getMyResultsBasePath(session), true,\r
+ null, observedNodeTypesUnderMyResult, false);\r
+ // observe tree changes under All results\r
+ observationManager.addEventListener(allResultsObserver,\r
+ Event.NODE_ADDED | Event.NODE_REMOVED,\r
+ SlcJcrResultUtils.getSlcResultsBasePath(session), true,\r
+ null, observedNodeTypesUnderAllResults, false);\r
+ } catch (RepositoryException e) {\r
+ throw new SlcException("Cannot register listeners", e);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Override default behaviour so that default defined order remains\r
+ * unchanged on first level of the tree\r
+ */\r
+ private void setOrderedInput(TreeViewer viewer) {\r
+ // Add specific ordering\r
+ viewer.setInput(null);\r
+ viewer.setComparator(null);\r
+ viewer.setInput(initializeResultTree());\r
+ viewer.setComparator(new ResultItemsComparator());\r
+ }\r
+\r
+ // The main tree viewer\r
+ protected TreeViewer createResultsTreeViewer(Composite parent) {\r
+ int style = SWT.BORDER | SWT.MULTI;\r
+\r
+ TreeViewer viewer = new TreeViewer(parent, style);\r
+ viewer.getTree().setLayoutData(\r
+ new GridData(SWT.FILL, SWT.FILL, true, true));\r
+\r
+ viewer.setContentProvider(new ResultTreeContentProvider());\r
+\r
+ // Add label provider with label decorator\r
+ ResultTreeLabelProvider rtLblProvider = new ResultTreeLabelProvider();\r
+ ILabelDecorator decorator = ClientUiPlugin.getDefault().getWorkbench()\r
+ .getDecoratorManager().getLabelDecorator();\r
+ viewer.setLabelProvider(new DecoratingLabelProvider(rtLblProvider,\r
+ decorator));\r
+ viewer.addDoubleClickListener(new ViewDoubleClickListener());\r
+\r
+ // Override default behaviour to insure that 2 distincts results that\r
+ // have the same name will be correctly and distincly returned by\r
+ // corresponding TreeViewer.getSelection() method.\r
+ viewer.setComparer(new ResultItemsComparer());\r
+\r
+ // viewer.setLabelProvider(rtLblProvider);\r
+ getSite().setSelectionProvider(viewer);\r
+\r
+ // add drag & drop support\r
+ int operations = DND.DROP_COPY | DND.DROP_MOVE;\r
+ Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };\r
+ viewer.addDragSupport(operations, tt, new ViewDragListener());\r
+ viewer.addDropSupport(operations, tt, new ViewDropListener(viewer));\r
+\r
+ // add context menu\r
+ MenuManager menuManager = new MenuManager();\r
+ Menu menu = menuManager.createContextMenu(viewer.getTree());\r
+ menuManager.addMenuListener(new IMenuListener() {\r
+ public void menuAboutToShow(IMenuManager manager) {\r
+ contextMenuAboutToShow(manager);\r
+ }\r
+ });\r
+ viewer.getTree().setMenu(menu);\r
+ menuManager.setRemoveAllWhenShown(true);\r
+\r
+ getSite().registerContextMenu(menuManager, viewer);\r
+\r
+ // add change listener to display TestResult information in the property\r
+ // viewer\r
+ viewer.addSelectionChangedListener(new MySelectionChangedListener());\r
+ return viewer;\r
+ }\r
+\r
+ // Detailed property viewer\r
+ protected TableViewer createPropertiesViewer(Composite parent) {\r
+ propertiesViewer = new TableViewer(parent);\r
+ propertiesViewer.getTable().setLayoutData(\r
+ new GridData(SWT.FILL, SWT.FILL, true, true));\r
+ propertiesViewer.getTable().setHeaderVisible(true);\r
+ propertiesViewer.setContentProvider(new PropertiesContentProvider());\r
+ TableViewerColumn col = new TableViewerColumn(propertiesViewer,\r
+ SWT.NONE);\r
+ col.getColumn().setText("Name");\r
+ col.getColumn().setWidth(100);\r
+ col.setLabelProvider(new ColumnLabelProvider() {\r
+ public String getText(Object element) {\r
+ try {\r
+ String name = ((Property) element).getName();\r
+ String value = null;\r
+ if (SlcNames.SLC_TEST_CASE.equals(name))\r
+ value = "Test case";\r
+ else if (SlcNames.SLC_COMPLETED.equals(name))\r
+ value = "Completed on";\r
+ else if (SlcNames.SLC_SUCCESS.equals(name))\r
+ value = "Status";\r
+ else if (SlcNames.SLC_MESSAGE.equals(name))\r
+ value = "Message";\r
+ else if (SlcNames.SLC_ERROR_MESSAGE.equals(name))\r
+ value = "Error";\r
+ return value;\r
+ } catch (RepositoryException e) {\r
+ throw new ArgeoException(\r
+ "Unexpected exception in label provider", e);\r
+ }\r
+ }\r
+ });\r
+ col = new TableViewerColumn(propertiesViewer, SWT.NONE);\r
+ col.getColumn().setText("Value");\r
+ col.getColumn().setWidth(200);\r
+ col.setLabelProvider(new ColumnLabelProvider() {\r
+ public String getText(Object element) {\r
+ try {\r
+ Property property = (Property) element;\r
+ String name = property.getName();\r
+ String value = null;\r
+\r
+ if (SlcNames.SLC_TEST_CASE.equals(name)\r
+ || SlcNames.SLC_ERROR_MESSAGE.equals(name)\r
+ || SlcNames.SLC_MESSAGE.equals(name))\r
+ value = property.getValue().getString();\r
+ else if (SlcNames.SLC_COMPLETED.equals(name)) {\r
+ Calendar date = property.getValue().getDate();\r
+ value = dateFormat.format(date.getTime());\r
+ } else if (SlcNames.SLC_SUCCESS.equals(name)) {\r
+ if (property.getValue().getBoolean())\r
+ value = "PASSED";\r
+ else {\r
+ if (property.getParent().hasProperty(\r
+ SlcNames.SLC_ERROR_MESSAGE))\r
+ value = "ERROR";\r
+ else\r
+ value = "FAILED";\r
+ }\r
+ }\r
+ return value;\r
+ } catch (RepositoryException e) {\r
+ throw new ArgeoException(\r
+ "Unexpected exception in label provider", e);\r
+ }\r
+ }\r
+ });\r
+ propertiesViewer.setInput(getViewSite());\r
+ return propertiesViewer;\r
+ }\r
+\r
+ /**\r
+ * Override to provide specific behaviour. Typically to enable the display\r
+ * of a result file.\r
+ * \r
+ * @param evt\r
+ */\r
+ protected void processDoubleClick(DoubleClickEvent evt) {\r
+ Object obj = ((IStructuredSelection) evt.getSelection())\r
+ .getFirstElement();\r
+ try {\r
+ if (obj instanceof SingleResultNode) {\r
+ SingleResultNode srNode = (SingleResultNode) obj;\r
+ Node node = srNode.getNode();\r
+ // FIXME: open a default result editor\r
+ if (node.isNodeType(SlcTypes.SLC_PROCESS)) {\r
+ IWorkbenchPage activePage = PlatformUI.getWorkbench()\r
+ .getActiveWorkbenchWindow().getActivePage();\r
+ activePage.openEditor(\r
+ new ProcessEditorInput(node.getPath()),\r
+ ProcessEditor.ID);\r
+ }\r
+ }\r
+ } catch (Exception e) {\r
+ throw new SlcException("Cannot open " + obj, e);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void setFocus() {\r
+ }\r
+\r
+ /**\r
+ * refreshes the passed resultParent and its corresponding subtree. It\r
+ * refreshes the whole viewer if null is passed.\r
+ * \r
+ * @param ResultParent\r
+ * \r
+ */\r
+ public void refresh(ResultParent resultParent) {\r
+ if (resultParent == null) {\r
+ if (!resultTreeViewer.getTree().isDisposed()) {\r
+ TreePath[] tps = resultTreeViewer.getExpandedTreePaths();\r
+ setOrderedInput(resultTreeViewer);\r
+ resultTreeViewer.setExpandedTreePaths(tps);\r
+ } else\r
+ setOrderedInput(resultTreeViewer);\r
+ } else {\r
+ if (resultParent instanceof ParentNodeFolder) {\r
+ ParentNodeFolder currFolder = (ParentNodeFolder) resultParent;\r
+ jcrRefresh(currFolder.getNode());\r
+ currFolder.forceFullRefresh();\r
+ }\r
+ // FIXME: specific refresh does not work\r
+ // resultTreeViewer.refresh(resultParent, true);\r
+ refresh(null);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * refreshes the passed node and its corresponding subtree.\r
+ * \r
+ * @param node\r
+ * cannot be null\r
+ * \r
+ */\r
+ public boolean jcrRefresh(Node node) {\r
+ // if (log.isDebugEnabled())\r
+ // log.debug(" JCR refreshing " + node + "...");\r
+ // Thread.dumpStack();\r
+ boolean isPassed = true;\r
+ try {\r
+ if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {\r
+ isPassed = node.getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
+ .getProperty(SlcNames.SLC_SUCCESS).getBoolean();\r
+ } else if (node.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {\r
+ NodeIterator ni = node.getNodes();\r
+ while (ni.hasNext()) {\r
+ Node currChild = ni.nextNode();\r
+ isPassed = isPassed & jcrRefresh(currChild);\r
+ }\r
+ if (isPassed != node.getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
+ .getProperty(SlcNames.SLC_SUCCESS).getBoolean()) {\r
+ node.getNode(SlcNames.SLC_AGGREGATED_STATUS).setProperty(\r
+ SlcNames.SLC_SUCCESS, isPassed);\r
+ node.getSession().save();\r
+ return isPassed;\r
+ }\r
+ } else\r
+ ; // do nothing\r
+ } catch (RepositoryException e) {\r
+ throw new SlcException("Cannot register listeners", e);\r
+ }\r
+ return isPassed;\r
+ }\r
+\r
+ private ResultParent[] initializeResultTree() {\r
+ try {\r
+ // Force initialization of the tree structure if needed\r
+ SlcJcrResultUtils.getSlcResultsParentNode(session);\r
+ SlcJcrResultUtils.getMyResultParentNode(session);\r
+ // Remove yesterday and last 7 days virtual folders\r
+ // ResultParent[] roots = new ResultParent[5];\r
+ ResultParent[] roots = new ResultParent[3];\r
+\r
+ // My results\r
+ roots[0] = new ParentNodeFolder(null,\r
+ SlcJcrResultUtils.getMyResultParentNode(session),\r
+ SlcUiConstants.DEFAULT_MY_RESULTS_FOLDER_LABEL);\r
+\r
+ // today\r
+ Calendar cal = Calendar.getInstance();\r
+ String relPath = JcrUtils.dateAsPath(cal);\r
+ List<String> datePathes = new ArrayList<String>();\r
+ datePathes.add(relPath);\r
+ roots[1] = new VirtualFolder(null,\r
+ ResultParentUtils.getResultsForDates(session, datePathes),\r
+ "Today");\r
+\r
+ // // Yesterday\r
+ // cal = Calendar.getInstance();\r
+ // cal.add(Calendar.DAY_OF_YEAR, -1);\r
+ // relPath = JcrUtils.dateAsPath(cal);\r
+ // datePathes = new ArrayList<String>();\r
+ // datePathes.add(relPath);\r
+ // roots[2] = new VirtualFolder(null,\r
+ // ResultParentUtils.getResultsForDates(session, datePathes),\r
+ // "Yesterday");\r
+ // // Last 7 days\r
+ //\r
+ // cal = Calendar.getInstance();\r
+ // datePathes = new ArrayList<String>();\r
+ //\r
+ // for (int i = 0; i < 7; i++) {\r
+ // cal.add(Calendar.DAY_OF_YEAR, -i);\r
+ // relPath = JcrUtils.dateAsPath(cal);\r
+ // datePathes.add(relPath);\r
+ // }\r
+ // roots[3] = new VirtualFolder(null,\r
+ // ResultParentUtils.getResultsForDates(session, datePathes),\r
+ // "Last 7 days");\r
+\r
+ // All results\r
+ Node otherResultsPar = session.getNode(SlcJcrResultUtils\r
+ .getSlcResultsBasePath(session));\r
+ // roots[4] = new ParentNodeFolder(null, otherResultsPar,\r
+ // "All results");\r
+ roots[2] = new ParentNodeFolder(null, otherResultsPar,\r
+ "All results");\r
+ return roots;\r
+ } catch (RepositoryException re) {\r
+ throw new ArgeoException(\r
+ "Unexpected error while initializing ResultTree.", re);\r
+ }\r
+ }\r
+\r
+ // Manage context menu\r
+ /**\r
+ * Defines the commands that will pop up in the context menu.\r
+ **/\r
+ protected void contextMenuAboutToShow(IMenuManager menuManager) {\r
+ IWorkbenchWindow window = ClientUiPlugin.getDefault().getWorkbench()\r
+ .getActiveWorkbenchWindow();\r
+\r
+ IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
+ .getSelection();\r
+ boolean canAddSubfolder = false;\r
+ boolean canRenamefolder = false;\r
+ boolean isSingleResultNode = false;\r
+ boolean isUnderMyResult = false;\r
+ boolean validMultipleDelete = false;\r
+ try {\r
+\r
+ // Building conditions\r
+ if (selection.size() == 1) {\r
+ Object obj = selection.getFirstElement();\r
+ if (obj instanceof SingleResultNode)\r
+ isSingleResultNode = true;\r
+ else if (obj instanceof ParentNodeFolder) {\r
+ Node cNode = ((ParentNodeFolder) obj).getNode();\r
+ if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {\r
+ canAddSubfolder = true;\r
+ canRenamefolder = true;\r
+ isUnderMyResult = true;\r
+ } else if (cNode\r
+ .isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER)) {\r
+ canAddSubfolder = true;\r
+ }\r
+ }\r
+ } else {\r
+ @SuppressWarnings("rawtypes")\r
+ Iterator it = selection.iterator();\r
+ multicheck: while (it.hasNext()) {\r
+ validMultipleDelete = true;\r
+ Object obj = it.next();\r
+ if (obj instanceof SingleResultNode)\r
+ continue multicheck;\r
+ else if (obj instanceof ParentNodeFolder) {\r
+ Node cNode = ((ParentNodeFolder) obj).getNode();\r
+ if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER))\r
+ continue multicheck;\r
+ else {\r
+ validMultipleDelete = false;\r
+ break multicheck;\r
+ }\r
+ } else {\r
+ validMultipleDelete = false;\r
+ break multicheck;\r
+ }\r
+ }\r
+ }\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException(\r
+ "unexpected error while building condition for context menu",\r
+ re);\r
+ }\r
+\r
+ // Effective Refresh\r
+ CommandUtils.refreshCommand(menuManager, window,\r
+ RefreshJcrResultTreeView.ID,\r
+ RefreshJcrResultTreeView.DEFAULT_LABEL,\r
+ RefreshJcrResultTreeView.DEFAULT_IMG_DESCRIPTOR, true);\r
+\r
+ CommandUtils.refreshCommand(menuManager, window, DeleteItems.ID,\r
+ DeleteItems.DEFAULT_LABEL, DeleteItems.DEFAULT_IMG_DESCRIPTOR,\r
+ isUnderMyResult || isSingleResultNode || validMultipleDelete);\r
+\r
+ CommandUtils.refreshCommand(menuManager, window, AddResultFolder.ID,\r
+ AddResultFolder.DEFAULT_LABEL,\r
+ ClientUiPlugin.getDefault().getWorkbench().getSharedImages()\r
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD),\r
+ canAddSubfolder);\r
+\r
+ CommandUtils.refreshCommand(menuManager, window, RenameResultFolder.ID,\r
+ RenameResultFolder.DEFAULT_LABEL,\r
+ RenameResultFolder.DEFAULT_IMG_DESCRIPTOR, canRenamefolder);\r
+\r
+ // Command removed for the time being.\r
+ CommandUtils.refreshCommand(menuManager, window, RenameResultNode.ID,\r
+ RenameResultNode.DEFAULT_LABEL,\r
+ RenameResultNode.DEFAULT_IMG_DESCRIPTOR, false);\r
+\r
+ // Test to be removed\r
+ // If you use this pattern, do not forget to call\r
+ // menuManager.setRemoveAllWhenShown(true);\r
+ // when creating the menuManager\r
+\r
+ // menuManager.add(new Action("Test") {\r
+ // public void run() {\r
+ // log.debug("do something");\r
+ // }\r
+ // });\r
+ }\r
+\r
+ /* INNER CLASSES */\r
+ class ViewDragListener implements DragSourceListener {\r
+\r
+ public void dragStart(DragSourceEvent event) {\r
+ // Check if the drag action should start.\r
+ IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
+ .getSelection();\r
+ boolean doIt = false;\r
+\r
+ // FIXME clean this code.\r
+ try {\r
+ if (selection.size() == 1) {\r
+ Object obj = selection.getFirstElement();\r
+ if (obj instanceof ResultFolder) {\r
+ Node tNode = ((ResultFolder) obj).getNode();\r
+ if (tNode.getPrimaryNodeType().isNodeType(\r
+ SlcTypes.SLC_RESULT_FOLDER)) {\r
+ doIt = true;\r
+ isResultFolder = true;\r
+ }\r
+ } else\r
+ isResultFolder = false;\r
+ } else\r
+ isResultFolder = false;\r
+\r
+ if (!isResultFolder) {\r
+ @SuppressWarnings("rawtypes")\r
+ Iterator it = selection.iterator();\r
+ while (it.hasNext()) {\r
+ Object obj = it.next();\r
+ if (obj instanceof SingleResultNode) {\r
+ Node tNode = ((SingleResultNode) obj).getNode();\r
+ if (tNode.getPrimaryNodeType().isNodeType(\r
+ SlcTypes.SLC_TEST_RESULT)) {\r
+ doIt = true;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException(\r
+ "unexpected error while validating drag source", re);\r
+ }\r
+ event.doit = doIt;\r
+ }\r
+\r
+ public void dragSetData(DragSourceEvent event) {\r
+ IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
+ .getSelection();\r
+\r
+ try {\r
+ // specific case of a result folder\r
+ if (isResultFolder) {\r
+ Object obj = selection.getFirstElement();\r
+ event.data = ((ResultFolder) obj).getNode().getIdentifier();\r
+ } else {\r
+ @SuppressWarnings("rawtypes")\r
+ Iterator it = selection.iterator();\r
+ StringBuilder nodes = new StringBuilder();\r
+ while (it.hasNext()) {\r
+ Object obj = it.next();\r
+ if (obj instanceof SingleResultNode) {\r
+ Node tNode = ((SingleResultNode) obj).getNode();\r
+ if (tNode.getPrimaryNodeType().isNodeType(\r
+ SlcTypes.SLC_TEST_RESULT)) {\r
+ nodes.append(tNode.getIdentifier()).append(";");\r
+ }\r
+ }\r
+ }\r
+ event.data = nodes.toString();\r
+ }\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException("unexpected error while setting data",\r
+ re);\r
+ }\r
+ }\r
+\r
+ public void dragFinished(DragSourceEvent event) {\r
+ // refresh is done via observer\r
+ }\r
+ }\r
+\r
+ // Implementation of the Drop Listener\r
+ protected class ViewDropListener extends ViewerDropAdapter {\r
+ private Node targetParentNode = null;\r
+\r
+ public ViewDropListener(Viewer viewer) {\r
+ super(viewer);\r
+ }\r
+\r
+ @Override\r
+ public boolean validateDrop(Object target, int operation,\r
+ TransferData transferType) {\r
+ boolean validDrop = false;\r
+ try {\r
+ // We can only drop under myResults\r
+ Node tpNode = null;\r
+ if (target instanceof SingleResultNode) {\r
+ Node currNode = ((SingleResultNode) target).getNode();\r
+ String pPath = currNode.getParent().getPath();\r
+ if (pPath.startsWith(SlcJcrResultUtils\r
+ .getMyResultsBasePath(session)))\r
+ tpNode = currNode.getParent();\r
+ } else if (target instanceof ResultFolder) {\r
+ tpNode = ((ResultFolder) target).getNode();\r
+ } else if (target instanceof ParentNodeFolder) {\r
+ Node node = ((ParentNodeFolder) target).getNode();\r
+ if (node.isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER))\r
+ tpNode = ((ParentNodeFolder) target).getNode();\r
+ }\r
+\r
+ if (tpNode != null) {\r
+ targetParentNode = tpNode;\r
+ validDrop = true;\r
+ }\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException(\r
+ "unexpected error while validating drop target", re);\r
+ }\r
+ return validDrop;\r
+ }\r
+\r
+ @Override\r
+ public boolean performDrop(Object data) {\r
+ // clear selection to prevent unwanted scrolling of the UI\r
+ resultTreeViewer.setSelection(null);\r
+ try {\r
+ if (isResultFolder) {\r
+ // Sanity check : we cannot move a folder to one of its sub\r
+ // folder or neither move an object in the same parent\r
+ // folder\r
+ Node source = session.getNodeByIdentifier((String) data);\r
+ if (targetParentNode.getPath().startsWith(source.getPath())\r
+ || source.getParent().getPath()\r
+ .equals(targetParentNode.getPath()))\r
+ return false;\r
+\r
+ // Move\r
+ String sourcePath = source.getPath();\r
+ String destPath = targetParentNode.getPath() + "/"\r
+ + source.getName();\r
+ session.move(sourcePath, destPath);\r
+ // Update passed status of the parent source Node\r
+ ResultParentUtils.updatePassedStatus(\r
+ session.getNode(JcrUtils.parentPath(sourcePath)),\r
+ true);\r
+ // Node target = session.getNode(destPath);\r
+ session.save();\r
+ return true;\r
+ }\r
+\r
+ String[] datas = ((String) data).split(";");\r
+ nodesToCopy: for (String id : datas) {\r
+\r
+ Node source = session.getNodeByIdentifier(id);\r
+ String name;\r
+ if (source.hasProperty(Property.JCR_TITLE))\r
+ name = source.getProperty(Property.JCR_TITLE)\r
+ .getString();\r
+ else if (source.hasProperty(SlcNames.SLC_TEST_CASE))\r
+ name = source.getProperty(SlcNames.SLC_TEST_CASE)\r
+ .getString();\r
+ else\r
+ name = source.getName();\r
+\r
+ // Check if another copy of the same test instance already\r
+ // exists at target\r
+ NodeIterator ni = targetParentNode.getNodes();\r
+ String slcUid = source.getProperty(SlcNames.SLC_UUID)\r
+ .getString();\r
+ while (ni.hasNext()) {\r
+ Node curr = ni.nextNode();\r
+ if (curr.hasProperty(SlcNames.SLC_UUID)\r
+ && slcUid.equals(curr.getProperty(\r
+ SlcNames.SLC_UUID).getString())) {\r
+ MessageDialog\r
+ .openWarning(\r
+ PlatformUI.getWorkbench()\r
+ .getDisplay()\r
+ .getActiveShell(),\r
+ "Duplicated instance.",\r
+ "An instance of the same test case ("\r
+ + name\r
+ + ") exists at destination.\n "\r
+ + "This item will not be neither copied nor moved.");\r
+ continue nodesToCopy;\r
+\r
+ }\r
+ }\r
+\r
+ Node target;\r
+ boolean passedStatus = false;\r
+ if (source.hasNode(SlcNames.SLC_AGGREGATED_STATUS))\r
+ passedStatus = source\r
+ .getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
+ .getProperty(SlcNames.SLC_SUCCESS).getBoolean();\r
+\r
+ boolean isActionUnderMyResult = source.getPath()\r
+ .startsWith(\r
+ SlcJcrResultUtils\r
+ .getMyResultsBasePath(session));\r
+\r
+ if (!isActionUnderMyResult) {// Copy\r
+ target = targetParentNode.addNode(source.getName(),\r
+ source.getPrimaryNodeType().getName());\r
+ JcrUtils.copy(source, target);\r
+ } else {// move\r
+ String sourcePath = source.getPath();\r
+ String destPath = targetParentNode.getPath() + "/"\r
+ + name;\r
+ session.move(sourcePath, destPath);\r
+ // Update passed status of the parent source Node\r
+ ResultParentUtils\r
+ .updatePassedStatus(session.getNode(JcrUtils\r
+ .parentPath(sourcePath)), true);\r
+ target = session.getNode(destPath);\r
+\r
+ }\r
+ if (!target.isNodeType(NodeType.MIX_TITLE))\r
+ target.addMixin(NodeType.MIX_TITLE);\r
+ target.setProperty(Property.JCR_TITLE, name);\r
+ ResultParentUtils.updatePassedStatus(target.getParent(),\r
+ passedStatus);\r
+ session.save();\r
+ }\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException(\r
+ "unexpected error while copying dropped node", re);\r
+\r
+ }\r
+ return true;\r
+ }\r
+ }\r
+\r
+ class MyResultsObserver extends AsyncUiEventListener {\r
+\r
+ public MyResultsObserver(Display display) {\r
+ super(display);\r
+ }\r
+\r
+ @Override\r
+ protected Boolean willProcessInUiThread(List<Event> events)\r
+ throws RepositoryException {\r
+ // unfiltered for the time being\r
+ return true;\r
+ }\r
+\r
+ protected void onEventInUiThread(List<Event> events)\r
+ throws RepositoryException {\r
+ List<Node> nodesToRefresh = new ArrayList<Node>();\r
+\r
+ for (Event event : events) {\r
+ String parPath = JcrUtils.parentPath(event.getPath());\r
+ if (session.nodeExists(parPath)) {\r
+ Node node = session.getNode(parPath);\r
+ if (!nodesToRefresh.contains(node)) {\r
+ nodesToRefresh.add(node);\r
+ }\r
+ }\r
+ }\r
+\r
+ // Update check nodes\r
+ for (Node node : nodesToRefresh)\r
+ jcrRefresh(node);\r
+ refresh(null);\r
+ }\r
+ }\r
+\r
+ class AllResultsObserver extends AsyncUiEventListener {\r
+\r
+ public AllResultsObserver(Display display) {\r
+ super(display);\r
+ }\r
+\r
+ @Override\r
+ protected Boolean willProcessInUiThread(List<Event> events)\r
+ throws RepositoryException {\r
+ // unfiltered for the time being\r
+ return true;\r
+ }\r
+\r
+ protected void onEventInUiThread(List<Event> events)\r
+ throws RepositoryException {\r
+ refresh(null);\r
+ // if (lastSelectedSourceElementParent != null)\r
+ // refresh(lastSelectedSourceElementParent);\r
+ }\r
+ }\r
+\r
+ class PropertiesContentProvider implements IStructuredContentProvider {\r
+\r
+ public void dispose() {\r
+ }\r
+\r
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {\r
+ }\r
+\r
+ public Object[] getElements(Object inputElement) {\r
+ try {\r
+ if (inputElement instanceof Node) {\r
+ Node node = (Node) inputElement;\r
+ if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {\r
+ List<Property> props = new ArrayList<Property>();\r
+ if (node.hasProperty(SlcNames.SLC_TEST_CASE))\r
+ props.add(node.getProperty(SlcNames.SLC_TEST_CASE));\r
+ if (node.hasProperty(SlcNames.SLC_COMPLETED))\r
+ props.add(node.getProperty(SlcNames.SLC_COMPLETED));\r
+ if (node.hasNode(SlcNames.SLC_AGGREGATED_STATUS)) {\r
+ Node status = node\r
+ .getNode(SlcNames.SLC_AGGREGATED_STATUS);\r
+ props.add(status.getProperty(SlcNames.SLC_SUCCESS));\r
+ if (status.hasProperty(SlcNames.SLC_MESSAGE))\r
+ props.add(status\r
+ .getProperty(SlcNames.SLC_MESSAGE));\r
+ if (status.hasProperty(SlcNames.SLC_ERROR_MESSAGE))\r
+ props.add(status\r
+ .getProperty(SlcNames.SLC_ERROR_MESSAGE));\r
+ }\r
+ return props.toArray();\r
+ }\r
+ }\r
+ return new Object[] {};\r
+\r
+ } catch (RepositoryException e) {\r
+ throw new ArgeoException("Cannot get element for "\r
+ + inputElement, e);\r
+ }\r
+ }\r
+ }\r
+\r
+ class MySelectionChangedListener implements ISelectionChangedListener {\r
+\r
+ public void selectionChanged(SelectionChangedEvent event) {\r
+ if (!event.getSelection().isEmpty()) {\r
+ IStructuredSelection sel = (IStructuredSelection) event\r
+ .getSelection();\r
+ ResultParent firstItem = (ResultParent) sel.getFirstElement();\r
+ if (firstItem instanceof SingleResultNode)\r
+ propertiesViewer.setInput(((SingleResultNode) firstItem)\r
+ .getNode());\r
+ else\r
+ propertiesViewer.setInput(null);\r
+ // update cache for Drag & drop\r
+ // lastSelectedTargetElement = firstItem;\r
+ // lastSelectedSourceElement = firstItem;\r
+ // lastSelectedSourceElementParent = (ResultParent) firstItem\r
+ // .getParent();\r
+ // String pPath = "";\r
+ // try {\r
+ //\r
+ // if (firstItem instanceof ParentNodeFolder)\r
+ // pPath = ((ParentNodeFolder) firstItem).getNode()\r
+ // .getPath();\r
+ // else if (firstItem instanceof SingleResultNode)\r
+ // pPath = ((SingleResultNode) firstItem).getNode()\r
+ // .getPath();\r
+ // } catch (RepositoryException e) {\r
+ // throw new SlcException(\r
+ // "Unexpected error while checking parent UI tree", e);\r
+ // }\r
+ // if ((pPath.startsWith(SlcJcrResultUtils\r
+ // .getMyResultsBasePath(session))))\r
+ // isActionUnderMyResult = true;\r
+ // else\r
+ // isActionUnderMyResult = false;\r
+ }\r
+ }\r
+ }\r
+\r
+ class ViewDoubleClickListener implements IDoubleClickListener {\r
+ public void doubleClick(DoubleClickEvent evt) {\r
+ processDoubleClick(evt);\r
+ }\r
+\r
+ }\r
+\r
+ /* DEPENDENCY INJECTION */\r
+ @Deprecated\r
+ public void setSession(Session session) {\r
+ this.session = session;\r
+ }\r
+\r
+ public void dispose() {\r
+ // JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);\r
+ JcrUtils.logoutQuietly(session);\r
+ super.dispose();\r
+ }\r
+\r
+ public void setRepository(Repository repository) {\r
+ try {\r
+ session = repository.login();\r
+ } catch (RepositoryException re) {\r
+ throw new SlcException("Unable to log in Repository " + repository,\r
+ re);\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.slc.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"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src/main/java"/>
- <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="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
-#Thu Apr 14 17:49:18 CEST 2011
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+++ /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 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 RAP</beans:description>\r
-\r
- <reference id="nodeRepository" interface="javax.jcr.Repository"\r
- filter="(argeo.jcr.repository.alias=node)" />\r
-\r
- <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
- <reference id="keyring" interface="org.argeo.security.crypto.CryptoKeyring" />\r
-\r
-</beans:beans>
\ 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
- parameter="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>plugins</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.rap</artifactId>
- <name>SLC Client RAP</name>
- <packaging>jar</packaging>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.argeo.slc.client.rap.SlcRapPlugin</Bundle-Activator>
- <Require-Bundle>org.eclipse.rap.ui;resolution:=optional</Require-Bundle>
- <Import-Package>
- javax.jcr.nodetype,
- javax.servlet,
- javax.servlet.http,
- org.argeo.eclipse.spring,
- org.argeo.slc.repo.core,
- *
- </Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <!-- SLC -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.repo</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
-
- <!-- Argeo common distribution for RAP projects -->
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.dep.rap</artifactId>
- <version>${version.argeo-commons}</version>
- <exclusions>
- <exclusion>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>org.mortbay.jetty.server</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>org.mortbay.jetty.server.util</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.eclipse.equinox</groupId>
- <artifactId>org.eclipse.equinox.http.jetty</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <!-- Argeo common distribution for Secured UI -->
- <dependency>
- <groupId>org.argeo.commons.security</groupId>
- <artifactId>org.argeo.security.ui.rap</artifactId>
- <version>${version.argeo-commons}</version>
- </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.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.eclipse.rwt.RWT;
-import org.eclipse.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() 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.rap;
-
-import org.argeo.security.ui.rap.RapWindowAdvisor;
-import org.argeo.security.ui.rap.RapWorkbenchAdvisor;
-import org.argeo.security.ui.rap.SecureEntryPoint;
-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 SecureEntryPoint {
-
- @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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.client.rap.SlcRapPlugin;
-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.rwt.RWT;
-import org.eclipse.rwt.service.IServiceHandler;
-import org.eclipse.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);
- 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("?");
- 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/main/java"/>
- <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
-<?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
-#Wed Dec 08 08:27:02 CET 2010
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+++ /dev/null
-#Wed Dec 08 08:27:02 CET 2010
-eclipse.preferences.version=1
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /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="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </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="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <bean id="normalizeWorkspace"
- class="org.argeo.slc.client.ui.dist.commands.NormalizeWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </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="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <bean id="copyWorkspace" class="org.argeo.slc.client.ui.dist.commands.CopyWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </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="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </bean>
-
- <bean id="deleteWorkspace" class="org.argeo.slc.client.ui.dist.commands.DeleteWorkspace">
- <property name="repositoryFactory" ref="repositoryFactory" />
- <property name="nodeRepository" ref="nodeRepository" />
- <property name="keyring" ref="keyring" />
- </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="org.argeo.slc.client.ui.dist.genericJcrQueryEditor"
- class="org.argeo.eclipse.ui.jcr.editors.GenericJcrQueryEditor" scope="prototype">
- <property name="session" ref="slcSession" />
- </bean>
-
- <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>
+++ /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="slcSession" class="org.argeo.jcr.spring.ThreadBoundSession">
- <property name="repository" ref="javaRepository" />
- <property name="workspace" value="org.argeo.tp-1.3.1" />
- </bean>
-
- <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>
+++ /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="(argeo.jcr.repository.alias=java)" />\r
-\r
- <reference id="repositoryFactory" interface="javax.jcr.RepositoryFactory" />\r
- <reference id="keyring" interface="org.argeo.security.crypto.CryptoKeyring" />\r
-\r
- <reference id="nodeRepository" interface="javax.jcr.Repository"\r
- filter="(argeo.jcr.repository.alias=node)" />\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>
+++ /dev/null
-source.. = src/main/java/
-output.. = target/classes/
-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>plugins</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.ui.dist</artifactId>
- <name>SLC Client UI Distribution</name>
- <packaging>jar</packaging>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.argeo.slc.client.ui.dist.DistPlugin</Bundle-Activator>
- <Require-Bundle>
- org.eclipse.ui;resolution:=optional,
- org.eclipse.rap.ui;resolution:=optional,
- org.eclipse.core.runtime;resolution:=optional,
- org.eclipse.rap.ui.workbench;resolution:=optional
- </Require-Bundle>
- <Import-Package>
- org.argeo.eclipse.spring,
- javax.jcr.nodetype,
- javax.jcr.security,
- aQute.lib.*;resolution:=optional,
- org.argeo.slc.client.ui.specific,
- *
- </Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
-
- <!-- Single sourcing - we build against RCP -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.client.rcp</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- Commons UI -->
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui.jcr</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui.rcp</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- SLC repo -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.specs</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.repo</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.server.repo</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
-
- <dependency>
- <groupId>org.argeo.tp</groupId>
- <artifactId>biz.aQute.bndlib</artifactId>
- </dependency>
-
- <!-- Argeo Base dependencies -->
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.util</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- </dependencies>
-</project>
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist;
-
-import org.argeo.slc.jcr.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist;
-
-public class DistLabels {
-
- public static String getLabel(String jcrName){
- String label = null;
-
-
- return label;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-public class DistPlugin extends AbstractUIPlugin {
- public final static String 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(ID, path);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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;
-
-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;
-import org.springframework.security.Authentication;
-import org.springframework.security.context.SecurityContextHolder;
-
-/**
- * Propagate authentication to an eclipse job. Typically to execute a privileged
- * action outside the UI thread
- */
-public abstract class PrivilegedJob extends Job {
-
- private final Authentication authentication;
- private Subject subject;
-
- public PrivilegedJob(String jobName) {
- super(jobName);
- authentication = SecurityContextHolder.getContext().getAuthentication();
- subject = Subject.getSubject(AccessController.getContext());
- }
-
- @Override
- protected IStatus run(final IProgressMonitor progressMonitor) {
- PrivilegedAction<IStatus> privilegedAction = new PrivilegedAction<IStatus>() {
- public IStatus run() {
- SecurityContextHolder.getContext().setAuthentication(
- authentication);
- return doRun(progressMonitor);
- }
- };
- return Subject.doAs(subject, privilegedAction);
- }
-
- /** Implement here what should be executed with default context authentication*/
- protected abstract IStatus doRun(IProgressMonitor progressMonitor);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.lib.osgi.Builder;
-import aQute.lib.osgi.Constants;
-import aQute.lib.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-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.PrivilegedJob;
-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 Log log = LogFactory
- .getLog(CopyLocalJavaWorkspace.class);
-
- public final static String ID = DistPlugin.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();
-
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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 ArgeoException(
- "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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-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.PrivilegedJob;
-import org.argeo.slc.client.ui.dist.utils.CommandHelpers;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(CopyWorkspace.class);
-
- public final static String ID = DistPlugin.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();
-
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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 ArgeoException(
- "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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.commands;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.eclipse.ui.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 Log log = LogFactory
- .getLog(CreateLocalJavaWorkspace.class);
-
- // Exposes commands meta-info
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.eclipse.ui.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.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(CreateWorkspace.class);
-
- // Exposes commands meta-info
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.commands;
-
-import java.util.Iterator;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.ArgeoException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.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 ArgeoException(
- "Unexpected error while deleting artifacts.", re);
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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;
-
-/**
- * Utilitary command used to enable sub menus in various toolbars. Does nothing
- */
-public class DoNothing extends AbstractHandler {
- public final static String ID = DistPlugin.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.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.argeo.slc.repo.RepoSync;
-import org.argeo.util.security.Keyring;
-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 {@link RepoSync} as an Eclipse command. Open a wizard that enable
- * definition of the fetch process parameters
- */
-public class Fetch extends AbstractHandler {
- // private final static Log log = LogFactory.getLog(Fetch.class);
-
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-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.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.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 ArgeoException("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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-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.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(MergeWorkspaces.class);
-
- public final static String ID = DistPlugin.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...");
-
- ArgeoMonitor monitor = new EclipseArgeoMonitor(eclipseMonitor);
- eclipseMonitor
- .beginTask("Copy files", expectedCount.intValue());
-
- Long count = JcrUtils.copyFiles(sourceSession.getRootNode(),
- targetSession.getRootNode(), true, monitor);
-
- 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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.NameVersion;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.aether.AetherUtils;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.ArtifactIndexer;
-import org.argeo.slc.repo.JarFileIndexer;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-import org.argeo.slc.repo.osgi.NormalizeGroup;
-import org.argeo.util.security.Keyring;
-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;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/** Legacy - Make sure than Maven and OSGi metadata are consistent */
-public class NormalizeDistribution extends AbstractHandler implements SlcNames {
- private final static Log log = LogFactory
- .getLog(NormalizeDistribution.class);
-
- public final static String ID = DistPlugin.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 {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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.ID,
- "Cannot normalize distribution "
- + session.getWorkspace().getName(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return Status.OK_STATUS;
- }
-
- }
-
- private class NormalizingTraverser extends TraversingItemVisitor {
- ArgeoMonitor monitor;
-
- public NormalizingTraverser(ArgeoMonitor 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 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-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.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(NormalizeWorkspace.class);
-
- public final static String ID = DistPlugin.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 {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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.ID,
- "Cannot normalize distribution "
- + session.getWorkspace().getName(), e);
- } finally {
- JcrUtils.logoutQuietly(session);
- }
- return Status.OK_STATUS;
- }
- }
-
- private class NormalizingTraverser extends TraversingItemVisitor {
- ArgeoMonitor monitor;
-
- public NormalizingTraverser(ArgeoMonitor 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());
- pdeSourceIndexer.index(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());
- 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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 Log log = LogFactory.getLog(DeleteWorkspace.class);
-
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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.jcr.SlcTypes;
-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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Node;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.jcr.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.DistWorkspaceEditor;
-import org.argeo.slc.client.ui.dist.editors.DistWkspEditorInput;
-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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcConstants;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-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 Log log = LogFactory.getLog(PublishWorkspace.class);
-
- public final static String ID = DistPlugin.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();
- 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 ArgeoException(
- "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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.commands;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryFactory;
-
-import org.argeo.jcr.ArgeoNames;
-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.argeo.slc.jcr.SlcNames;
-import org.argeo.util.security.Keyring;
-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
- */
-public class RegisterRepository extends AbstractHandler implements ArgeoNames,
- SlcNames {
-
- public final static String ID = DistPlugin.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;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.eclipse.ui.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.core.execution.tasks.JvmProcess;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-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;
-import org.sonatype.aether.artifact.Artifact;
-
-/** <b>UNDER DEVELOPMENT</b>. Download and prepare an OSGi runtime */
-public class RunInOsgi extends AbstractHandler implements SlcNames {
- private final static Log log = LogFactory.getLog(RunInOsgi.class);
-
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.ArgeoTypes;
-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;
-
-/**
- * Unregisters 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 Log log = LogFactory
- // .getLog(UnregisterRemoteRepo.class);
-
- public final static String ID = DistPlugin.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.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();
- 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;
-
-/**
- * Enables 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 {
-
- // 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.jcr.SlcTypes;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.graphics.Image;
-
-public class ArtifactLabelProvider extends ColumnLabelProvider implements
- DistConstants, SlcTypes {
-
- // 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 ArgeoException(
- "Unexepected error while getting property values", re);
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.eclipse.ui.jcr.utils.JcrItemsComparator;
-import org.argeo.slc.jcr.SlcTypes;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public class ArtifactsTreeContentProvider implements ITreeContentProvider,
- SlcTypes {
-
- // 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 ArgeoException(
- "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 ArgeoException(
- "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.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-
-/**
- * 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 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.eclipse.ui.TreeParent;
-import org.argeo.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.ArgeoTypes;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.UserJcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.model.RepoElem;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.util.security.Keyring;
-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 Session nodeSession;
- List<RepoElem> repositories = new ArrayList<RepoElem>();
-
- /* DEPENDENCY INJECTION */
- private RepositoryFactory repositoryFactory;
- private Keyring keyring;
-
- public Object[] getElements(Object input) {
- Repository nodeRepository = (Repository) input;
- try {
- if (nodeSession != null)
- dispose();
- nodeSession = nodeRepository.login();
-
- String reposPath = UserJcrUtils.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 = UserJcrUtils.getUserHome(nodeSession);
- if (homeNode == null) // anonymous
- throw new SlcException("User must be authenticated.");
-
- // make sure base directory is available
- Node repos = JcrUtils.mkdirs(nodeSession, homeNode.getPath()
- + RepoConstants.REPOSITORIES_BASE_PATH);
- nodeSession.save();
-
- // register default local java repository
- String alias = RepoConstants.DEFAULT_JAVA_REPOSITORY_ALIAS;
- Repository javaRepository = ArgeoJcrUtils.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.eclipse.ui.utils.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.eclipse.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;
-
-/**
- * Manages icons and labels for the Distributions tree browser
- */
-public class DistTreeLabelProvider extends ColumnLabelProvider {
- @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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-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;
-
-/**
- * Base editor to manage an artifact in a multiple repository environment
- */
-public class ArtifactVersionEditor extends FormEditor implements SlcNames {
- // private final static Log log =
- // LogFactory.getLog(ArtifactEditor.class);
- public final static String ID = DistPlugin.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 ArgeoException("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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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);
- // /gd.heightHint = 200;
- 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() {
- @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() {
-
- 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() {
- @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() {
- @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() {
- @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() {
- @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() {
- @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() {
- @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 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.utils.CommandUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.build.License;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.utils.AbstractHyperlinkListener;
-import org.argeo.slc.client.ui.specific.OpenJcrFile;
-import org.argeo.slc.client.ui.specific.OpenJcrFileCmdId;
-import org.argeo.slc.jcr.SlcNames;
-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 the details for a given bundle.
- */
-public class BundleDetailPage extends FormPage implements SlcNames {
- private final static Log log = LogFactory.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 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(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 AbstractHyperlinkListener {
- final private String path;
-
- public OpenFileLinkListener(String path) {
- this.path = path;
- }
-
- @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, 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 ArgeoException(
- "unexpected error while generating maven snippet");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.slc.client.ui.dist.DistImages;
-import org.argeo.slc.client.ui.dist.utils.DistUiHelpers;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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;
-
-/**
- * Lists 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 {
-
- 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 ArgeoException(
- "unexpected error while getting artifact information",
- e);
- }
- }
- }
-
- private class TreeContentProvider implements ITreeContentProvider {
- 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 ArgeoException(
- "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 ArgeoException(
- "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 ArgeoException(
- "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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-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.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory
- // .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() {
- @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() {
-
- 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-import org.argeo.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.PrivilegedJob;
-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.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory
- // .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 {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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.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() {
- 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() {
- @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() {
- @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() {
- @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() {
- 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() {
- @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 {
- // 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-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 final static Log log =
- // LogFactory.getLog(DistributionEditor.class);
- public final static String ID = DistPlugin.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 ArgeoException("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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.ArgeoException;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.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 ArgeoException(
- "unexpected error while generating maven snippet");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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 final static Log log =
- // LogFactory.getLog(ModularDistVersionEditor.class);
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-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.AbstractHyperlinkListener;
-import org.argeo.slc.client.ui.dist.utils.DistNodeViewerComparator;
-import org.argeo.slc.client.ui.specific.OpenJcrFile;
-import org.argeo.slc.client.ui.specific.OpenJcrFileCmdId;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.slc.repo.maven.MavenConventionsUtils;
-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;
-import org.sonatype.aether.artifact.Artifact;
-import org.sonatype.aether.util.artifact.DefaultArtifact;
-
-/**
- * Show all modules contained in a given modular distribution as filter-able
- * table
- */
-public class ModularDistVersionOverviewPage extends FormPage implements
- SlcNames {
-
- 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 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 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 AbstractHyperlinkListener {
- final private String path;
-
- public OpenFileLinkListener(String path) {
- this.path = path;
- }
-
- @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, 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() {
- public void modifyText(ModifyEvent event) {
- refresh();
- }
- });
-
- Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
- resetBtn.setImage(DistImages.IMG_CLEAR);
- resetBtn.addSelectionListener(new SelectionAdapter() {
- 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() {
- @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() {
- @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() {
- @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() {
- @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() {
- @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 {
- // 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/**
- * An 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.editors;
-
-import javax.jcr.Node;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.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() {
- @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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-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.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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() {
- public void modifyText(ModifyEvent event) {
- refresh();
- }
- });
-
- Button resetBtn = tk.createButton(parent, null, SWT.PUSH);
- resetBtn.setImage(DistImages.IMG_REPO_READONLY);
- resetBtn.addSelectionListener(new SelectionAdapter() {
- 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() {
- @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() {
- @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() {
- 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.refreshParametrizedCommand(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() {
- @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 {
- // 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.ArgeoException;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.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 ArgeoException("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.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.slc.repo.RepoUtils;
-import org.argeo.util.security.Keyring;
-
-/**
- * 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 Log log = LogFactory.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 = ArgeoJcrUtils.getRepositoryByUri(
- repositoryFactory, uri);
- else {
- repository = RepoUtils.getRepository(repositoryFactory,
- keyring, repoNode);
- credentials = RepoUtils.getRepositoryCredentials(keyring,
- repoNode);
- }
-
- try {
- defaultSession = repository.login(credentials);
- 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 {
- 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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-
-/**
- * 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 ArgeoException("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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.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 ArgeoException(
- "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 ArgeoException(
- "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
-/*
- * Argeo Connect - Data management and communications
- * Copyright (C) 2012 Argeo GmbH
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
- * Additional permission under GNU GPL version 3 section 7
- *
- * If you modify this Program, or any covered work, by linking or combining it
- * with software covered by the terms of the Eclipse Public License, the
- * licensors of this Program grant you additional permission to convey the
- * resulting work. Corresponding Source for a non-source form of such a
- * combination shall include the source code for the parts of such software
- * which are used as well as that of the covered work.
- */
-package org.argeo.slc.client.ui.dist.utils;
-
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.events.IHyperlinkListener;
-
-public abstract class AbstractHyperlinkListener implements IHyperlinkListener {
-
- public void linkEntered(HyperlinkEvent e) {
- }
-
- public void linkExited(HyperlinkEvent e) {
- }
-
- /** Must be overriden **/
- public abstract void linkActivated(HyperlinkEvent e);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory
- // .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() {
- @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() {
- public String getText(Object element) {
- return null;
- }
-
- public Image getImage(Object element) {
- return null;
- }
- };
- } else
- return new ColumnLabelProvider() {
- public String getText(Object element) {
- Row row = (Row) element;
- try {
- return row.getValue(columnName).getString();
- } catch (RepositoryException e) {
- throw new ArgeoException("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 {
-
- 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 ArgeoException("comparator for object type "
- + v1.getType() + " is not yet implemented");
- } catch (Exception e) {
- throw new ArgeoException("rows cannot be compared ", e);
- }
- } else
- throw new ArgeoException("Unsupported row type");
- // If descending order, flip the direction
- if (direction == DESCENDING) {
- rc = -rc;
- }
- return rc;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.utils;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.ArgeoException;
-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 ArgeoException(
- "Unexepected exception while opening node editor", e);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.eclipse.jface.viewers.Viewer;
-
-/** Add ability to order by name version and version */
-public class DistNodeViewerComparator extends GenericTableComparator {
- private final static Log log = LogFactory
- .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 ArgeoException(
- "Unimplemented comparaison for PropertyType "
- + propertyType);
- }
-
- // If descending order, flip the direction
- if (direction == DESCENDING) {
- rc = -rc;
- }
-
- } catch (RepositoryException re) {
- throw new ArgeoException("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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.slc.client.ui.dist.DistConstants;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-
-public class DistUiHelpers implements DistConstants, SlcTypes, SlcNames {
- private final static Log log = LogFactory.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 ArgeoException("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.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 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 {
-
- @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;
-
-/**
- * Centralizes 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.GenericTableComparator;
-import org.argeo.slc.client.ui.dist.utils.ArtifactsTableConfigurer;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory
- .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 ArgeoException("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 {
-
- 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 {
- 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.views;
-
-import org.argeo.jcr.ArgeoNames;
-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.argeo.slc.jcr.SlcNames;
-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 Log log = LogFactory
- // .getLog(AnonymousDistributionsView.class);
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-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.jcr.SlcTypes;
-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 Log log = LogFactory.getLog(ArtifactsBrowser.class);
- public final static String ID = DistPlugin.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 ArgeoException("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 {
-
- // 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 ArgeoException(
- "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 ArgeoException(
- // "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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.views;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.TreeParent;
-import org.argeo.eclipse.ui.utils.CommandUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.slc.SlcException;
-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.argeo.slc.jcr.SlcNames;
-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.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() {
- 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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(menuManager, window,
- DeleteWorkspace.ID, DeleteWorkspace.DEFAULT_LABEL,
- DeleteWorkspace.DEFAULT_ICON, isDistribElem
- && singleElement && !isReadOnly, params);
-
- // Advanced submenu
- MenuManager submenu = new MenuManager("Advanced", DistPlugin.ID
- + ".advancedSubmenu");
- IContributionItem ici = menuManager.find(DistPlugin.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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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.refreshParametrizedCommand(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 repository) {
- this.nodeRepository = repository;
- }
-
- public void setTreeContentProvider(
- DistTreeContentProvider treeContentProvider) {
- this.treeContentProvider = treeContentProvider;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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;
-
-/**
- *
- * Displays some info about the distribution
- *
- */
-public class HelpView extends ViewPart {
- public final static String ID = DistPlugin.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.views;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-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 Log log = LogFactory.getLog(QueryArtifactsForm.class);
- public static final String ID = DistPlugin.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() {
- 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 ArgeoException(
- "Cannot generate where statement to get artifacts", e);
- }
- }
-
- @Override
- public void setFocus() {
- executeBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.views;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-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.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() {
- 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.views;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 Log log = LogFactory.getLog(QueryBundlesForm.class);
- public static final String ID = DistPlugin.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() {
- 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 ArgeoException(
- "Cannot generate where statement to get artifacts", e);
- }
- }
-
- @Override
- public void setFocus() {
- executeBtn.setFocus();
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.wizards;
-
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
-import org.argeo.ArgeoException;
-import org.argeo.jcr.JcrUtils;
-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 ArgeoException("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 ArgeoException(
- "Unexpected error while setting privileges", re);
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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 {
-
- // 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.ArgeoTypes;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.UserJcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.dist.DistPlugin;
-import org.argeo.slc.client.ui.dist.PrivilegedJob;
-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.argeo.util.security.Keyring;
-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 Log log = LogFactory.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 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() {
- 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() {
- 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() {
- @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 WkspComparator());
- }
- }
-
- private class AdvancedFetchPage extends WizardPage {
-
- 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 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() {
- @Override
- public String getText(Object element) {
- return ((WkspObject) element).srcName;
- }
- });
-
- column = ViewerUtils.createTableViewerColumn(recapViewer,
- "targets", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- @Override
- public String getText(Object element) {
- return ((WkspObject) element).targetName;
- }
- });
-
- recapViewer.setContentProvider(new IStructuredContentProvider() {
-
- 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 WkspComparator());
- 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 {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(progressMonitor);
- repoSync.setMonitor(monitor);
- repoSync.run();
- } catch (Exception e) {
- return new Status(IStatus.ERROR, DistPlugin.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 {
- // 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();
- session = currSourceRepo.login(currSourceCred);
- // 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(UserJcrUtils.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-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.PrivilegedJob;
-import org.argeo.slc.client.ui.dist.utils.ViewerUtils;
-import org.argeo.slc.jcr.SlcTypes;
-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.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;
-import org.sonatype.aether.artifact.Artifact;
-
-/**
- * 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 Log log = LogFactory
- .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 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() {
- @Override
- public String getText(Object element) {
- return ((Artifact) element).getArtifactId();
- }
- });
-
- column = ViewerUtils.createTableViewerColumn(recapViewer,
- "Version", SWT.NONE, 250);
- column.setLabelProvider(new ColumnLabelProvider() {
- @Override
- public String getText(Object element) {
- return ((Artifact) element).getBaseVersion();
- }
- });
-
- recapViewer.setContentProvider(new IStructuredContentProvider() {
- 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 {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(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.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.dist.wizards;
-
-import java.net.URI;
-import java.util.Hashtable;
-
-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.eclipse.ui.ErrorFeedback;
-import org.argeo.jcr.ArgeoJcrConstants;
-import org.argeo.jcr.ArgeoJcrUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.ArgeoTypes;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.jcr.UserJcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.repo.RepoConstants;
-import org.argeo.util.security.Keyring;
-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 = "http://repo.argeo.org/data/pub/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();
- String reposPath = UserJcrUtils.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 {
-
- 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() {
- 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() {
- 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();
- Hashtable<String, String> params = new Hashtable<String, String>();
- params.put(ArgeoJcrConstants.JCR_REPOSITORY_URI, checkedUriStr);
- Repository repository = ArgeoJcrUtils.getRepositoryByUri(
- repositoryFactory, checkedUriStr);
- if (username.getText().trim().equals("")) {// anonymous
- session = repository.login();
- } 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);
- }
- } else {// alias
- Repository repository = ArgeoJcrUtils.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/main/java"/>
- <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
-<?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
-#Wed Aug 04 16:31:36 CEST 2010
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.5
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+++ /dev/null
-#Tue Jul 27 14:24:51 CEST 2010
-eclipse.preferences.version=1
-resolve.requirebundle=false
+++ /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="(argeo.jcr.repository.alias=slc)" />\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
-source.. = src/main/java
-output.. = target/classes
-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="ROLE_SLC" />
- </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>plugins</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>org.argeo.slc.client.ui</artifactId>
- <name>SLC Client UI</name>
- <packaging>jar</packaging>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.argeo.slc.client.ui.ClientUiPlugin</Bundle-Activator>
- <Require-Bundle>
- org.eclipse.ui;resolution:=optional,
- org.eclipse.core.runtime;resolution:=optional,
- org.eclipse.rap.ui;resolution:=optional,
- org.eclipse.rap.ui.workbench;resolution:=optional
- </Require-Bundle>
- <Import-Package>
- org.argeo.eclipse.spring,
- org.argeo.security.ui,
- *
- </Import-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <!-- Single sourcing - we build against RCP -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.client.rcp</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- SLC -->
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.core</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.slc</groupId>
- <artifactId>org.argeo.slc.support.jcr</artifactId>
- <version>2.1.1-SNAPSHOT</version>
- </dependency>
-
- <!-- Argeo Commons -->
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui.jcr</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.security</groupId>
- <artifactId>org.argeo.security.ui</artifactId>
- <version>${version.argeo-commons}</version>
- </dependency>
-
- <!-- Eclipse and RCP only dependency, needed at compile time -->
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.ui.rcp</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.argeo.commons.base</groupId>
- <artifactId>org.argeo.eclipse.dep.rcp</artifactId>
- <version>${version.argeo-commons}</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.deploy.ModulesManager;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui;
-
-import org.argeo.security.ui.SecurityUiPlugin;
-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.3f, 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.commands;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.eclipse.ui.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
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.client.ui.commands;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-\r
-import javax.jcr.Node;\r
-import javax.jcr.RepositoryException;\r
-import javax.jcr.Session;\r
-\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.client.ui.ClientUiPlugin;\r
-import org.argeo.slc.client.ui.model.ResultFolder;\r
-import org.argeo.slc.client.ui.model.ResultParent;\r
-import org.argeo.slc.client.ui.model.ResultParentUtils;\r
-import org.argeo.slc.client.ui.model.SingleResultNode;\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.dialogs.MessageDialog;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-\r
-/** Deletes one or many results */\r
-public class DeleteItems extends AbstractHandler {\r
- public final static String ID = ClientUiPlugin.ID + ".deleteItems";\r
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin\r
- .getImageDescriptor("icons/removeAll.png");\r
- public final static String DEFAULT_LABEL = "Delete selected item(s)";\r
-\r
- public Object execute(final ExecutionEvent event) throws ExecutionException {\r
- final ISelection selection = HandlerUtil\r
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();\r
-\r
- // confirmation\r
- StringBuilder buf = new StringBuilder("");\r
- Iterator<?> lst = ((IStructuredSelection) selection).iterator();\r
- while (lst.hasNext()) {\r
- Object obj = lst.next();\r
- if (obj instanceof ResultParent) {\r
- ResultParent rp = ((ResultParent) obj);\r
- buf.append(rp.getName()).append(", ");\r
- }\r
- }\r
-\r
- String msg = "Nothing to delete";\r
- // remove last separator\r
- if (buf.lastIndexOf(", ") > -1) {\r
- msg = "Do you want to delete following objects (and their children): "\r
- + buf.substring(0, buf.lastIndexOf(", ")) + "?";\r
- }\r
- Boolean ok = MessageDialog.openConfirm(\r
- HandlerUtil.getActiveShell(event), "Confirm deletion", msg);\r
-\r
- if (!ok)\r
- return null;\r
-\r
- Job job = new Job("Delete results") {\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- if (selection != null\r
- && selection instanceof IStructuredSelection) {\r
- Map<String, Node> nodes = new HashMap<String, Node>();\r
- Iterator<?> it = ((IStructuredSelection) selection)\r
- .iterator();\r
- Object obj = null;\r
- try {\r
-\r
- while (it.hasNext()) {\r
- obj = it.next();\r
- if (obj instanceof ResultFolder) {\r
- Node node = ((ResultFolder) obj).getNode();\r
- nodes.put(node.getPath(), node);\r
- } else if (obj instanceof SingleResultNode) {\r
- Node node = ((SingleResultNode) obj).getNode();\r
- nodes.put(node.getPath(), node);\r
- }\r
- }\r
- if (!nodes.isEmpty()) {\r
- Session session = null;\r
- monitor.beginTask("Delete results", nodes.size());\r
- for (String path : nodes.keySet()) {\r
- if (session == null)\r
- session = nodes.get(path).getSession();\r
-\r
- // check if the item has not already been\r
- // deleted while deleting one of its ancestor\r
- if (session.itemExists(path)) {\r
- Node parent = nodes.get(path).getParent();\r
- nodes.get(path).remove();\r
- ResultParentUtils.updatePassedStatus(\r
- parent, true);\r
- }\r
- monitor.worked(1);\r
- }\r
- session.save();\r
- }\r
-\r
- } catch (RepositoryException e) {\r
- throw new SlcException(\r
- "Unexpected error while deleteting node(s)", e);\r
- }\r
- monitor.done();\r
- }\r
- return Status.OK_STATUS;\r
- }\r
-\r
- };\r
- job.setUser(true);\r
- job.schedule();\r
- return null;\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.client.ui.commands;\r
-\r
-import java.util.Iterator;\r
-\r
-import org.argeo.slc.client.ui.ClientUiPlugin;\r
-import org.argeo.slc.client.ui.model.ResultParent;\r
-import org.argeo.slc.client.ui.views.JcrResultTreeView;\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-\r
-/**\r
- * Force refresh the ResultTreeView. This command is only intended to be called\r
- * by either the toolbar menu of the view or by the popup menu. Refresh due to\r
- * data changes must be triggered by Observers\r
- */\r
-public class RefreshJcrResultTreeView extends AbstractHandler {\r
- public final static String ID = ClientUiPlugin.ID\r
- + ".refreshJcrResultTreeView";\r
- public final static String PARAM_REFRESH_TYPE = ClientUiPlugin.ID\r
- + ".param.refreshType";\r
- public final static String PARAM_REFRESH_TYPE_FULL = "fullRefresh";\r
- public final static ImageDescriptor DEFAULT_IMG_DESCRIPTOR = ClientUiPlugin\r
- .getImageDescriptor("icons/refresh.png");\r
- public final static String DEFAULT_LABEL = "Refresh selected";\r
-\r
- public Object execute(final ExecutionEvent event) throws ExecutionException {\r
- String refreshType = event.getParameter(PARAM_REFRESH_TYPE);\r
- JcrResultTreeView view = (JcrResultTreeView) HandlerUtil\r
- .getActiveWorkbenchWindow(event).getActivePage()\r
- .getActivePart();\r
-\r
- // force full refresh without preserving selection from the tool bar\r
- if (PARAM_REFRESH_TYPE_FULL.equals(refreshType))\r
- view.refresh(null);\r
- else {\r
- IStructuredSelection selection = (IStructuredSelection) HandlerUtil\r
- .getActiveWorkbenchWindow(event).getActivePage()\r
- .getSelection();\r
- @SuppressWarnings("rawtypes")\r
- Iterator it = selection.iterator();\r
- while (it.hasNext()) {\r
- Object obj = it.next();\r
- if (obj instanceof ResultParent) {\r
- view.refresh((ResultParent) obj);\r
- }\r
- }\r
- }\r
- return null;\r
- }\r
-}\r
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.client.ui.commands;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-\r
-import javax.jcr.Node;\r
-\r
-import org.apache.commons.logging.Log;\r
-import org.apache.commons.logging.LogFactory;\r
-import org.argeo.slc.BasicNameVersion;\r
-import org.argeo.slc.NameVersion;\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.deploy.ModulesManager;\r
-import org.argeo.slc.jcr.SlcNames;\r
-import org.argeo.slc.jcr.SlcTypes;\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-\r
-/** Deletes one or many results */\r
-public class UpdateModule extends AbstractHandler {\r
- private final static Log log = LogFactory.getLog(UpdateModule.class);\r
-\r
- private ModulesManager modulesManager;\r
-\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- final ISelection selection = HandlerUtil\r
- .getActiveWorkbenchWindow(event).getActivePage().getSelection();\r
- if (selection != null && selection instanceof IStructuredSelection) {\r
- UpdateJob job = new UpdateJob(selection);\r
- job.setUser(true);\r
- job.schedule();\r
- }\r
- return null;\r
- }\r
-\r
- private class UpdateJob extends Job {\r
- private final IStructuredSelection selection;\r
-\r
- public UpdateJob(ISelection selection) {\r
- super("Update modules");\r
- this.selection = ((IStructuredSelection) selection);\r
- }\r
-\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- Iterator<?> it = selection.iterator();\r
- Object obj = null;\r
- try {\r
- Map<String, Node> nodes = new HashMap<String, Node>();\r
- nodes: while (it.hasNext()) {\r
- obj = it.next();\r
- if (obj instanceof Node) {\r
- Node node = (Node) obj;\r
- Node executionModuleNode = null;\r
- while (executionModuleNode == null) {\r
- if (node.isNodeType(SlcTypes.SLC_EXECUTION_MODULE)) {\r
- executionModuleNode = node;\r
- }\r
- node = node.getParent();\r
- if (node.getPath().equals("/"))// root\r
- continue nodes;\r
- }\r
-\r
- if (!nodes.containsKey(executionModuleNode.getPath()))\r
- nodes.put(executionModuleNode.getPath(),\r
- executionModuleNode);\r
- }\r
- }\r
-\r
- monitor.beginTask("Update modules", nodes.size());\r
- for (Node executionModuleNode : nodes.values()) {\r
- monitor.subTask("Update " + executionModuleNode.getName());\r
- NameVersion nameVersion = new BasicNameVersion(\r
- executionModuleNode.getProperty(SlcNames.SLC_NAME)\r
- .getString(), executionModuleNode\r
- .getProperty(SlcNames.SLC_VERSION)\r
- .getString());\r
- modulesManager.upgrade(nameVersion);\r
- monitor.worked(1);\r
- log.info("Module " + nameVersion + " updated");\r
- if (monitor.isCanceled())\r
- return Status.CANCEL_STATUS;\r
- }\r
- return Status.OK_STATUS;\r
- } catch (Exception e) {\r
- throw new SlcException("Cannot update module " + obj, e);\r
- // return Status.CANCEL_STATUS;\r
- }\r
- }\r
-\r
- @Override\r
- protected void canceling() {\r
- getThread().interrupt();\r
- super.canceling();\r
- }\r
-\r
- }\r
-\r
- public void setModulesManager(ModulesManager modulesManager) {\r
- this.modulesManager = modulesManager;\r
- }\r
-\r
-}\r
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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.argeo.slc.jcr.SlcNames;
-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 Log log = LogFactory
- // .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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-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.ArgeoException;
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-import org.argeo.slc.client.ui.SlcImages;
-import org.argeo.slc.core.execution.PrimitiveAccessor;
-import org.argeo.slc.core.execution.PrimitiveUtils;
-import org.argeo.slc.execution.ExecutionProcess;
-import org.argeo.slc.jcr.SlcJcrUtils;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 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;
- }
-
- @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 ArgeoException("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 = processNode.getSession().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 ArgeoException("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 ArgeoException("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);
- 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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.ErrorFeedback;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-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.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-import org.eclipse.core.runtime.IProgressMonitor;
-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 {
- public final static String ID = ClientUiPlugin.ID + ".processEditor";
-
- private Session session;
- private Node processNode;
- private ProcessController processController;
-
- private ProcessBuilderPage builderPage;
-
- private ExecutionModulesManager modulesManager;
-
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- super.init(site, input);
- ProcessEditorInput pei = (ProcessEditorInput) input;
- String processPath = pei.getProcessPath();
- try {
- if (processPath != null) {
- if (!session.itemExists(processPath))
- throw new SlcException("Process " + processPath
- + " does not exist");
- processNode = session.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(session,
- uuid);
- Node processNode = JcrUtils.mkdirs(session, 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(session);
- 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 = flowNode.getSession().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);
- session.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 updateStatus(ExecutionProcess process, String oldStatus,
- // String newStatus) {
- // }
- //
- // public void addSteps(ExecutionProcess process, List<ExecutionStep> steps)
- // {
- // }
-
- /** Expects one session per editor. */
- @Deprecated
- public void setSession(Session session) {
- this.session = session;
- }
-
- public void setRepository(Repository repository) {
- try {
- session = repository.login();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to log in Repository " + repository,
- re);
- }
- }
-
- public void setProcessController(ProcessController processController) {
- this.processController = processController;
- }
-
- public void setModulesManager(ExecutionModulesManager modulesManager) {
- this.modulesManager = modulesManager;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.execution.ExecutionStep;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.jcr.SlcNames;
-import org.argeo.slc.jcr.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 Log log = LogFactory.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.model;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.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.jcr.SlcNames;
-import org.argeo.slc.jcr.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.jcr.SlcJcrResultUtils;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-
-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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.jcr.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.client.ui.model;
-
-import java.util.List;
-
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-
-import org.argeo.slc.SlcException;
-import org.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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 Log log = LogFactory
- // .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
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-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.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.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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.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 Log log = LogFactory
- .getLog(JcrExecutionModulesView.class);
-
- public static final String ID = ClientUiPlugin.ID
- + ".jcrExecutionModulesView";
-
- private TreeViewer viewer;
-
- /* DEPENDENCY INJECTION */
- private Session session;
- private ExecutionModulesManager modulesManager;
-
- public void createPartControl(Composite parent) {
- 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 {
-
- 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 ArgeoException("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 {
-
- @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 {
-
- // 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);
- super.dispose();
- }
-
- // DEPENDENCY INJECTION
-
- public void setModulesManager(ExecutionModulesManager modulesManager) {
- this.modulesManager = modulesManager;
- }
-
- @Deprecated
- public void setSession(Session session) {
- this.session = session;
- }
-
- public void setRepository(Repository repository) {
- try {
- session = repository.login();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to log in Repository " + repository,
- re);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.eclipse.ui.jcr.AsyncUiEventListener;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.slc.SlcException;
-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.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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.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 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) {
- 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);
- }
- }
-
- }
-
- @Deprecated
- public void setSession(Session session) {
- this.session = session;
- }
-
- public void dispose() {
- JcrUtils.unregisterQuietly(session.getWorkspace(), processesObserver);
- JcrUtils.logoutQuietly(session);
- super.dispose();
- }
-
- public void setRepository(Repository repository) {
- try {
- session = repository.login();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to log in Repository " + repository,
- re);
- }
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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.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.argeo.slc.jcr.SlcNames;
-import org.argeo.slc.jcr.SlcTypes;
-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 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) {
-
- 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 {
-
- 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 {
-
- 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();
- }
- }
-
- @Deprecated
- public void setSession(Session session) {
- this.session = session;
- }
-
- public void dispose() {
- JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);
- JcrUtils.logoutQuietly(session);
- super.dispose();
- }
-
- public void setRepository(Repository repository) {
- try {
- session = repository.login();
- } catch (RepositoryException re) {
- throw new SlcException("Unable to log in Repository " + repository,
- re);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (C) 2007-2012 Argeo GmbH\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.argeo.slc.client.ui.views;\r
-\r
-import java.text.DateFormat;\r
-import java.text.SimpleDateFormat;\r
-import java.util.ArrayList;\r
-import java.util.Calendar;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-import javax.jcr.Node;\r
-import javax.jcr.NodeIterator;\r
-import javax.jcr.Property;\r
-import javax.jcr.Repository;\r
-import javax.jcr.RepositoryException;\r
-import javax.jcr.Session;\r
-import javax.jcr.nodetype.NodeType;\r
-import javax.jcr.observation.Event;\r
-import javax.jcr.observation.EventListener;\r
-import javax.jcr.observation.ObservationManager;\r
-\r
-import org.argeo.ArgeoException;\r
-import org.argeo.eclipse.ui.jcr.AsyncUiEventListener;\r
-import org.argeo.eclipse.ui.utils.CommandUtils;\r
-import org.argeo.jcr.JcrUtils;\r
-import org.argeo.slc.SlcException;\r
-import org.argeo.slc.client.ui.ClientUiPlugin;\r
-import org.argeo.slc.client.ui.SlcUiConstants;\r
-import org.argeo.slc.client.ui.commands.AddResultFolder;\r
-import org.argeo.slc.client.ui.commands.DeleteItems;\r
-import org.argeo.slc.client.ui.commands.RefreshJcrResultTreeView;\r
-import org.argeo.slc.client.ui.commands.RenameResultFolder;\r
-import org.argeo.slc.client.ui.commands.RenameResultNode;\r
-import org.argeo.slc.client.ui.editors.ProcessEditor;\r
-import org.argeo.slc.client.ui.editors.ProcessEditorInput;\r
-import org.argeo.slc.client.ui.model.ParentNodeFolder;\r
-import org.argeo.slc.client.ui.model.ResultFolder;\r
-import org.argeo.slc.client.ui.model.ResultItemsComparator;\r
-import org.argeo.slc.client.ui.model.ResultItemsComparer;\r
-import org.argeo.slc.client.ui.model.ResultParent;\r
-import org.argeo.slc.client.ui.model.ResultParentUtils;\r
-import org.argeo.slc.client.ui.model.SingleResultNode;\r
-import org.argeo.slc.client.ui.model.VirtualFolder;\r
-import org.argeo.slc.client.ui.providers.ResultTreeContentProvider;\r
-import org.argeo.slc.client.ui.providers.ResultTreeLabelProvider;\r
-import org.argeo.slc.jcr.SlcJcrResultUtils;\r
-import org.argeo.slc.jcr.SlcNames;\r
-import org.argeo.slc.jcr.SlcTypes;\r
-import org.eclipse.jface.action.IMenuListener;\r
-import org.eclipse.jface.action.IMenuManager;\r
-import org.eclipse.jface.action.MenuManager;\r
-import org.eclipse.jface.dialogs.MessageDialog;\r
-import org.eclipse.jface.viewers.ColumnLabelProvider;\r
-import org.eclipse.jface.viewers.DecoratingLabelProvider;\r
-import org.eclipse.jface.viewers.DoubleClickEvent;\r
-import org.eclipse.jface.viewers.IDoubleClickListener;\r
-import org.eclipse.jface.viewers.ILabelDecorator;\r
-import org.eclipse.jface.viewers.ISelectionChangedListener;\r
-import org.eclipse.jface.viewers.IStructuredContentProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.viewers.SelectionChangedEvent;\r
-import org.eclipse.jface.viewers.TableViewer;\r
-import org.eclipse.jface.viewers.TableViewerColumn;\r
-import org.eclipse.jface.viewers.TreePath;\r
-import org.eclipse.jface.viewers.TreeViewer;\r
-import org.eclipse.jface.viewers.Viewer;\r
-import org.eclipse.jface.viewers.ViewerDropAdapter;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.SashForm;\r
-import org.eclipse.swt.dnd.DND;\r
-import org.eclipse.swt.dnd.DragSourceEvent;\r
-import org.eclipse.swt.dnd.DragSourceListener;\r
-import org.eclipse.swt.dnd.TextTransfer;\r
-import org.eclipse.swt.dnd.Transfer;\r
-import org.eclipse.swt.dnd.TransferData;\r
-import org.eclipse.swt.layout.FillLayout;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.swt.widgets.Menu;\r
-import org.eclipse.ui.ISharedImages;\r
-import org.eclipse.ui.IWorkbenchPage;\r
-import org.eclipse.ui.IWorkbenchWindow;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.part.ViewPart;\r
-\r
-/** SLC generic JCR Result tree view. */\r
-public class JcrResultTreeView extends ViewPart {\r
- public final static String ID = ClientUiPlugin.ID + ".jcrResultTreeView";\r
-\r
- private final static DateFormat dateFormat = new SimpleDateFormat(\r
- SlcUiConstants.DEFAULT_DISPLAY_DATE_TIME_FORMAT);\r
-\r
- // private final static Log log =\r
- // LogFactory.getLog(JcrResultTreeView.class);\r
-\r
- /* DEPENDENCY INJECTION */\r
- private Session session;\r
-\r
- // This page widgets\r
- private TreeViewer resultTreeViewer;\r
- private TableViewer propertiesViewer;\r
-\r
- private EventListener myResultsObserver = null;\r
- private EventListener allResultsObserver = null;\r
-\r
- // under My Results\r
- private final static String[] observedNodeTypesUnderMyResult = {\r
- SlcTypes.SLC_TEST_RESULT, SlcTypes.SLC_RESULT_FOLDER,\r
- SlcTypes.SLC_MY_RESULT_ROOT_FOLDER };\r
-\r
- private final static String[] observedNodeTypesUnderAllResults = {\r
- SlcTypes.SLC_TEST_RESULT, NodeType.NT_UNSTRUCTURED };\r
-\r
- private boolean isResultFolder = false;\r
-\r
- /**\r
- * To be overridden to adapt size of form and result frames.\r
- */\r
- protected int[] getWeights() {\r
- return new int[] { 70, 30 };\r
- }\r
-\r
- @Override\r
- public void createPartControl(Composite parent) {\r
- parent.setLayout(new FillLayout());\r
- // Main layout\r
- SashForm sashForm = new SashForm(parent, SWT.VERTICAL);\r
- sashForm.setSashWidth(4);\r
- sashForm.setLayout(new FillLayout());\r
-\r
- // Create the tree on top of the view\r
- Composite top = new Composite(sashForm, SWT.NONE);\r
- GridLayout gl = new GridLayout(1, false);\r
- top.setLayout(gl);\r
- resultTreeViewer = createResultsTreeViewer(top);\r
-\r
- // Create the property viewer on the bottom\r
- Composite bottom = new Composite(sashForm, SWT.NONE);\r
- bottom.setLayout(new GridLayout(1, false));\r
- propertiesViewer = createPropertiesViewer(bottom);\r
-\r
- sashForm.setWeights(getWeights());\r
-\r
- setOrderedInput(resultTreeViewer);\r
-\r
- // Initialize observer\r
- try {\r
- ObservationManager observationManager = session.getWorkspace()\r
- .getObservationManager();\r
- myResultsObserver = new MyResultsObserver(resultTreeViewer\r
- .getTree().getDisplay());\r
- allResultsObserver = new AllResultsObserver(resultTreeViewer\r
- .getTree().getDisplay());\r
-\r
- // observe tree changes under MyResults\r
- observationManager.addEventListener(myResultsObserver,\r
- Event.NODE_ADDED | Event.NODE_REMOVED,\r
- SlcJcrResultUtils.getMyResultsBasePath(session), true,\r
- null, observedNodeTypesUnderMyResult, false);\r
- // observe tree changes under All results\r
- observationManager.addEventListener(allResultsObserver,\r
- Event.NODE_ADDED | Event.NODE_REMOVED,\r
- SlcJcrResultUtils.getSlcResultsBasePath(session), true,\r
- null, observedNodeTypesUnderAllResults, false);\r
- } catch (RepositoryException e) {\r
- throw new SlcException("Cannot register listeners", e);\r
- }\r
- }\r
-\r
- /**\r
- * Override default behaviour so that default defined order remains\r
- * unchanged on first level of the tree\r
- */\r
- private void setOrderedInput(TreeViewer viewer) {\r
- // Add specific ordering\r
- viewer.setInput(null);\r
- viewer.setComparator(null);\r
- viewer.setInput(initializeResultTree());\r
- viewer.setComparator(new ResultItemsComparator());\r
- }\r
-\r
- // The main tree viewer\r
- protected TreeViewer createResultsTreeViewer(Composite parent) {\r
- int style = SWT.BORDER | SWT.MULTI;\r
-\r
- TreeViewer viewer = new TreeViewer(parent, style);\r
- viewer.getTree().setLayoutData(\r
- new GridData(SWT.FILL, SWT.FILL, true, true));\r
-\r
- viewer.setContentProvider(new ResultTreeContentProvider());\r
-\r
- // Add label provider with label decorator\r
- ResultTreeLabelProvider rtLblProvider = new ResultTreeLabelProvider();\r
- ILabelDecorator decorator = ClientUiPlugin.getDefault().getWorkbench()\r
- .getDecoratorManager().getLabelDecorator();\r
- viewer.setLabelProvider(new DecoratingLabelProvider(rtLblProvider,\r
- decorator));\r
- viewer.addDoubleClickListener(new ViewDoubleClickListener());\r
-\r
- // Override default behaviour to insure that 2 distincts results that\r
- // have the same name will be correctly and distincly returned by\r
- // corresponding TreeViewer.getSelection() method.\r
- viewer.setComparer(new ResultItemsComparer());\r
-\r
- // viewer.setLabelProvider(rtLblProvider);\r
- getSite().setSelectionProvider(viewer);\r
-\r
- // add drag & drop support\r
- int operations = DND.DROP_COPY | DND.DROP_MOVE;\r
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };\r
- viewer.addDragSupport(operations, tt, new ViewDragListener());\r
- viewer.addDropSupport(operations, tt, new ViewDropListener(viewer));\r
-\r
- // add context menu\r
- MenuManager menuManager = new MenuManager();\r
- Menu menu = menuManager.createContextMenu(viewer.getTree());\r
- menuManager.addMenuListener(new IMenuListener() {\r
- public void menuAboutToShow(IMenuManager manager) {\r
- contextMenuAboutToShow(manager);\r
- }\r
- });\r
- viewer.getTree().setMenu(menu);\r
- menuManager.setRemoveAllWhenShown(true);\r
-\r
- getSite().registerContextMenu(menuManager, viewer);\r
-\r
- // add change listener to display TestResult information in the property\r
- // viewer\r
- viewer.addSelectionChangedListener(new MySelectionChangedListener());\r
- return viewer;\r
- }\r
-\r
- // Detailed property viewer\r
- protected TableViewer createPropertiesViewer(Composite parent) {\r
- propertiesViewer = new TableViewer(parent);\r
- propertiesViewer.getTable().setLayoutData(\r
- new GridData(SWT.FILL, SWT.FILL, true, true));\r
- propertiesViewer.getTable().setHeaderVisible(true);\r
- propertiesViewer.setContentProvider(new PropertiesContentProvider());\r
- TableViewerColumn col = new TableViewerColumn(propertiesViewer,\r
- SWT.NONE);\r
- col.getColumn().setText("Name");\r
- col.getColumn().setWidth(100);\r
- col.setLabelProvider(new ColumnLabelProvider() {\r
- public String getText(Object element) {\r
- try {\r
- String name = ((Property) element).getName();\r
- String value = null;\r
- if (SlcNames.SLC_TEST_CASE.equals(name))\r
- value = "Test case";\r
- else if (SlcNames.SLC_COMPLETED.equals(name))\r
- value = "Completed on";\r
- else if (SlcNames.SLC_SUCCESS.equals(name))\r
- value = "Status";\r
- else if (SlcNames.SLC_MESSAGE.equals(name))\r
- value = "Message";\r
- else if (SlcNames.SLC_ERROR_MESSAGE.equals(name))\r
- value = "Error";\r
- return value;\r
- } catch (RepositoryException e) {\r
- throw new ArgeoException(\r
- "Unexpected exception in label provider", e);\r
- }\r
- }\r
- });\r
- col = new TableViewerColumn(propertiesViewer, SWT.NONE);\r
- col.getColumn().setText("Value");\r
- col.getColumn().setWidth(200);\r
- col.setLabelProvider(new ColumnLabelProvider() {\r
- public String getText(Object element) {\r
- try {\r
- Property property = (Property) element;\r
- String name = property.getName();\r
- String value = null;\r
-\r
- if (SlcNames.SLC_TEST_CASE.equals(name)\r
- || SlcNames.SLC_ERROR_MESSAGE.equals(name)\r
- || SlcNames.SLC_MESSAGE.equals(name))\r
- value = property.getValue().getString();\r
- else if (SlcNames.SLC_COMPLETED.equals(name)) {\r
- Calendar date = property.getValue().getDate();\r
- value = dateFormat.format(date.getTime());\r
- } else if (SlcNames.SLC_SUCCESS.equals(name)) {\r
- if (property.getValue().getBoolean())\r
- value = "PASSED";\r
- else {\r
- if (property.getParent().hasProperty(\r
- SlcNames.SLC_ERROR_MESSAGE))\r
- value = "ERROR";\r
- else\r
- value = "FAILED";\r
- }\r
- }\r
- return value;\r
- } catch (RepositoryException e) {\r
- throw new ArgeoException(\r
- "Unexpected exception in label provider", e);\r
- }\r
- }\r
- });\r
- propertiesViewer.setInput(getViewSite());\r
- return propertiesViewer;\r
- }\r
-\r
- /**\r
- * Override to provide specific behaviour. Typically to enable the display\r
- * of a result file.\r
- * \r
- * @param evt\r
- */\r
- protected void processDoubleClick(DoubleClickEvent evt) {\r
- Object obj = ((IStructuredSelection) evt.getSelection())\r
- .getFirstElement();\r
- try {\r
- if (obj instanceof SingleResultNode) {\r
- SingleResultNode srNode = (SingleResultNode) obj;\r
- Node node = srNode.getNode();\r
- // FIXME: open a default result editor\r
- if (node.isNodeType(SlcTypes.SLC_PROCESS)) {\r
- IWorkbenchPage activePage = PlatformUI.getWorkbench()\r
- .getActiveWorkbenchWindow().getActivePage();\r
- activePage.openEditor(\r
- new ProcessEditorInput(node.getPath()),\r
- ProcessEditor.ID);\r
- }\r
- }\r
- } catch (Exception e) {\r
- throw new SlcException("Cannot open " + obj, e);\r
- }\r
- }\r
-\r
- @Override\r
- public void setFocus() {\r
- }\r
-\r
- /**\r
- * refreshes the passed resultParent and its corresponding subtree. It\r
- * refreshes the whole viewer if null is passed.\r
- * \r
- * @param ResultParent\r
- * \r
- */\r
- public void refresh(ResultParent resultParent) {\r
- if (resultParent == null) {\r
- if (!resultTreeViewer.getTree().isDisposed()) {\r
- TreePath[] tps = resultTreeViewer.getExpandedTreePaths();\r
- setOrderedInput(resultTreeViewer);\r
- resultTreeViewer.setExpandedTreePaths(tps);\r
- } else\r
- setOrderedInput(resultTreeViewer);\r
- } else {\r
- if (resultParent instanceof ParentNodeFolder) {\r
- ParentNodeFolder currFolder = (ParentNodeFolder) resultParent;\r
- jcrRefresh(currFolder.getNode());\r
- currFolder.forceFullRefresh();\r
- }\r
- // FIXME: specific refresh does not work\r
- // resultTreeViewer.refresh(resultParent, true);\r
- refresh(null);\r
- }\r
- }\r
-\r
- /**\r
- * refreshes the passed node and its corresponding subtree.\r
- * \r
- * @param node\r
- * cannot be null\r
- * \r
- */\r
- public boolean jcrRefresh(Node node) {\r
- // if (log.isDebugEnabled())\r
- // log.debug(" JCR refreshing " + node + "...");\r
- // Thread.dumpStack();\r
- boolean isPassed = true;\r
- try {\r
- if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {\r
- isPassed = node.getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean();\r
- } else if (node.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {\r
- NodeIterator ni = node.getNodes();\r
- while (ni.hasNext()) {\r
- Node currChild = ni.nextNode();\r
- isPassed = isPassed & jcrRefresh(currChild);\r
- }\r
- if (isPassed != node.getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean()) {\r
- node.getNode(SlcNames.SLC_AGGREGATED_STATUS).setProperty(\r
- SlcNames.SLC_SUCCESS, isPassed);\r
- node.getSession().save();\r
- return isPassed;\r
- }\r
- } else\r
- ; // do nothing\r
- } catch (RepositoryException e) {\r
- throw new SlcException("Cannot register listeners", e);\r
- }\r
- return isPassed;\r
- }\r
-\r
- private ResultParent[] initializeResultTree() {\r
- try {\r
- // Force initialization of the tree structure if needed\r
- SlcJcrResultUtils.getSlcResultsParentNode(session);\r
- SlcJcrResultUtils.getMyResultParentNode(session);\r
- // Remove yesterday and last 7 days virtual folders\r
- // ResultParent[] roots = new ResultParent[5];\r
- ResultParent[] roots = new ResultParent[3];\r
-\r
- // My results\r
- roots[0] = new ParentNodeFolder(null,\r
- SlcJcrResultUtils.getMyResultParentNode(session),\r
- SlcUiConstants.DEFAULT_MY_RESULTS_FOLDER_LABEL);\r
-\r
- // today\r
- Calendar cal = Calendar.getInstance();\r
- String relPath = JcrUtils.dateAsPath(cal);\r
- List<String> datePathes = new ArrayList<String>();\r
- datePathes.add(relPath);\r
- roots[1] = new VirtualFolder(null,\r
- ResultParentUtils.getResultsForDates(session, datePathes),\r
- "Today");\r
-\r
- // // Yesterday\r
- // cal = Calendar.getInstance();\r
- // cal.add(Calendar.DAY_OF_YEAR, -1);\r
- // relPath = JcrUtils.dateAsPath(cal);\r
- // datePathes = new ArrayList<String>();\r
- // datePathes.add(relPath);\r
- // roots[2] = new VirtualFolder(null,\r
- // ResultParentUtils.getResultsForDates(session, datePathes),\r
- // "Yesterday");\r
- // // Last 7 days\r
- //\r
- // cal = Calendar.getInstance();\r
- // datePathes = new ArrayList<String>();\r
- //\r
- // for (int i = 0; i < 7; i++) {\r
- // cal.add(Calendar.DAY_OF_YEAR, -i);\r
- // relPath = JcrUtils.dateAsPath(cal);\r
- // datePathes.add(relPath);\r
- // }\r
- // roots[3] = new VirtualFolder(null,\r
- // ResultParentUtils.getResultsForDates(session, datePathes),\r
- // "Last 7 days");\r
-\r
- // All results\r
- Node otherResultsPar = session.getNode(SlcJcrResultUtils\r
- .getSlcResultsBasePath(session));\r
- // roots[4] = new ParentNodeFolder(null, otherResultsPar,\r
- // "All results");\r
- roots[2] = new ParentNodeFolder(null, otherResultsPar,\r
- "All results");\r
- return roots;\r
- } catch (RepositoryException re) {\r
- throw new ArgeoException(\r
- "Unexpected error while initializing ResultTree.", re);\r
- }\r
- }\r
-\r
- // Manage context menu\r
- /**\r
- * Defines the commands that will pop up in the context menu.\r
- **/\r
- protected void contextMenuAboutToShow(IMenuManager menuManager) {\r
- IWorkbenchWindow window = ClientUiPlugin.getDefault().getWorkbench()\r
- .getActiveWorkbenchWindow();\r
-\r
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
- .getSelection();\r
- boolean canAddSubfolder = false;\r
- boolean canRenamefolder = false;\r
- boolean isSingleResultNode = false;\r
- boolean isUnderMyResult = false;\r
- boolean validMultipleDelete = false;\r
- try {\r
-\r
- // Building conditions\r
- if (selection.size() == 1) {\r
- Object obj = selection.getFirstElement();\r
- if (obj instanceof SingleResultNode)\r
- isSingleResultNode = true;\r
- else if (obj instanceof ParentNodeFolder) {\r
- Node cNode = ((ParentNodeFolder) obj).getNode();\r
- if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER)) {\r
- canAddSubfolder = true;\r
- canRenamefolder = true;\r
- isUnderMyResult = true;\r
- } else if (cNode\r
- .isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER)) {\r
- canAddSubfolder = true;\r
- }\r
- }\r
- } else {\r
- @SuppressWarnings("rawtypes")\r
- Iterator it = selection.iterator();\r
- multicheck: while (it.hasNext()) {\r
- validMultipleDelete = true;\r
- Object obj = it.next();\r
- if (obj instanceof SingleResultNode)\r
- continue multicheck;\r
- else if (obj instanceof ParentNodeFolder) {\r
- Node cNode = ((ParentNodeFolder) obj).getNode();\r
- if (cNode.isNodeType(SlcTypes.SLC_RESULT_FOLDER))\r
- continue multicheck;\r
- else {\r
- validMultipleDelete = false;\r
- break multicheck;\r
- }\r
- } else {\r
- validMultipleDelete = false;\r
- break multicheck;\r
- }\r
- }\r
- }\r
- } catch (RepositoryException re) {\r
- throw new SlcException(\r
- "unexpected error while building condition for context menu",\r
- re);\r
- }\r
-\r
- // Effective Refresh\r
- CommandUtils.refreshCommand(menuManager, window,\r
- RefreshJcrResultTreeView.ID,\r
- RefreshJcrResultTreeView.DEFAULT_LABEL,\r
- RefreshJcrResultTreeView.DEFAULT_IMG_DESCRIPTOR, true);\r
-\r
- CommandUtils.refreshCommand(menuManager, window, DeleteItems.ID,\r
- DeleteItems.DEFAULT_LABEL, DeleteItems.DEFAULT_IMG_DESCRIPTOR,\r
- isUnderMyResult || isSingleResultNode || validMultipleDelete);\r
-\r
- CommandUtils.refreshCommand(menuManager, window, AddResultFolder.ID,\r
- AddResultFolder.DEFAULT_LABEL,\r
- ClientUiPlugin.getDefault().getWorkbench().getSharedImages()\r
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD),\r
- canAddSubfolder);\r
-\r
- CommandUtils.refreshCommand(menuManager, window, RenameResultFolder.ID,\r
- RenameResultFolder.DEFAULT_LABEL,\r
- RenameResultFolder.DEFAULT_IMG_DESCRIPTOR, canRenamefolder);\r
-\r
- // Command removed for the time being.\r
- CommandUtils.refreshCommand(menuManager, window, RenameResultNode.ID,\r
- RenameResultNode.DEFAULT_LABEL,\r
- RenameResultNode.DEFAULT_IMG_DESCRIPTOR, false);\r
-\r
- // Test to be removed\r
- // If you use this pattern, do not forget to call\r
- // menuManager.setRemoveAllWhenShown(true);\r
- // when creating the menuManager\r
-\r
- // menuManager.add(new Action("Test") {\r
- // public void run() {\r
- // log.debug("do something");\r
- // }\r
- // });\r
- }\r
-\r
- /* INNER CLASSES */\r
- class ViewDragListener implements DragSourceListener {\r
-\r
- public void dragStart(DragSourceEvent event) {\r
- // Check if the drag action should start.\r
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
- .getSelection();\r
- boolean doIt = false;\r
-\r
- // FIXME clean this code.\r
- try {\r
- if (selection.size() == 1) {\r
- Object obj = selection.getFirstElement();\r
- if (obj instanceof ResultFolder) {\r
- Node tNode = ((ResultFolder) obj).getNode();\r
- if (tNode.getPrimaryNodeType().isNodeType(\r
- SlcTypes.SLC_RESULT_FOLDER)) {\r
- doIt = true;\r
- isResultFolder = true;\r
- }\r
- } else\r
- isResultFolder = false;\r
- } else\r
- isResultFolder = false;\r
-\r
- if (!isResultFolder) {\r
- @SuppressWarnings("rawtypes")\r
- Iterator it = selection.iterator();\r
- while (it.hasNext()) {\r
- Object obj = it.next();\r
- if (obj instanceof SingleResultNode) {\r
- Node tNode = ((SingleResultNode) obj).getNode();\r
- if (tNode.getPrimaryNodeType().isNodeType(\r
- SlcTypes.SLC_TEST_RESULT)) {\r
- doIt = true;\r
- }\r
- }\r
- }\r
- }\r
-\r
- } catch (RepositoryException re) {\r
- throw new SlcException(\r
- "unexpected error while validating drag source", re);\r
- }\r
- event.doit = doIt;\r
- }\r
-\r
- public void dragSetData(DragSourceEvent event) {\r
- IStructuredSelection selection = (IStructuredSelection) resultTreeViewer\r
- .getSelection();\r
-\r
- try {\r
- // specific case of a result folder\r
- if (isResultFolder) {\r
- Object obj = selection.getFirstElement();\r
- event.data = ((ResultFolder) obj).getNode().getIdentifier();\r
- } else {\r
- @SuppressWarnings("rawtypes")\r
- Iterator it = selection.iterator();\r
- StringBuilder nodes = new StringBuilder();\r
- while (it.hasNext()) {\r
- Object obj = it.next();\r
- if (obj instanceof SingleResultNode) {\r
- Node tNode = ((SingleResultNode) obj).getNode();\r
- if (tNode.getPrimaryNodeType().isNodeType(\r
- SlcTypes.SLC_TEST_RESULT)) {\r
- nodes.append(tNode.getIdentifier()).append(";");\r
- }\r
- }\r
- }\r
- event.data = nodes.toString();\r
- }\r
- } catch (RepositoryException re) {\r
- throw new SlcException("unexpected error while setting data",\r
- re);\r
- }\r
- }\r
-\r
- public void dragFinished(DragSourceEvent event) {\r
- // refresh is done via observer\r
- }\r
- }\r
-\r
- // Implementation of the Drop Listener\r
- protected class ViewDropListener extends ViewerDropAdapter {\r
- private Node targetParentNode = null;\r
-\r
- public ViewDropListener(Viewer viewer) {\r
- super(viewer);\r
- }\r
-\r
- @Override\r
- public boolean validateDrop(Object target, int operation,\r
- TransferData transferType) {\r
- boolean validDrop = false;\r
- try {\r
- // We can only drop under myResults\r
- Node tpNode = null;\r
- if (target instanceof SingleResultNode) {\r
- Node currNode = ((SingleResultNode) target).getNode();\r
- String pPath = currNode.getParent().getPath();\r
- if (pPath.startsWith(SlcJcrResultUtils\r
- .getMyResultsBasePath(session)))\r
- tpNode = currNode.getParent();\r
- } else if (target instanceof ResultFolder) {\r
- tpNode = ((ResultFolder) target).getNode();\r
- } else if (target instanceof ParentNodeFolder) {\r
- Node node = ((ParentNodeFolder) target).getNode();\r
- if (node.isNodeType(SlcTypes.SLC_MY_RESULT_ROOT_FOLDER))\r
- tpNode = ((ParentNodeFolder) target).getNode();\r
- }\r
-\r
- if (tpNode != null) {\r
- targetParentNode = tpNode;\r
- validDrop = true;\r
- }\r
- } catch (RepositoryException re) {\r
- throw new SlcException(\r
- "unexpected error while validating drop target", re);\r
- }\r
- return validDrop;\r
- }\r
-\r
- @Override\r
- public boolean performDrop(Object data) {\r
- // clear selection to prevent unwanted scrolling of the UI\r
- resultTreeViewer.setSelection(null);\r
- try {\r
- if (isResultFolder) {\r
- // Sanity check : we cannot move a folder to one of its sub\r
- // folder or neither move an object in the same parent\r
- // folder\r
- Node source = session.getNodeByIdentifier((String) data);\r
- if (targetParentNode.getPath().startsWith(source.getPath())\r
- || source.getParent().getPath()\r
- .equals(targetParentNode.getPath()))\r
- return false;\r
-\r
- // Move\r
- String sourcePath = source.getPath();\r
- String destPath = targetParentNode.getPath() + "/"\r
- + source.getName();\r
- session.move(sourcePath, destPath);\r
- // Update passed status of the parent source Node\r
- ResultParentUtils.updatePassedStatus(\r
- session.getNode(JcrUtils.parentPath(sourcePath)),\r
- true);\r
- // Node target = session.getNode(destPath);\r
- session.save();\r
- return true;\r
- }\r
-\r
- String[] datas = ((String) data).split(";");\r
- nodesToCopy: for (String id : datas) {\r
-\r
- Node source = session.getNodeByIdentifier(id);\r
- String name;\r
- if (source.hasProperty(Property.JCR_TITLE))\r
- name = source.getProperty(Property.JCR_TITLE)\r
- .getString();\r
- else if (source.hasProperty(SlcNames.SLC_TEST_CASE))\r
- name = source.getProperty(SlcNames.SLC_TEST_CASE)\r
- .getString();\r
- else\r
- name = source.getName();\r
-\r
- // Check if another copy of the same test instance already\r
- // exists at target\r
- NodeIterator ni = targetParentNode.getNodes();\r
- String slcUid = source.getProperty(SlcNames.SLC_UUID)\r
- .getString();\r
- while (ni.hasNext()) {\r
- Node curr = ni.nextNode();\r
- if (curr.hasProperty(SlcNames.SLC_UUID)\r
- && slcUid.equals(curr.getProperty(\r
- SlcNames.SLC_UUID).getString())) {\r
- MessageDialog\r
- .openWarning(\r
- PlatformUI.getWorkbench()\r
- .getDisplay()\r
- .getActiveShell(),\r
- "Duplicated instance.",\r
- "An instance of the same test case ("\r
- + name\r
- + ") exists at destination.\n "\r
- + "This item will not be neither copied nor moved.");\r
- continue nodesToCopy;\r
-\r
- }\r
- }\r
-\r
- Node target;\r
- boolean passedStatus = false;\r
- if (source.hasNode(SlcNames.SLC_AGGREGATED_STATUS))\r
- passedStatus = source\r
- .getNode(SlcNames.SLC_AGGREGATED_STATUS)\r
- .getProperty(SlcNames.SLC_SUCCESS).getBoolean();\r
-\r
- boolean isActionUnderMyResult = source.getPath()\r
- .startsWith(\r
- SlcJcrResultUtils\r
- .getMyResultsBasePath(session));\r
-\r
- if (!isActionUnderMyResult) {// Copy\r
- target = targetParentNode.addNode(source.getName(),\r
- source.getPrimaryNodeType().getName());\r
- JcrUtils.copy(source, target);\r
- } else {// move\r
- String sourcePath = source.getPath();\r
- String destPath = targetParentNode.getPath() + "/"\r
- + name;\r
- session.move(sourcePath, destPath);\r
- // Update passed status of the parent source Node\r
- ResultParentUtils\r
- .updatePassedStatus(session.getNode(JcrUtils\r
- .parentPath(sourcePath)), true);\r
- target = session.getNode(destPath);\r
-\r
- }\r
- if (!target.isNodeType(NodeType.MIX_TITLE))\r
- target.addMixin(NodeType.MIX_TITLE);\r
- target.setProperty(Property.JCR_TITLE, name);\r
- ResultParentUtils.updatePassedStatus(target.getParent(),\r
- passedStatus);\r
- session.save();\r
- }\r
- } catch (RepositoryException re) {\r
- throw new SlcException(\r
- "unexpected error while copying dropped node", re);\r
-\r
- }\r
- return true;\r
- }\r
- }\r
-\r
- class MyResultsObserver extends AsyncUiEventListener {\r
-\r
- public MyResultsObserver(Display display) {\r
- super(display);\r
- }\r
-\r
- @Override\r
- protected Boolean willProcessInUiThread(List<Event> events)\r
- throws RepositoryException {\r
- // unfiltered for the time being\r
- return true;\r
- }\r
-\r
- protected void onEventInUiThread(List<Event> events)\r
- throws RepositoryException {\r
- List<Node> nodesToRefresh = new ArrayList<Node>();\r
-\r
- for (Event event : events) {\r
- String parPath = JcrUtils.parentPath(event.getPath());\r
- if (session.nodeExists(parPath)) {\r
- Node node = session.getNode(parPath);\r
- if (!nodesToRefresh.contains(node)) {\r
- nodesToRefresh.add(node);\r
- }\r
- }\r
- }\r
-\r
- // Update check nodes\r
- for (Node node : nodesToRefresh)\r
- jcrRefresh(node);\r
- refresh(null);\r
- }\r
- }\r
-\r
- class AllResultsObserver extends AsyncUiEventListener {\r
-\r
- public AllResultsObserver(Display display) {\r
- super(display);\r
- }\r
-\r
- @Override\r
- protected Boolean willProcessInUiThread(List<Event> events)\r
- throws RepositoryException {\r
- // unfiltered for the time being\r
- return true;\r
- }\r
-\r
- protected void onEventInUiThread(List<Event> events)\r
- throws RepositoryException {\r
- refresh(null);\r
- // if (lastSelectedSourceElementParent != null)\r
- // refresh(lastSelectedSourceElementParent);\r
- }\r
- }\r
-\r
- class PropertiesContentProvider implements IStructuredContentProvider {\r
-\r
- public void dispose() {\r
- }\r
-\r
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {\r
- }\r
-\r
- public Object[] getElements(Object inputElement) {\r
- try {\r
- if (inputElement instanceof Node) {\r
- Node node = (Node) inputElement;\r
- if (node.isNodeType(SlcTypes.SLC_TEST_RESULT)) {\r
- List<Property> props = new ArrayList<Property>();\r
- if (node.hasProperty(SlcNames.SLC_TEST_CASE))\r
- props.add(node.getProperty(SlcNames.SLC_TEST_CASE));\r
- if (node.hasProperty(SlcNames.SLC_COMPLETED))\r
- props.add(node.getProperty(SlcNames.SLC_COMPLETED));\r
- if (node.hasNode(SlcNames.SLC_AGGREGATED_STATUS)) {\r
- Node status = node\r
- .getNode(SlcNames.SLC_AGGREGATED_STATUS);\r
- props.add(status.getProperty(SlcNames.SLC_SUCCESS));\r
- if (status.hasProperty(SlcNames.SLC_MESSAGE))\r
- props.add(status\r
- .getProperty(SlcNames.SLC_MESSAGE));\r
- if (status.hasProperty(SlcNames.SLC_ERROR_MESSAGE))\r
- props.add(status\r
- .getProperty(SlcNames.SLC_ERROR_MESSAGE));\r
- }\r
- return props.toArray();\r
- }\r
- }\r
- return new Object[] {};\r
-\r
- } catch (RepositoryException e) {\r
- throw new ArgeoException("Cannot get element for "\r
- + inputElement, e);\r
- }\r
- }\r
- }\r
-\r
- class MySelectionChangedListener implements ISelectionChangedListener {\r
-\r
- public void selectionChanged(SelectionChangedEvent event) {\r
- if (!event.getSelection().isEmpty()) {\r
- IStructuredSelection sel = (IStructuredSelection) event\r
- .getSelection();\r
- ResultParent firstItem = (ResultParent) sel.getFirstElement();\r
- if (firstItem instanceof SingleResultNode)\r
- propertiesViewer.setInput(((SingleResultNode) firstItem)\r
- .getNode());\r
- else\r
- propertiesViewer.setInput(null);\r
- // update cache for Drag & drop\r
- // lastSelectedTargetElement = firstItem;\r
- // lastSelectedSourceElement = firstItem;\r
- // lastSelectedSourceElementParent = (ResultParent) firstItem\r
- // .getParent();\r
- // String pPath = "";\r
- // try {\r
- //\r
- // if (firstItem instanceof ParentNodeFolder)\r
- // pPath = ((ParentNodeFolder) firstItem).getNode()\r
- // .getPath();\r
- // else if (firstItem instanceof SingleResultNode)\r
- // pPath = ((SingleResultNode) firstItem).getNode()\r
- // .getPath();\r
- // } catch (RepositoryException e) {\r
- // throw new SlcException(\r
- // "Unexpected error while checking parent UI tree", e);\r
- // }\r
- // if ((pPath.startsWith(SlcJcrResultUtils\r
- // .getMyResultsBasePath(session))))\r
- // isActionUnderMyResult = true;\r
- // else\r
- // isActionUnderMyResult = false;\r
- }\r
- }\r
- }\r
-\r
- class ViewDoubleClickListener implements IDoubleClickListener {\r
- public void doubleClick(DoubleClickEvent evt) {\r
- processDoubleClick(evt);\r
- }\r
-\r
- }\r
-\r
- /* DEPENDENCY INJECTION */\r
- @Deprecated\r
- public void setSession(Session session) {\r
- this.session = session;\r
- }\r
-\r
- public void dispose() {\r
- // JcrUtils.unregisterQuietly(session.getWorkspace(), resultsObserver);\r
- JcrUtils.logoutQuietly(session);\r
- super.dispose();\r
- }\r
-\r
- public void setRepository(Repository repository) {\r
- try {\r
- session = repository.login();\r
- } catch (RepositoryException re) {\r
- throw new SlcException("Unable to log in Repository " + repository,\r
- re);\r
- }\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.slc.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