From: Mathieu Baudier Date: Tue, 25 Nov 2014 12:51:35 +0000 (+0000) Subject: New project conventions X-Git-Tag: argeo-commons-2.1.30~524 X-Git-Url: http://git.argeo.org/?a=commitdiff_plain;h=e61dd9dda88354091625cca85aa7c96d196688b3;p=lgpl%2Fargeo-commons.git New project conventions git-svn-id: https://svn.argeo.org/commons/trunk@7524 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc --- diff --git a/org.argeo.eclipse.ui/.classpath b/org.argeo.eclipse.ui/.classpath index a50743442..d2953a684 100644 --- a/org.argeo.eclipse.ui/.classpath +++ b/org.argeo.eclipse.ui/.classpath @@ -1,7 +1,9 @@ - - > - - + + + + diff --git a/org.argeo.eclipse.ui/.settings/org.eclipse.jdt.core.prefs b/org.argeo.eclipse.ui/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index f441c9045..000000000 --- a/org.argeo.eclipse.ui/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -#Thu Jul 29 10:54:11 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.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 diff --git a/org.argeo.eclipse.ui/.settings/org.eclipse.pde.core.prefs b/org.argeo.eclipse.ui/.settings/org.eclipse.pde.core.prefs deleted file mode 100644 index 8e36e3304..000000000 --- a/org.argeo.eclipse.ui/.settings/org.eclipse.pde.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Thu Jul 29 11:00:39 CEST 2010 -eclipse.preferences.version=1 -resolve.requirebundle=false diff --git a/org.argeo.eclipse.ui/bnd.bnd b/org.argeo.eclipse.ui/bnd.bnd new file mode 100644 index 000000000..e69de29bb diff --git a/org.argeo.eclipse.ui/build.properties b/org.argeo.eclipse.ui/build.properties index 5fc538bc8..fd806ca05 100644 --- a/org.argeo.eclipse.ui/build.properties +++ b/org.argeo.eclipse.ui/build.properties @@ -1,4 +1,2 @@ -source.. = src/main/java/ -output.. = target/classes/ -bin.includes = META-INF/,\ - . +source.. = src/ +output.. = bin/ diff --git a/org.argeo.eclipse.ui/pom.xml b/org.argeo.eclipse.ui/pom.xml index 29e94fc0b..0147c6e31 100644 --- a/org.argeo.eclipse.ui/pom.xml +++ b/org.argeo.eclipse.ui/pom.xml @@ -13,18 +13,6 @@ jar - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.maven.plugins - maven-source-plugin - - - org.apache.maven.plugins - maven-jar-plugin - org.apache.felix maven-bundle-plugin @@ -87,6 +75,5 @@ org.argeo.tp slf4j.org.apache.commons.logging - \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/ApplicationContextTracker.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/ApplicationContextTracker.java deleted file mode 100644 index 070c70826..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/ApplicationContextTracker.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.spring; - -import static java.text.MessageFormat.format; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.core.runtime.Platform; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.util.tracker.ServiceTracker; -import org.springframework.context.ApplicationContext; - -/** - * Tracks Spring application context published as services. - * - * @author Heiko Seeberger - * @author Mathieu Baudier - */ -class ApplicationContextTracker { - private final static Log log = LogFactory - .getLog(ApplicationContextTracker.class); - - private static final String FILTER = "(&(objectClass=org.springframework.context.ApplicationContext)" //$NON-NLS-1$ - + "(org.springframework.context.service.name={0}))"; //$NON-NLS-1$ - - public final static String APPLICATION_CONTEXT_TRACKER_TIMEOUT = "org.argeo.eclipse.spring.applicationContextTrackerTimeout"; - - private static Long defaultTimeout = Long.parseLong(System.getProperty( - APPLICATION_CONTEXT_TRACKER_TIMEOUT, "30000")); - - private ServiceTracker applicationContextServiceTracker; - - /** - * @param contributorBundle - * OSGi bundle for which the Spring application context is to be - * tracked. Must not be null! - * @param factoryBundleContext - * BundleContext object which can be used to track services - * @throws IllegalArgumentException - * if the given bundle is null. - */ - public ApplicationContextTracker(final Bundle contributorBundle, - final BundleContext factoryBundleContext) { - final String filter = format(FILTER, - contributorBundle.getSymbolicName()); - try { - applicationContextServiceTracker = new ServiceTracker( - factoryBundleContext, FrameworkUtil.createFilter(filter), - null); - // applicationContextServiceTracker.open(); - } catch (final InvalidSyntaxException e) { - e.printStackTrace(); - } - } - - public void open() { - if (applicationContextServiceTracker != null) { - applicationContextServiceTracker.open(); - } - } - - public void close() { - if (applicationContextServiceTracker != null) { - applicationContextServiceTracker.close(); - } - } - - public ApplicationContext getApplicationContext() { - ApplicationContext applicationContext = null; - if (applicationContextServiceTracker != null) { - try { - applicationContext = (ApplicationContext) applicationContextServiceTracker - .waitForService(defaultTimeout); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return applicationContext; - } - - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } - - static ApplicationContext getApplicationContext(String bundleSymbolicName) { - Bundle contributorBundle = Platform.getBundle(bundleSymbolicName); - return getApplicationContext(contributorBundle); - } - - static ApplicationContext getApplicationContext( - final Bundle contributorBundle) { - if (log.isTraceEnabled()) - log.trace("Get application context for bundle " + contributorBundle); - - // Start if not yet started (also if in STARTING state, may be lazy) - if (contributorBundle.getState() != Bundle.ACTIVE) { - if (log.isTraceEnabled()) - log.trace("Starting bundle: " - + contributorBundle.getSymbolicName()); - // Thread startBundle = new Thread("Start bundle " - // + contributorBundle.getSymbolicName()) { - // public void run() { - try { - contributorBundle.start(); - } catch (BundleException e) { - log.error("Cannot start bundle " + contributorBundle, e); - } - // } - // }; - // startBundle.start(); - // try { - // startBundle.join(10 * 1000l); - // } catch (InterruptedException e) { - // // silent - // } - } - - final ApplicationContextTracker applicationContextTracker = new ApplicationContextTracker( - contributorBundle, contributorBundle.getBundleContext()); - ApplicationContext applicationContext = null; - try { - applicationContextTracker.open(); - applicationContext = applicationContextTracker - .getApplicationContext(); - } finally { - applicationContextTracker.close(); - } - return applicationContext; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringCommandHandler.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringCommandHandler.java deleted file mode 100644 index 4c7a152df..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringCommandHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.spring; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.argeo.ArgeoException; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.IHandler; -import org.eclipse.core.commands.IHandlerListener; -import org.springframework.context.ApplicationContext; - -/** Allows to declare Eclipse commands as Spring beans */ -public class SpringCommandHandler implements IHandler { - private final static Log log = LogFactory - .getLog(SpringCommandHandler.class); - - public void addHandlerListener(IHandlerListener handlerListener) { - } - - public void dispose() { - } - - public Object execute(ExecutionEvent event) throws ExecutionException { - String commandId = event.getCommand().getId(); - String bundleSymbolicName = commandId.substring(0, - commandId.lastIndexOf('.')); - try { - if (log.isTraceEnabled()) - log.trace("Execute " + event + " via spring command handler " - + this); - // TODO: make it more flexible and robust - ApplicationContext applicationContext = ApplicationContextTracker - .getApplicationContext(bundleSymbolicName); - if (applicationContext == null) - throw new ArgeoException("No application context found for " - + bundleSymbolicName); - - // retrieve the command via its id - String beanName = event.getCommand().getId(); - - if (!applicationContext.containsBean(beanName)) { - if (beanName.startsWith(bundleSymbolicName)) - beanName = beanName - .substring(bundleSymbolicName.length() + 1); - } - - if (!applicationContext.containsBean(beanName)) - throw new ExecutionException("No bean found with name " - + beanName + " in bundle " + bundleSymbolicName); - Object bean = applicationContext.getBean(beanName); - - if (!(bean instanceof IHandler)) - throw new ExecutionException("Bean with name " + beanName - + " and class " + bean.getClass() - + " does not implement the IHandler interface."); - - IHandler handler = (IHandler) bean; - return handler.execute(event); - } catch (Exception e) { - // TODO: use eclipse error management - // log.error(e); - throw new ExecutionException("Cannot execute Spring command " - + commandId + " in bundle " + bundleSymbolicName, e); - } - } - - public boolean isEnabled() { - return true; - } - - public boolean isHandled() { - return true; - } - - public void removeHandlerListener(IHandlerListener handlerListener) { - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringExtensionFactory.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringExtensionFactory.java deleted file mode 100644 index 7a0486fd2..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/spring/SpringExtensionFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.spring; - -import org.argeo.ArgeoException; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExecutableExtension; -import org.eclipse.core.runtime.IExecutableExtensionFactory; -import org.eclipse.core.runtime.IExtension; -import org.springframework.context.ApplicationContext; - -/** - * The Spring Extension Factory builds a bridge between the Eclipse Extension - * Registry and the Spring Framework (especially Spring Dynamic Modules). - * - * It allows you to define your extension as a spring bean within the spring - * application context of your bundle. If you would like to use this bean as an - * instance of an extension (an Eclipse RCP view, for example) you define the - * extension with this spring extension factory as the class to be created. - * - * To let the spring extension factory pick the right bean from your application - * context you need to set the bean id to the same value as the id of the view - * within the view definition, for example. This is important if your extension - * definition contains more than one element, where each element has its own id. - * - * If the extension definition elements themselves have no id attribute the - * spring extension factory uses the id of the extension itself to identify the - * bean. - * - * original code from: Blog entry - * - * @author Martin Lippert - * @author mbaudier - */ -public class SpringExtensionFactory implements IExecutableExtensionFactory, - IExecutableExtension { - - private Object bean; - - public Object create() throws CoreException { - if (bean == null) - throw new ArgeoException("No underlying bean for extension"); - return bean; - } - - public void setInitializationData(IConfigurationElement config, - String propertyName, Object data) throws CoreException { - String bundleSymbolicName = config.getContributor().getName(); - ApplicationContext applicationContext = ApplicationContextTracker - .getApplicationContext(bundleSymbolicName); - if (applicationContext == null) - throw new ArgeoException( - "Cannot find application context for bundle " - + bundleSymbolicName); - - String beanName = getBeanName(data, config); - if (beanName == null) - throw new ArgeoException("Cannot find bean name for extension " - + config); - - if (!applicationContext.containsBean(beanName)) { - if (beanName.startsWith(bundleSymbolicName)) - beanName = beanName.substring(bundleSymbolicName.length() + 1); - } - - if (!applicationContext.containsBean(beanName)) - throw new ArgeoException("No bean with name '" + beanName + "'"); - - this.bean = applicationContext.getBean(beanName); - if (this.bean instanceof IExecutableExtension) { - ((IExecutableExtension) this.bean).setInitializationData(config, - propertyName, data); - } - } - - private String getBeanName(Object data, IConfigurationElement config) { - - // try the specific bean id the extension defines - if (data != null && data.toString().length() > 0) { - return data.toString(); - } - - // try the id of the config element - if (config.getAttribute("id") != null) { - return config.getAttribute("id"); - } - - // try the id of the extension element itself - if (config.getParent() != null - && config.getParent() instanceof IExtension) { - IExtension extensionDefinition = (IExtension) config.getParent(); - return extensionDefinition.getSimpleIdentifier(); - } - - return null; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/AbstractTreeContentProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/AbstractTreeContentProvider.java deleted file mode 100644 index 6b86676b4..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/AbstractTreeContentProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; - -/** - * Tree content provider dealing with tree objects and providing reasonable - * defaults. - */ -public abstract class AbstractTreeContentProvider implements - ITreeContentProvider { - private static final long serialVersionUID = 8246126401957763868L; - - /** Does nothing */ - public void dispose() { - } - - /** Does nothing */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - public Object[] getChildren(Object element) { - if (element instanceof TreeParent) { - return ((TreeParent) element).getChildren(); - } - return new Object[0]; - } - - public Object getParent(Object element) { - if (element instanceof TreeParent) { - return ((TreeParent) element).getParent(); - } - return null; - } - - public boolean hasChildren(Object element) { - if (element instanceof TreeParent) { - return ((TreeParent) element).hasChildren(); - } - return false; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ArgeoUiPlugin.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ArgeoUiPlugin.java deleted file mode 100644 index 6befdf7d4..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ArgeoUiPlugin.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.core.runtime.ILogListener; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -/** - * The activator class controls the plug-in life cycle - */ -public class ArgeoUiPlugin extends AbstractUIPlugin implements ILogListener { - public static final String PLUGIN_ID = "org.argeo.eclipse.ui"; - private final static Log log = LogFactory.getLog(ArgeoUiPlugin.class); - // The shared instance - private static ArgeoUiPlugin plugin; - - public void start(BundleContext context) throws Exception { - super.start(context); - // weirdly, the start method is called twice... - if (plugin == null) { - plugin = this; - Platform.addLogListener(this); - log.debug("Eclipse logging now directed to standard logging"); - } - } - - public void stop(BundleContext context) throws Exception { - try { - // weirdly, the stop method is called twice... - if (plugin != null) { - Platform.removeLogListener(this); - log.debug("Eclipse logging not directed anymore to standard logging"); - plugin = null; - } - } finally { - super.stop(context); - } - } - - /** Returns the shared instance */ - public static ArgeoUiPlugin getDefault() { - return plugin; - } - - public void logging(IStatus status, String plugin) { - Log pluginLog = LogFactory.getLog(plugin); - Integer severity = status.getSeverity(); - if (severity == IStatus.ERROR) - pluginLog.error(status.getMessage(), status.getException()); - else if (severity == IStatus.WARNING) - pluginLog.warn(status.getMessage(), status.getException()); - else if (severity == IStatus.INFO) - pluginLog.info(status.getMessage(), status.getException()); - else if (severity == IStatus.CANCEL) - if (pluginLog.isDebugEnabled()) - pluginLog.debug(status.getMessage(), status.getException()); - - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ColumnViewerComparator.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ColumnViewerComparator.java deleted file mode 100644 index 8db5d4fe8..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ColumnViewerComparator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import java.util.Comparator; - -import org.eclipse.jface.viewers.ColumnViewer; -import org.eclipse.jface.viewers.TableViewerColumn; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; - -/** Generic column viewer sorter */ -public class ColumnViewerComparator extends ViewerComparator { - private static final long serialVersionUID = -2266218906355859909L; - - public static final int ASC = 1; - - public static final int NONE = 0; - - public static final int DESC = -1; - - private int direction = 0; - - private TableViewerColumn column; - - private ColumnViewer viewer; - - public ColumnViewerComparator(TableViewerColumn column, - Comparator comparator) { - super(comparator); - this.column = column; - this.viewer = column.getViewer(); - this.column.getColumn().addSelectionListener(new SelectionAdapter() { - private static final long serialVersionUID = 7586796298965472189L; - - public void widgetSelected(SelectionEvent e) { - if (ColumnViewerComparator.this.viewer.getComparator() != null) { - if (ColumnViewerComparator.this.viewer.getComparator() == ColumnViewerComparator.this) { - int tdirection = ColumnViewerComparator.this.direction; - - if (tdirection == ASC) { - setSortDirection(DESC); - } else if (tdirection == DESC) { - setSortDirection(NONE); - } - } else { - setSortDirection(ASC); - } - } else { - setSortDirection(ASC); - } - } - }); - } - - private void setSortDirection(int direction) { - if (direction == NONE) { - column.getColumn().getParent().setSortColumn(null); - column.getColumn().getParent().setSortDirection(SWT.NONE); - viewer.setComparator(null); - } else { - column.getColumn().getParent().setSortColumn(column.getColumn()); - this.direction = direction; - - if (direction == ASC) { - column.getColumn().getParent().setSortDirection(SWT.DOWN); - } else { - column.getColumn().getParent().setSortDirection(SWT.UP); - } - - if (viewer.getComparator() == this) { - viewer.refresh(); - } else { - viewer.setComparator(this); - } - - } - } - - @SuppressWarnings("unchecked") - public int compare(Viewer viewer, Object e1, Object e2) { - return direction * getComparator().compare((T) e1, (T) e2); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseArgeoMonitor.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseArgeoMonitor.java deleted file mode 100644 index 7c0b39884..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseArgeoMonitor.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.argeo.ArgeoMonitor; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * Wraps an Eclipse {@link IProgressMonitor} so that it can be passed to - * framework agnostic Argeo routines. - */ -public class EclipseArgeoMonitor implements ArgeoMonitor { - private final IProgressMonitor progressMonitor; - - public EclipseArgeoMonitor(IProgressMonitor progressMonitor) { - this.progressMonitor = progressMonitor; - } - - public void beginTask(String name, int totalWork) { - progressMonitor.beginTask(name, totalWork); - } - - public void done() { - progressMonitor.done(); - } - - public boolean isCanceled() { - return progressMonitor.isCanceled(); - } - - public void setCanceled(boolean value) { - progressMonitor.setCanceled(value); - } - - public void setTaskName(String name) { - progressMonitor.setTaskName(name); - } - - public void subTask(String name) { - progressMonitor.subTask(name); - } - - public void worked(int work) { - progressMonitor.worked(work); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseUiUtils.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseUiUtils.java deleted file mode 100644 index 8e1c7e632..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/EclipseUiUtils.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; - -/** Utilities to simplify UI development. */ -public class EclipseUiUtils { - /** - * Create a label and a text field for a grid layout, the text field grabing - * excess horizontal - * - * @param parent - * the parent composite - * @param label - * the lable to display - * @param modifyListener - * a {@link ModifyListener} to listen on events on the text, can - * be null - * @return the created text - * - */ - // FIXME why was this deprecated. - // * @ deprecated use { @ link #createGridLT(Composite, String)} instead - // @ Deprecated - public static Text createGridLT(Composite parent, String label, - ModifyListener modifyListener) { - Label lbl = new Label(parent, SWT.LEAD); - lbl.setText(label); - lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - Text txt = new Text(parent, SWT.LEAD | SWT.BORDER); - txt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (modifyListener != null) - txt.addModifyListener(modifyListener); - return txt; - } - - /** - * Create a label and a text field for a grid layout, the text field - * grabbing excess horizontal - */ - public static Text createGridLT(Composite parent, String label) { - return createGridLT(parent, label, null); - } - - /** - * Creates one label and a text field not editable with background color of - * the parent (like a label but with selectable text) - */ - public static Text createGridLL(Composite parent, String label, String text) { - Text txt = createGridLT(parent, label); - txt.setText(text); - txt.setEditable(false); - txt.setBackground(parent.getBackground()); - return txt; - } - - /** - * Create a label and a text field with password display for a grid layout, - * the text field grabbing excess horizontal - */ - public static Text createGridLP(Composite parent, String label, - ModifyListener modifyListener) { - Label lbl = new Label(parent, SWT.LEAD); - lbl.setText(label); - lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - Text txt = new Text(parent, SWT.LEAD | SWT.BORDER | SWT.PASSWORD); - txt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - if (txt != null) - txt.addModifyListener(modifyListener); - return txt; - } - - /** Shortcut to retrieve default italic font from display */ - public static Font getItalicFont(Composite parent) { - return JFaceResources.getFontRegistry().defaultFontDescriptor() - .setStyle(SWT.ITALIC).createFont(parent.getDisplay()); - } - - /** Shortcut to retrieve default bold font from display */ - public static Font getBoldFont(Composite parent) { - return JFaceResources.getFontRegistry().defaultFontDescriptor() - .setStyle(SWT.BOLD).createFont(parent.getDisplay()); - } - - /** Shortcut to retrieve default bold italic font from display */ - public static Font getBoldItalicFont(Composite parent) { - return JFaceResources.getFontRegistry().defaultFontDescriptor() - .setStyle(SWT.BOLD | SWT.ITALIC) - .createFont(parent.getDisplay()); - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/Error.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/Error.java deleted file mode 100644 index 03b047001..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/Error.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.eclipse.swt.widgets.Shell; - -/** - * @deprecated deprecated because of poor naming, use {@link ErrorFeedback} - * instead - */ -@SuppressWarnings("serial") -@Deprecated -public class Error extends ErrorFeedback { - - public Error(Shell parentShell, String message, Throwable e) { - super(parentShell, message, e); - // TODO Auto-generated constructor stub - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ErrorFeedback.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ErrorFeedback.java deleted file mode 100644 index 895e8b866..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/ErrorFeedback.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.PlatformUI; - -/** Generic error dialog to be used in try/catch blocks */ -@SuppressWarnings("serial") -public class ErrorFeedback extends TitleAreaDialog { - private final static Log log = LogFactory.getLog(ErrorFeedback.class); - - private final String message; - private final Throwable exception; - - public static void show(String message, Throwable e) { - // rethrow ThreaDeath in order to make sure that RAP will properly clean - // up the UI thread - if (e instanceof ThreadDeath) - throw (ThreadDeath) e; - - new ErrorFeedback(getDisplay().getActiveShell(), message, e).open(); - } - - public static void show(String message) { - new ErrorFeedback(getDisplay().getActiveShell(), message, null).open(); - } - - /** Tries to find a display */ - private static Display getDisplay() { - try { - Display display = PlatformUI.getWorkbench().getDisplay(); - if (display != null) - return display; - else - return Display.getDefault(); - } catch (Exception e) { - return Display.getCurrent(); - } - } - - public ErrorFeedback(Shell parentShell, String message, Throwable e) { - super(parentShell); - this.message = message; - this.exception = e; - log.error(message, e); - } - - protected Point getInitialSize() { - if (exception != null) - return new Point(800, 600); - else - return new Point(400, 300); - } - - @Override - 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, true)); - - setMessage(message != null ? message - + (exception != null ? ": " + exception.getMessage() : "") - : exception != null ? exception.getMessage() : "Unkown Error", - IMessageProvider.ERROR); - - if (exception != null) { - Text stack = new Text(composite, SWT.MULTI | SWT.LEAD | SWT.BORDER - | SWT.V_SCROLL | SWT.H_SCROLL); - stack.setEditable(false); - stack.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - StringWriter sw = new StringWriter(); - exception.printStackTrace(new PrintWriter(sw)); - stack.setText(sw.toString()); - } - - parent.pack(); - return composite; - } - - protected void configureShell(Shell shell) { - super.configureShell(shell); - shell.setText("Error"); - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/FileProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/FileProvider.java deleted file mode 100644 index 91ca71969..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/FileProvider.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import java.io.InputStream; - -/** - * Used for file download : subclasses must implement model specific methods to - * get a byte array representing a file given is ID. - */ -@Deprecated -public interface FileProvider { - - public byte[] getByteArrayFileFromId(String fileId); - - public InputStream getInputStreamFromFileId(String fileId); - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/GenericTableComparator.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/GenericTableComparator.java deleted file mode 100644 index a4179cbee..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/GenericTableComparator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; - -public abstract class GenericTableComparator extends ViewerComparator { - private static final long serialVersionUID = -1175894935075325810L; - protected int propertyIndex; - public static final int ASCENDING = 0, DESCENDING = 1; - protected int direction = DESCENDING; - - /** - * Creates an instance of a sorter for TableViewer. - * - * @param defaultColumn - * the default sorter column - */ - - public GenericTableComparator(int defaultColumnIndex, int direction) { - propertyIndex = defaultColumnIndex; - this.direction = direction; - } - - 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; - direction = DESCENDING; - } - } - - /** - * Must be Overriden in each view. - */ - public abstract int compare(Viewer viewer, Object e1, Object e2); -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/TreeParent.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/TreeParent.java deleted file mode 100644 index 2dfd2e60c..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/TreeParent.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui; - -import java.util.ArrayList; -import java.util.List; - -/** Parent / children semantic to be used for simple UI Tree structure */ -public class TreeParent { - private String name; - private TreeParent parent; - - private List children; - - /** - * Unique id within the context of a tree display. If set, equals() and - * hashCode() methods will be based on it - */ - private String path = null; - - /** False until at least one child has been added, then true until cleared */ - private boolean loaded = false; - - public TreeParent(String name) { - this.name = name; - children = new ArrayList(); - } - - public synchronized void addChild(Object child) { - loaded = true; - children.add(child); - if (child instanceof TreeParent) - ((TreeParent) child).setParent(this); - } - - /** - * Remove this child. The child is disposed. - */ - public synchronized void removeChild(Object child) { - children.remove(child); - if (child instanceof TreeParent) { - ((TreeParent) child).dispose(); - } - } - - public synchronized void clearChildren() { - for (Object obj : children) { - if (obj instanceof TreeParent) - ((TreeParent) obj).dispose(); - } - loaded = false; - children.clear(); - } - - /** - * If overridden, super.dispose() must be called, typically - * after custom cleaning. - */ - public synchronized void dispose() { - clearChildren(); - parent = null; - children = null; - } - - public synchronized Object[] getChildren() { - return children.toArray(new Object[children.size()]); - } - - @SuppressWarnings("unchecked") - public synchronized List getChildrenOfType(Class clss) { - List lst = new ArrayList(); - for (Object obj : children) { - if (clss.isAssignableFrom(obj.getClass())) - lst.add((T) obj); - } - return lst; - } - - public synchronized boolean hasChildren() { - return children.size() > 0; - } - - public Object getChildByName(String name) { - for (Object child : children) { - if (child.toString().equals(name)) - return child; - } - return null; - } - - public synchronized Boolean isLoaded() { - return loaded; - } - - public String getName() { - return name; - } - - public void setParent(TreeParent parent) { - this.parent = parent; - if (parent != null && parent.path != null) - this.path = parent.path + '/' + name; - else - this.path = '/' + name; - } - - public TreeParent getParent() { - return parent; - } - - public String toString() { - return getName(); - } - - public int compareTo(TreeParent o) { - return name.compareTo(o.name); - } - - @Override - public int hashCode() { - if (path != null) - return path.hashCode(); - else - return name.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (path != null && obj instanceof TreeParent) - return path.equals(((TreeParent) obj).path); - else - return name.equals(obj.toString()); - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/Error.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/Error.java deleted file mode 100644 index 918bfd244..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/Error.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.dialogs; - -import org.eclipse.swt.widgets.Shell; - -/** - * Generic error dialog to be used in try/catch blocks - * - * @deprecated use {@link org.argeo.eclipse.ui.ErrorFeedback} instead. - */ -public class Error extends org.argeo.eclipse.ui.ErrorFeedback { - private static final long serialVersionUID = -93864960090248736L; - - public Error(Shell parentShell, String message, Throwable e) { - super(parentShell, message, e); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/SingleValue.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/SingleValue.java deleted file mode 100644 index b58f44694..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/dialogs/SingleValue.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.dialogs; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; - -/** Dialog retrieve a single value. */ -public class SingleValue extends TitleAreaDialog { - private static final long serialVersionUID = 2843538207460082349L; - - private Text valueT; - private String value; - private final String title, message, label; - private final Boolean multiline; - - public static String ask(String label, String message) { - SingleValue svd = new SingleValue(label, message); - if (svd.open() == Dialog.OK) - return svd.getString(); - else - return null; - } - - public static Long askLong(String label, String message) { - SingleValue svd = new SingleValue(label, message); - if (svd.open() == Dialog.OK) - return svd.getLong(); - else - return null; - } - - public static Double askDouble(String label, String message) { - SingleValue svd = new SingleValue(label, message); - if (svd.open() == Dialog.OK) - return svd.getDouble(); - else - return null; - } - - public SingleValue(String label, String message) { - this(Display.getDefault().getActiveShell(), label, message, label, - false); - } - - public SingleValue(Shell parentShell, String title, String message, - String label, Boolean multiline) { - super(parentShell); - this.title = title; - this.message = message; - this.label = label; - this.multiline = multiline; - } - - 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)); - valueT = createLT(composite, label); - - setMessage(message, IMessageProvider.NONE); - - parent.pack(); - return composite; - } - - @Override - protected void okPressed() { - value = valueT.getText(); - 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 - | (multiline ? SWT.MULTI : SWT.NONE)); - text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - return text; - } - - protected void configureShell(Shell shell) { - super.configureShell(shell); - shell.setText(title); - } - - public String getString() { - return value; - } - - public Long getLong() { - return Long.valueOf(getString()); - } - - public Double getDouble() { - return Double.valueOf(getString()); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java deleted file mode 100644 index ef2b8a845..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -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.ArgeoException; -import org.argeo.eclipse.ui.AbstractTreeContentProvider; - -/** Canonic implementation of tree content provider manipulating JCR nodes. */ -public abstract class AbstractNodeContentProvider extends - AbstractTreeContentProvider { - private final static Log log = LogFactory - .getLog(AbstractNodeContentProvider.class); - - private Session session; - - public AbstractNodeContentProvider(Session session) { - this.session = session; - } - - /** - * Whether this path is a base path (and thus has no parent). By default it - * returns true if path is '/' (root node) - */ - protected Boolean isBasePath(String path) { - // root node - return path.equals("/"); - } - - @Override - public Object[] getChildren(Object element) { - Object[] children; - if (element instanceof Node) { - try { - Node node = (Node) element; - children = getChildren(node); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get children of " + element, e); - } - } else if (element instanceof WrappedNode) { - WrappedNode wrappedNode = (WrappedNode) element; - try { - children = getChildren(wrappedNode.getNode()); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get children of " - + wrappedNode, e); - } - } else if (element instanceof NodesWrapper) { - NodesWrapper node = (NodesWrapper) element; - children = node.getChildren(); - } else { - children = super.getChildren(element); - } - - children = sort(element, children); - return children; - } - - /** Do not sort by default. To be overidden to provide custom sort. */ - protected Object[] sort(Object parent, Object[] children) { - return children; - } - - /** - * To be overridden in order to filter out some nodes. Does nothing by - * default. The provided list is a temporary one and can thus be modified - * directly . (e.g. via an iterator) - */ - protected List filterChildren(List children) - throws RepositoryException { - return children; - } - - protected Object[] getChildren(Node node) throws RepositoryException { - List nodes = new ArrayList(); - for (NodeIterator nit = node.getNodes(); nit.hasNext();) - nodes.add(nit.nextNode()); - nodes = filterChildren(nodes); - return nodes.toArray(); - } - - @Override - public Object getParent(Object element) { - if (element instanceof Node) { - Node node = (Node) element; - try { - String path = node.getPath(); - if (isBasePath(path)) - return null; - else - return node.getParent(); - } catch (RepositoryException e) { - log.warn("Cannot get parent of " + element + ": " + e); - return null; - } - } else if (element instanceof WrappedNode) { - WrappedNode wrappedNode = (WrappedNode) element; - return wrappedNode.getParent(); - } else if (element instanceof NodesWrapper) { - NodesWrapper nodesWrapper = (NodesWrapper) element; - return this.getParent(nodesWrapper.getNode()); - } - return super.getParent(element); - } - - @Override - public boolean hasChildren(Object element) { - try { - if (element instanceof Node) { - Node node = (Node) element; - return node.hasNodes(); - } else if (element instanceof WrappedNode) { - WrappedNode wrappedNode = (WrappedNode) element; - return wrappedNode.getNode().hasNodes(); - } else if (element instanceof NodesWrapper) { - NodesWrapper nodesWrapper = (NodesWrapper) element; - return nodesWrapper.hasChildren(); - } - - } catch (RepositoryException e) { - throw new ArgeoException("Cannot check whether " + element - + " has children", e); - } - return super.hasChildren(element); - } - - public Session getSession() { - return session; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java deleted file mode 100644 index 100ceb444..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import java.util.ArrayList; -import java.util.List; - -import javax.jcr.RepositoryException; -import javax.jcr.observation.Event; -import javax.jcr.observation.EventIterator; -import javax.jcr.observation.EventListener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.argeo.ArgeoException; -import org.eclipse.swt.widgets.Display; - -/** {@link EventListener} which simplifies running actions within the UI thread. */ -public abstract class AsyncUiEventListener implements EventListener { -// private final static Log logSuper = LogFactory -// .getLog(AsyncUiEventListener.class); - private final Log logThis = LogFactory.getLog(getClass()); - - private final Display display; - - public AsyncUiEventListener(Display display) { - super(); - this.display = display; - } - - /** Called asynchronously in the UI thread. */ - protected abstract void onEventInUiThread(List events) - throws RepositoryException; - - /** - * Whether these events should be processed in the UI or skipped with no UI - * job created. - */ - protected Boolean willProcessInUiThread(List events) - throws RepositoryException { - return true; - } - - protected Log getLog() { - return logThis; - } - - public final void onEvent(final EventIterator eventIterator) { - final List events = new ArrayList(); - while (eventIterator.hasNext()) - events.add(eventIterator.nextEvent()); - - if (logThis.isTraceEnabled()) - logThis.trace("Received " + events.size() + " events"); - - try { - if (!willProcessInUiThread(events)) - return; - } catch (RepositoryException e) { - throw new ArgeoException("Cannot test skip events " + events, e); - } - -// Job job = new Job("JCR Events") { -// protected IStatus run(IProgressMonitor monitor) { -// if (display.isDisposed()) { -// logSuper.warn("Display is disposed cannot update UI"); -// return Status.CANCEL_STATUS; -// } - - display.asyncExec(new Runnable() { - public void run() { - try { - onEventInUiThread(events); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot process events " - + events, e); - } - } - }); - -// return Status.OK_STATUS; -// } -// }; -// job.schedule(); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java deleted file mode 100644 index 76fac1256..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import javax.jcr.Node; -import javax.jcr.Property; -import javax.jcr.RepositoryException; -import javax.jcr.nodetype.NodeType; - -import org.argeo.ArgeoException; -import org.argeo.jcr.ArgeoTypes; -import org.eclipse.jface.viewers.ColumnLabelProvider; -import org.eclipse.swt.graphics.Image; - -/** Provides reasonable overridable defaults for know JCR types. */ -public class DefaultNodeLabelProvider extends ColumnLabelProvider { - // Images - /** - * @deprecated Use {@link JcrImages#NODE} instead - */ - public final static Image NODE = JcrImages.NODE; - /** - * @deprecated Use {@link JcrImages#FOLDER} instead - */ - public final static Image FOLDER = JcrImages.FOLDER; - /** - * @deprecated Use {@link JcrImages#FILE} instead - */ - public final static Image FILE = JcrImages.FILE; - /** - * @deprecated Use {@link JcrImages#BINARY} instead - */ - public final static Image BINARY = JcrImages.BINARY; - /** - * @deprecated Use {@link JcrImages#HOME} instead - */ - public final static Image HOME = JcrImages.HOME; - - public String getText(Object element) { - try { - if (element instanceof Node) { - return getText((Node) element); - } else if (element instanceof WrappedNode) { - return getText(((WrappedNode) element).getNode()); - } else if (element instanceof NodesWrapper) { - return getText(((NodesWrapper) element).getNode()); - } - return super.getText(element); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get text for of " + element, e); - } - } - - 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 - return node.getName(); - } - - @Override - public Image getImage(Object element) { - try { - if (element instanceof Node) { - return getImage((Node) element); - } else if (element instanceof WrappedNode) { - return getImage(((WrappedNode) element).getNode()); - } else if (element instanceof NodesWrapper) { - return getImage(((NodesWrapper) element).getNode()); - } - } catch (RepositoryException e) { - throw new ArgeoException("Cannot retrieve image for " + element, e); - } - return super.getImage(element); - } - - protected Image getImage(Node node) throws RepositoryException { - // optimized order - if (node.getPrimaryNodeType().isNodeType(NodeType.NT_FILE)) - return JcrImages.FILE; - else if (node.getPrimaryNodeType().isNodeType(NodeType.NT_FOLDER)) - return JcrImages.FOLDER; - else if (node.getPrimaryNodeType().isNodeType(NodeType.NT_RESOURCE)) - return JcrImages.BINARY; - else if (node.isNodeType(ArgeoTypes.ARGEO_USER_HOME)) - return JcrImages.HOME; - else - return JcrImages.NODE; - } - - @Override - public String getToolTipText(Object element) { - try { - if (element instanceof Node) { - return getToolTipText((Node) element); - } else if (element instanceof WrappedNode) { - return getToolTipText(((WrappedNode) element).getNode()); - } else if (element instanceof NodesWrapper) { - return getToolTipText(((NodesWrapper) element).getNode()); - } - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get tooltip for " + element, e); - } - return super.getToolTipText(element); - } - - protected String getToolTipText(Node node) throws RepositoryException { - return null; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrImages.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrImages.java deleted file mode 100644 index 255ea7a25..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrImages.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import org.eclipse.swt.graphics.Image; - -/** Shared icons. */ -public class JcrImages { - public final static Image NODE = JcrUiPlugin.getImageDescriptor( - "icons/node.gif").createImage(); - public final static Image FOLDER = JcrUiPlugin.getImageDescriptor( - "icons/folder.gif").createImage(); - public final static Image FILE = JcrUiPlugin.getImageDescriptor( - "icons/file.gif").createImage(); - public final static Image BINARY = JcrUiPlugin.getImageDescriptor( - "icons/binary.png").createImage(); - public final static Image HOME = JcrUiPlugin.getImageDescriptor( - "icons/home.gif").createImage(); - public final static Image SORT = JcrUiPlugin.getImageDescriptor( - "icons/sort.gif").createImage(); - - public final static Image REPOSITORIES = JcrUiPlugin.getImageDescriptor( - "icons/repositories.gif").createImage(); - public final static Image REPOSITORY_DISCONNECTED = JcrUiPlugin - .getImageDescriptor("icons/repository_disconnected.gif") - .createImage(); - public final static Image REPOSITORY_CONNECTED = JcrUiPlugin - .getImageDescriptor("icons/repository_connected.gif").createImage(); - public final static Image REMOTE_DISCONNECTED = JcrUiPlugin - .getImageDescriptor("icons/remote_disconnected.gif").createImage(); - public final static Image REMOTE_CONNECTED = JcrUiPlugin - .getImageDescriptor("icons/remote_connected.gif").createImage(); - public final static Image WORKSPACE_DISCONNECTED = JcrUiPlugin - .getImageDescriptor("icons/workspace_disconnected.png") - .createImage(); - public final static Image WORKSPACE_CONNECTED = JcrUiPlugin - .getImageDescriptor("icons/workspace_connected.png").createImage(); - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java deleted file mode 100644 index c9777cefd..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Properties; - -import javax.jcr.Node; -import javax.jcr.Property; -import javax.jcr.PropertyIterator; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.version.VersionManager; - -import org.apache.commons.io.IOUtils; -import org.argeo.ArgeoException; -import org.argeo.jcr.ArgeoNames; -import org.argeo.jcr.ArgeoTypes; -import org.argeo.jcr.JcrUtils; -import org.argeo.jcr.UserJcrUtils; -import org.eclipse.jface.preference.PreferenceStore; -import org.eclipse.ui.preferences.ScopedPreferenceStore; -import org.osgi.framework.BundleContext; - -/** - * Persist preferences as key/value pairs under ~/argeo:preferences.
- * TODO: better integrate JCR and Eclipse:
- * - typing
- * - use eclipse preferences
- * - better integrate with {@link ScopedPreferenceStore} provided by RAP - */ -public class JcrPreferenceStore extends PreferenceStore implements ArgeoNames { - private Session session; - private BundleContext bundleContext; - - /** Retrieves the preference node */ - protected Node getPreferenceNode() { - try { - if (session.hasPendingChanges()) - session.save(); - Node userHome = UserJcrUtils.getUserHome(session); - if (userHome == null) - throw new ArgeoException("No user home for " - + session.getUserID()); - Node preferences; - if (!userHome.hasNode(ARGEO_PREFERENCES)) { - preferences = userHome.addNode(ARGEO_PREFERENCES); - preferences.addMixin(ArgeoTypes.ARGEO_PREFERENCE_NODE); - session.save(); - } else - preferences = userHome.getNode(ARGEO_PREFERENCES); - - String pluginPreferencesName = bundleContext.getBundle() - .getSymbolicName(); - Node pluginPreferences; - if (!preferences.hasNode(pluginPreferencesName)) { - VersionManager vm = session.getWorkspace().getVersionManager(); - vm.checkout(preferences.getPath()); - pluginPreferences = preferences.addNode(pluginPreferencesName); - pluginPreferences.addMixin(ArgeoTypes.ARGEO_PREFERENCE_NODE); - session.save(); - vm.checkin(preferences.getPath()); - } else - pluginPreferences = preferences.getNode(pluginPreferencesName); - return pluginPreferences; - } catch (RepositoryException e) { - e.printStackTrace(); - JcrUtils.discardQuietly(session); - throw new ArgeoException("Cannot retrieve preferences", e); - } - - } - - @Override - public void load() throws IOException { - ByteArrayOutputStream out = null; - ByteArrayInputStream in = null; - try { - Properties props = new Properties(); - PropertyIterator it = getPreferenceNode().getProperties(); - while (it.hasNext()) { - Property p = it.nextProperty(); - if (!p.isMultiple() && !p.getDefinition().isProtected()) { - props.setProperty(p.getName(), p.getValue().getString()); - } - } - out = new ByteArrayOutputStream(); - props.store(out, ""); - in = new ByteArrayInputStream(out.toByteArray()); - load(in); - } catch (Exception e) { - e.printStackTrace(); - throw new ArgeoException("Cannot load preferences", e); - } finally { - IOUtils.closeQuietly(in); - IOUtils.closeQuietly(out); - } - } - - @Override - public void save() throws IOException { - ByteArrayOutputStream out = null; - ByteArrayInputStream in = null; - Node pluginPreferences = null; - try { - out = new ByteArrayOutputStream(); - save(out, ""); - in = new ByteArrayInputStream(out.toByteArray()); - Properties props = new Properties(); - props.load(in); - pluginPreferences = getPreferenceNode(); - VersionManager vm = pluginPreferences.getSession().getWorkspace() - .getVersionManager(); - vm.checkout(pluginPreferences.getPath()); - for (Object key : props.keySet()) { - String name = key.toString(); - String value = props.getProperty(name); - pluginPreferences.setProperty(name, value); - } - JcrUtils.updateLastModified(pluginPreferences); - pluginPreferences.getSession().save(); - vm.checkin(pluginPreferences.getPath()); - } catch (Exception e) { - JcrUtils.discardUnderlyingSessionQuietly(pluginPreferences); - throw new ArgeoException("Cannot save preferences", e); - } finally { - IOUtils.closeQuietly(in); - IOUtils.closeQuietly(out); - } - } - - public void init() { - try { - load(); - } catch (IOException e) { - throw new ArgeoException("Cannot initialize preference store", e); - } - } - - public void setSession(Session session) { - this.session = session; - } - - public void setBundleContext(BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java deleted file mode 100644 index adfa1a4f4..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import java.util.ResourceBundle; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -public class JcrUiPlugin extends AbstractUIPlugin { - private final static Log log = LogFactory.getLog(JcrUiPlugin.class); - - public final static String ID = "org.argeo.eclipse.ui.jcr"; - - private ResourceBundle messages; - - private static JcrUiPlugin plugin; - - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - messages = ResourceBundle.getBundle("org.argeo.eclipse.ui.jcr"); - } - - public static JcrUiPlugin getDefault() { - return plugin; - } - - public static ImageDescriptor getImageDescriptor(String path) { - return imageDescriptorFromPlugin(ID, path); - } - - /** Returns the internationalized label for the given key */ - public static String getMessage(String key) { - try { - return getDefault().messages.getString(key); - } catch (NullPointerException npe) { - log.warn(key + " not found."); - return key; - } - } - - /** - * Gives access to the internationalization message bundle. Returns null in - * case the ClientUiPlugin is not started (for JUnit tests, by instance) - */ - public static ResourceBundle getMessagesBundle() { - if (getDefault() != null) - // To avoid NPE - return getDefault().messages; - else - return null; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiUtils.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiUtils.java deleted file mode 100644 index 8ee13aab0..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/JcrUiUtils.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.argeo.eclipse.ui.jcr; - -import java.util.Calendar; - -import javax.jcr.Node; -import javax.jcr.PropertyType; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.jcr.lists.NodeViewerComparator; -import org.argeo.eclipse.ui.jcr.lists.RowViewerComparator; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.widgets.Table; - -/** Utility methods to simplify UI development using eclipse and JCR. */ -public class JcrUiUtils { - - /** - * Centralizes management of updating property value. Among other to avoid - * infinite loop when the new value is the same as the ones that is already - * stored in JCR. - * - * @return true if the value as changed - */ - public static boolean setJcrProperty(Node node, String propName, - int propertyType, Object value) { - try { - // int propertyType = getPic().getProperty(propName).getType(); - switch (propertyType) { - case PropertyType.STRING: - if ("".equals((String) value) - && (!node.hasProperty(propName) || node - .hasProperty(propName) - && "".equals(node.getProperty(propName) - .getString()))) - // workaround the fact that the Text widget value cannot be - // set to null - return false; - else if (node.hasProperty(propName) - && node.getProperty(propName).getString() - .equals((String) value)) - // nothing changed yet - return false; - else { - node.setProperty(propName, (String) value); - return true; - } - case PropertyType.BOOLEAN: - if (node.hasProperty(propName) - && node.getProperty(propName).getBoolean() == (Boolean) value) - // nothing changed yet - return false; - else { - node.setProperty(propName, (Boolean) value); - return true; - } - case PropertyType.DATE: - if (node.hasProperty(propName) - && node.getProperty(propName).getDate() - .equals((Calendar) value)) - // nothing changed yet - return false; - else { - node.setProperty(propName, (Calendar) value); - return true; - } - case PropertyType.LONG: - Long lgValue = (Long) value; - - if (lgValue == null) - lgValue = 0L; - - if (node.hasProperty(propName) - && node.getProperty(propName).getLong() == lgValue) - // nothing changed yet - return false; - else { - node.setProperty(propName, lgValue); - return true; - } - - default: - throw new ArgeoException("Unimplemented property save"); - } - } catch (RepositoryException re) { - throw new ArgeoException("Unexpected error while setting property", - re); - } - } - - /** - * Creates a new selection adapter in order to provide sorting abitily on a - * swt table that display a row list - **/ - public static SelectionAdapter getRowSelectionAdapter(final int index, - final int propertyType, final String selectorName, - final String propertyName, final RowViewerComparator comparator, - final TableViewer viewer) { - SelectionAdapter selectionAdapter = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Table table = viewer.getTable(); - comparator.setColumn(propertyType, selectorName, propertyName); - 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; - } - - /** - * Creates a new selection adapter in order to provide sorting abitily on a - * swt table that display a row list - **/ - public static SelectionAdapter getNodeSelectionAdapter(final int index, - final int propertyType, final String propertyName, - final NodeViewerComparator comparator, final TableViewer viewer) { - SelectionAdapter selectionAdapter = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Table table = viewer.getTable(); - comparator.setColumn(propertyType, propertyName); - 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; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodeElementComparer.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodeElementComparer.java deleted file mode 100644 index f284b9c13..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodeElementComparer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; -import org.eclipse.jface.viewers.IElementComparer; - -/** Element comparer for JCR node, to be used in JFace viewers. */ -public class NodeElementComparer implements IElementComparer { - - public boolean equals(Object a, Object b) { - try { - if ((a instanceof Node) && (b instanceof Node)) { - Node nodeA = (Node) a; - Node nodeB = (Node) b; - return nodeA.getIdentifier().equals(nodeB.getIdentifier()); - } else { - return a.equals(b); - } - } catch (RepositoryException e) { - throw new ArgeoException("Cannot compare nodes", e); - } - } - - public int hashCode(Object element) { - try { - if (element instanceof Node) - return ((Node) element).getIdentifier().hashCode(); - return element.hashCode(); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get hash code", e); - } - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodesWrapper.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodesWrapper.java deleted file mode 100644 index dcd3b42f6..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/NodesWrapper.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import java.util.ArrayList; -import java.util.List; - -import javax.jcr.Node; -import javax.jcr.NodeIterator; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; - -/** - * Element of tree which is based on a node, but whose children are not - * necessarily this node children. - */ -public class NodesWrapper { - private final Node node; - - public NodesWrapper(Node node) { - super(); - this.node = node; - } - - protected NodeIterator getNodeIterator() throws RepositoryException { - return node.getNodes(); - } - - protected List getWrappedNodes() throws RepositoryException { - List nodes = new ArrayList(); - for (NodeIterator nit = getNodeIterator(); nit.hasNext();) - nodes.add(new WrappedNode(this, nit.nextNode())); - return nodes; - } - - public Object[] getChildren() { - try { - return getWrappedNodes().toArray(); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get wrapped children", e); - } - } - - /** - * @return true by default because we don't want to compute the wrapped - * nodes twice - */ - public Boolean hasChildren() { - return true; - } - - public Node getNode() { - return node; - } - - @Override - public int hashCode() { - return node.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof NodesWrapper) - return node.equals(((NodesWrapper) obj).getNode()); - else - return false; - } - - public String toString() { - return "nodes wrapper based on " + node; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java deleted file mode 100644 index 0dad19cfe..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.Session; - -import org.argeo.ArgeoException; -import org.argeo.jcr.JcrUtils; - -/** Simple JCR node content provider taking a list of String as base path. */ -public class SimpleNodeContentProvider extends AbstractNodeContentProvider { - private final List basePaths; - private Boolean mkdirs = false; - - public SimpleNodeContentProvider(Session session, String... basePaths) { - this(session, Arrays.asList(basePaths)); - } - - public SimpleNodeContentProvider(Session session, List basePaths) { - super(session); - this.basePaths = basePaths; - } - - @Override - protected Boolean isBasePath(String path) { - if (basePaths.contains(path)) - return true; - return super.isBasePath(path); - } - - public Object[] getElements(Object inputElement) { - try { - List baseNodes = new ArrayList(); - for (String basePath : basePaths) - if (mkdirs && !getSession().itemExists(basePath)) - baseNodes.add(JcrUtils.mkdirs(getSession(), basePath)); - else - baseNodes.add(getSession().getNode(basePath)); - return baseNodes.toArray(); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot get base nodes for " + basePaths, - e); - } - } - - public List getBasePaths() { - return basePaths; - } - - public void setMkdirs(Boolean mkdirs) { - this.mkdirs = mkdirs; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/WrappedNode.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/WrappedNode.java deleted file mode 100644 index c0e197336..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/WrappedNode.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr; - -import javax.jcr.Node; - -/** Wraps a node (created from a {@link NodesWrapper}) */ -public class WrappedNode { - private final NodesWrapper parent; - private final Node node; - - public WrappedNode(NodesWrapper parent, Node node) { - super(); - this.parent = parent; - this.node = node; - } - - public NodesWrapper getParent() { - return parent; - } - - public Node getNode() { - return node; - } - - public String toString() { - return "wrapped " + node; - } - - @Override - public int hashCode() { - return node.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof WrappedNode) - return node.equals(((WrappedNode) obj).getNode()); - else - return false; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java deleted file mode 100644 index 5fc7db031..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.commands; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.nodetype.NodeType; - -import org.argeo.eclipse.ui.ErrorFeedback; -import org.argeo.eclipse.ui.dialogs.SingleValue; -import org.argeo.eclipse.ui.jcr.JcrUiPlugin; -import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.handlers.HandlerUtil; - -/** Adds a node of type nt:folder */ -public class AddFileFolder extends AbstractHandler { - - public Object execute(ExecutionEvent event) throws ExecutionException { - ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) - .getActivePage().getSelection(); - AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil - .getActiveWorkbenchWindow(event).getActivePage() - .findView(HandlerUtil.getActivePartId(event)); - if (selection != null && !selection.isEmpty() - && selection instanceof IStructuredSelection) { - Object obj = ((IStructuredSelection) selection).getFirstElement(); - - if (obj instanceof Node) { - String folderName = SingleValue.ask("Folder name", - "Enter folder name"); - if (folderName != null) { - Node parentNode = (Node) obj; - try { - Node newNode = parentNode.addNode(folderName, - NodeType.NT_FOLDER); - view.nodeAdded(parentNode, newNode); - parentNode.getSession().save(); - } catch (RepositoryException e) { - ErrorFeedback.show("Cannot create folder " + folderName - + " under " + parentNode, e); - } - } - } else { - ErrorFeedback.show(JcrUiPlugin - .getMessage("errorUnvalidNtFolderNodeType")); - } - } - return null; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java deleted file mode 100644 index 168674806..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.commands; - -import java.util.Iterator; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.ErrorFeedback; -import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.handlers.HandlerUtil; - -/** - * Deletes the selected nodes and refresh the corresponding AbstractJcrView. - * Note that no model specific check is done to see if the node can be removed - * or not. Extend or override to implement specific behaviour. - */ -public class DeleteNodes extends AbstractHandler { - public final static String ID = "org.argeo.eclipse.ui.jcr.deleteNodes"; - public final static String DEFAULT_LABEL = "Delete selected nodes"; - - public Object execute(ExecutionEvent event) throws ExecutionException { - ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) - .getActivePage().getSelection(); - AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil - .getActiveWorkbenchWindow(event).getActivePage() - .findView(HandlerUtil.getActivePartId(event)); - - if (selection != null && selection instanceof IStructuredSelection) { - Iterator it = ((IStructuredSelection) selection).iterator(); - Object obj = null; - Node ancestor = null; - try { - while (it.hasNext()) { - obj = it.next(); - if (obj instanceof Node) { - Node node = (Node) obj; - Node parentNode = node.getParent(); - node.remove(); - node.getSession().save(); - ancestor = getOlder(ancestor, parentNode); - } - } - if (ancestor != null) - view.nodeRemoved(ancestor); - } catch (Exception e) { - ErrorFeedback.show("Cannot delete node " + obj, e); - } - } - return null; - } - - protected Node getOlder(Node A, Node B) { - try { - - if (A == null) - return B == null ? null : B; - // Todo enhanced this method - else - return A.getDepth() <= B.getDepth() ? A : B; - } catch (RepositoryException re) { - throw new ArgeoException("Cannot find ancestor", re); - } - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java deleted file mode 100644 index ce42266cc..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.commands; - -import org.argeo.eclipse.ui.jcr.editors.JcrQueryEditorInput; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.handlers.HandlerUtil; - -/** Open a JCR query editor. */ -public class OpenGenericJcrQueryEditor extends AbstractHandler { - private String editorId; - - public Object execute(ExecutionEvent event) throws ExecutionException { - try { - JcrQueryEditorInput editorInput = new JcrQueryEditorInput("", null); - IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow( - event).getActivePage(); - activePage.openEditor(editorInput, editorId); - } catch (Exception e) { - throw new ExecutionException("Cannot open editor", e); - } - return null; - } - - public void setEditorId(String editorId) { - this.editorId = editorId; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/Refresh.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/Refresh.java deleted file mode 100644 index f62be37eb..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/commands/Refresh.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.commands; - -import java.util.Iterator; - -import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.handlers.HandlerUtil; - -/** - * Call the refresh method of the active AbstractJcrBrowser instance. - * - * Warning: this method only refreshes the viewer, if the model is "stale", e.g. - * if some changes in the underlying data have not yet been propagated to the - * model, the view will not display up-to-date information. - */ -@Deprecated -public class Refresh extends AbstractHandler { - - public Object execute(ExecutionEvent event) throws ExecutionException { - ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) - .getActivePage().getSelection(); - AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil - .getActiveWorkbenchWindow(event).getActivePage() - .findView(HandlerUtil.getActivePartId(event)); - if (selection != null && selection instanceof IStructuredSelection) { - Iterator it = ((IStructuredSelection) selection).iterator(); - while (it.hasNext()) { - Object obj = it.next(); - view.refresh(obj); - } - } - return null; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java deleted file mode 100644 index 5e7d69644..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.editors; - -import java.util.ArrayList; -import java.util.List; - -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.query.QueryResult; -import javax.jcr.query.Row; -import javax.jcr.query.RowIterator; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.GenericTableComparator; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.viewers.ColumnLabelProvider; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TableViewerColumn; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.part.EditorPart; - -/** Executes any JCR query. */ -public abstract class AbstractJcrQueryEditor extends EditorPart { - private final static Log log = LogFactory - .getLog(AbstractJcrQueryEditor.class); - - protected String initialQuery; - protected String initialQueryType; - - /* DEPENDENCY INJECTION */ - private Session session; - - // Widgets - private TableViewer viewer; - private List tableViewerColumns = new ArrayList(); - private GenericTableComparator comparator; - - /** Override to layout a form enabling the end user to build his query */ - protected abstract void createQueryForm(Composite parent); - - @Override - public void init(IEditorSite site, IEditorInput input) - throws PartInitException { - JcrQueryEditorInput editorInput = (JcrQueryEditorInput) input; - initialQuery = editorInput.getQuery(); - initialQueryType = editorInput.getQueryType(); - setSite(site); - setInput(editorInput); - } - - @Override - public final void createPartControl(final Composite parent) { - parent.setLayout(new FillLayout()); - - SashForm sashForm = new SashForm(parent, SWT.VERTICAL); - sashForm.setSashWidth(4); - sashForm.setLayout(new FillLayout()); - - Composite top = new Composite(sashForm, SWT.NONE); - GridLayout gl = new GridLayout(1, false); - top.setLayout(gl); - - createQueryForm(top); - - Composite bottom = new Composite(sashForm, SWT.NONE); - bottom.setLayout(new GridLayout(1, false)); - sashForm.setWeights(getWeights()); - - viewer = new TableViewer(bottom); - viewer.getTable().setLayoutData( - new GridData(SWT.FILL, SWT.FILL, true, true)); - viewer.getTable().setHeaderVisible(true); - viewer.setContentProvider(getQueryResultContentProvider()); - viewer.setInput(getEditorSite()); - - if (getComparator() != null) { - comparator = getComparator(); - viewer.setComparator(comparator); - } - if (getTableDoubleClickListener() != null) - viewer.addDoubleClickListener(getTableDoubleClickListener()); - - } - - protected void executeQuery(String statement) { - try { - if (log.isDebugEnabled()) - log.debug("Query : " + statement); - - QueryResult qr = session.getWorkspace().getQueryManager() - .createQuery(statement, initialQueryType).execute(); - - // remove previous columns - for (TableViewerColumn tvc : tableViewerColumns) - tvc.getColumn().dispose(); - - int i = 0; - for (final String columnName : qr.getColumnNames()) { - TableViewerColumn tvc = new TableViewerColumn(viewer, SWT.NONE); - configureColumn(columnName, tvc, i); - tvc.setLabelProvider(getLabelProvider(columnName)); - tableViewerColumns.add(tvc); - i++; - } - - // Must create a local list: QueryResults can only be read once. - try { - List rows = new ArrayList(); - 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())); - } - } - - /** - * To be overidden to adapt size of form and result frames. - * - * @return - */ - protected int[] getWeights() { - return new int[] { 30, 70 }; - } - - /** - * To be overidden to implement a doubleclick Listener on one of the rows of - * the table. - * - * @return - */ - protected IDoubleClickListener getTableDoubleClickListener() { - return null; - } - - /** - * To be overiden in order to implement a specific - * QueryResultContentProvider - */ - protected IStructuredContentProvider getQueryResultContentProvider() { - return new QueryResultContentProvider(); - } - - /** - * Enable specific implementation for columns - */ - protected List getTableViewerColumns() { - return tableViewerColumns; - } - - /** - * Enable specific implementation for columns - */ - protected TableViewer getTableViewer() { - return viewer; - } - - /** - * To be overridden in order to configure column label providers . - */ - protected ColumnLabelProvider getLabelProvider(final String columnName) { - return new ColumnLabelProvider() { - 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; - } - }; - } - - /** - * To be overridden in order to configure the columns. - * - * @deprecated use {@link - * org.argeo.eclipse.ui.jcr.editors.AbstractJcrQueryEditor. - * configureColumn(String jcrColumnName, TableViewerColumn - * column, int columnIndex)} instead - */ - protected void configureColumn(String jcrColumnName, - TableViewerColumn column) { - column.getColumn().setWidth(50); - column.getColumn().setText(jcrColumnName); - } - - /** To be overridden in order to configure the columns. */ - protected void configureColumn(String jcrColumnName, - TableViewerColumn column, int columnIndex) { - column.getColumn().setWidth(50); - column.getColumn().setText(jcrColumnName); - } - - private class QueryResultContentProvider implements - IStructuredContentProvider { - - public void dispose() { - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - public Object[] getElements(Object inputElement) { - - if (inputElement instanceof List) - return ((List) inputElement).toArray(); - - // Never reached might be deleted in future release - if (!(inputElement instanceof QueryResult)) - return new String[] {}; - - try { - QueryResult queryResult = (QueryResult) inputElement; - List rows = new ArrayList(); - RowIterator rit = queryResult.getRows(); - while (rit.hasNext()) { - rows.add(rit.nextRow()); - } - - // List elems = new ArrayList(); - // NodeIterator nit = queryResult.getNodes(); - // while (nit.hasNext()) { - // elems.add(nit.nextNode()); - // } - return rows.toArray(); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot read query result", e); - } - } - - } - - /** - * Might be used by children classes to sort columns. - * - * @param column - * @param index - * @return - */ - protected SelectionAdapter getSelectionAdapter(final TableColumn column, - final int index) { - - // A comparator must be define - if (comparator == null) - return null; - - SelectionAdapter selectionAdapter = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - - try { - - comparator.setColumn(index); - int dir = viewer.getTable().getSortDirection(); - if (viewer.getTable().getSortColumn() == column) { - dir = dir == SWT.UP ? SWT.DOWN : SWT.UP; - } else { - - dir = SWT.DOWN; - } - viewer.getTable().setSortDirection(dir); - viewer.getTable().setSortColumn(column); - viewer.refresh(); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - }; - return selectionAdapter; - } - - /** - * To be overridden to enable sorting. - */ - protected GenericTableComparator getComparator() { - return null; - } - - @Override - public boolean isDirty() { - return false; - } - - @Override - public void doSave(IProgressMonitor monitor) { - // TODO save the query in JCR? - } - - @Override - public void doSaveAs() { - } - - @Override - public boolean isSaveAsAllowed() { - return false; - } - - /** Returns the injected current session */ - protected Session getSession() { - return session; - } - - /* DEPENDENCY INJECTION */ - public void setSession(Session session) { - this.session = session; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java deleted file mode 100644 index eedccc85b..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.editors; - -import javax.jcr.query.Query; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IPersistableElement; - -public class JcrQueryEditorInput implements IEditorInput { - private final String query; - private final String queryType; - - public JcrQueryEditorInput(String query, String queryType) { - this.query = query; - if (queryType == null) - this.queryType = Query.JCR_SQL2; - else - this.queryType = queryType; - } - - public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { - return null; - } - - public boolean exists() { - return true; - } - - public ImageDescriptor getImageDescriptor() { - return null; - } - - public String getName() { - return query; - } - - public IPersistableElement getPersistable() { - return null; - } - - public String getToolTipText() { - return query; - } - - public String getQuery() { - return query; - } - - public String getQueryType() { - return queryType; - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java deleted file mode 100644 index a55884f2e..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.editors; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IPersistableElement; - -/** - * A canonical editor input based on a path to a node. In a multirepository - * environment, path can be enriched with Repository Alias and workspace - */ - -public class NodeEditorInput implements IEditorInput { - private final String path; - - public NodeEditorInput(String path) { - this.path = path; - } - - public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { - return null; - } - - public boolean exists() { - return true; - } - - public ImageDescriptor getImageDescriptor() { - return null; - } - - public String getName() { - return path; - } - - public IPersistableElement getPersistable() { - return null; - } - - public String getToolTipText() { - return path; - } - - public String getPath() { - return path; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java deleted file mode 100644 index 9e338276a..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -/** - * Utility object to manage column in various tables and extracts displaying - * data from JCR - */ -public class ColumnDefinition { - private final static int DEFAULT_COLUMN_SIZE = 120; - - private String selectorName; - private String propertyName; - private String headerLabel; - private int propertyType; - private int columnSize = DEFAULT_COLUMN_SIZE; - - /** - * new column using default width - * - * @param selectorName - * @param propertyName - * @param propertyType - * @param headerLabel - */ - public ColumnDefinition(String selectorName, String propertyName, - int propertyType, String headerLabel) { - this.selectorName = selectorName; - this.propertyName = propertyName; - this.propertyType = propertyType; - this.headerLabel = headerLabel; - } - - /** - * - * @param selectorName - * @param propertyName - * @param propertyType - * @param headerLabel - * @param columnSize - */ - public ColumnDefinition(String selectorName, String propertyName, - int propertyType, String headerLabel, int columnSize) { - this.selectorName = selectorName; - this.propertyName = propertyName; - this.propertyType = propertyType; - this.headerLabel = headerLabel; - this.columnSize = columnSize; - } - - public String getSelectorName() { - return selectorName; - } - - public void setSelectorName(String selectorName) { - this.selectorName = selectorName; - } - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public String getHeaderLabel() { - return headerLabel; - } - - public void setHeaderLabel(String headerLabel) { - this.headerLabel = headerLabel; - } - - public int getPropertyType() { - return propertyType; - } - - public void setPropertyType(int propertyType) { - this.propertyType = propertyType; - } - - public int getColumnSize() { - return columnSize; - } - - public void setColumnSize(int columnSize) { - this.columnSize = columnSize; - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/IListProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/IListProvider.java deleted file mode 100644 index 622e2e259..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/IListProvider.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -import java.util.List; - -/** - * Views and editors can implement this interface so that one of the row list - * that is displayed in the part (For instance in a Table or a Tree Viewer) can - * be rebuilt externally. typically to generate csv or calc extract. - */ -public interface IListProvider { - /** - * Returns an array of current and relevant elements - */ - public Object[] getElements(String extractId); - - /** - * Returns the column definition for passed ID - */ - public List getColumnDefinition(String extractId); -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java deleted file mode 100644 index 11f12e6f5..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -import java.math.BigDecimal; -import java.util.Calendar; - -import javax.jcr.Node; -import javax.jcr.PropertyType; -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFormatException; - -import org.argeo.ArgeoException; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; - -/** - * Base comparator to enable ordering on Table or Tree viewer that display Jcr - * Nodes. - * - * Note that the following snippet must be added before setting the comparator - * to the corresponding control: - * // IMPORTANT: initialize comparator before setting it - * ColumnDefinition firstCol = colDefs.get(0); - * comparator.setColumn(firstCol.getPropertyType(), - * firstCol.getPropertyName()); - * viewer.setComparator(comparator); - */ -public class NodeViewerComparator extends ViewerComparator { - - protected String propertyName; - - protected int propertyType; - public static final int ASCENDING = 0, DESCENDING = 1; - protected int direction = DESCENDING; - - public NodeViewerComparator() { - } - - /** - * e1 and e2 must both be Jcr nodes. - * - * @param viewer - * @param e1 - * @param e2 - * @return - */ - @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(propertyName)) - v1 = n1.getProperty(propertyName).getValue(); - if (n2.hasProperty(propertyName)) - v2 = n2.getProperty(propertyName).getValue(); - - if (v2 == null && v1 == null) - return 0; - else if (v2 == null) - return -1; - else if (v1 == null) - return 1; - - switch (propertyType) { - 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 a long - 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 = -1; - else if (lc > 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; - case PropertyType.DOUBLE: - Double d1 = v1.getDouble(); - Double d2 = v2.getDouble(); - rc = d1.compareTo(d2); - 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; - } - - /** - * @param propertyType - * Corresponding JCR type - * @param propertyName - * name of the property to use. - */ - public void setColumn(int propertyType, String propertyName) { - if (this.propertyName != null && this.propertyName.equals(propertyName)) { - // Same column as last sort; toggle the direction - direction = 1 - direction; - } else { - // New column; do an ascending sort - this.propertyType = propertyType; - this.propertyName = propertyName; - direction = ASCENDING; - } - } - - // Getters and setters - protected String getPropertyName() { - return propertyName; - } - - protected void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - protected int getPropertyType() { - return propertyType; - } - - protected void setPropertyType(int propertyType) { - this.propertyType = propertyType; - } - - protected int getDirection() { - return direction; - } - - protected void setDirection(int direction) { - this.direction = direction; - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java deleted file mode 100644 index 509f72324..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.query.Row; - -import org.argeo.ArgeoException; -import org.eclipse.jface.viewers.Viewer; - -/** - * Base comparator to enable ordering on Table or Tree viewer that display Jcr - * rows - */ -public class RowViewerComparator extends NodeViewerComparator { - - protected String selectorName; - - public RowViewerComparator() { - } - - /** - * e1 and e2 must both be Jcr rows. - * - * @param viewer - * @param e1 - * @param e2 - * @return - */ - @Override - public int compare(Viewer viewer, Object e1, Object e2) { - try { - Node n1 = ((Row) e1).getNode(selectorName); - Node n2 = ((Row) e2).getNode(selectorName); - return super.compare(viewer, n1, n2); - } catch (RepositoryException re) { - throw new ArgeoException("Unexpected error " - + "while comparing nodes", re); - } - } - - /** - * @param propertyType - * Corresponding JCR type - * @param propertyName - * name of the property to use. - */ - public void setColumn(int propertyType, String selectorName, - String propertyName) { - if (this.selectorName != null && getPropertyName() != null - && this.selectorName.equals(selectorName) - && this.getPropertyName().equals(propertyName)) { - // Same column as last sort; toggle the direction - setDirection(1 - getDirection()); - } else { - // New column; do a descending sort - setPropertyType(propertyType); - setPropertyName(propertyName); - this.selectorName = selectorName; - setDirection(NodeViewerComparator.ASCENDING); - } - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java deleted file mode 100644 index 88585c343..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.text.SimpleDateFormat; - -import javax.jcr.Node; -import javax.jcr.PropertyType; -import javax.jcr.RepositoryException; -import javax.jcr.Value; - -import org.argeo.ArgeoException; -import org.eclipse.jface.viewers.ColumnLabelProvider; - -/** - * Base implementation of a label provider for widgets that display JCR Rows. - */ -public class SimpleJcrNodeLabelProvider extends ColumnLabelProvider { - private static final long serialVersionUID = -5215787695436221993L; - - private final static String DEFAULT_DATE_FORMAT = "EEE, dd MMM yyyy"; - private final static String DEFAULT_NUMBER_FORMAT = "#,##0.0"; - - private DateFormat dateFormat; - private NumberFormat numberFormat; - - final private String propertyName; - - /** - * Default Label provider for a given property of a node. Using default - * pattern for date and number formating - */ - public SimpleJcrNodeLabelProvider(String propertyName) { - this.propertyName = propertyName; - dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT); - numberFormat = DecimalFormat.getInstance(); - ((DecimalFormat) numberFormat).applyPattern(DEFAULT_NUMBER_FORMAT); - } - - /** - * Label provider for a given property of a node optionally precising date - * and/or number format patterns - */ - public SimpleJcrNodeLabelProvider(String propertyName, - String dateFormatPattern, String numberFormatPattern) { - this.propertyName = propertyName; - dateFormat = new SimpleDateFormat( - dateFormatPattern == null ? DEFAULT_DATE_FORMAT - : dateFormatPattern); - numberFormat = DecimalFormat.getInstance(); - ((DecimalFormat) numberFormat) - .applyPattern(numberFormatPattern == null ? DEFAULT_NUMBER_FORMAT - : numberFormatPattern); - } - - @Override - public String getText(Object element) { - try { - Node currNode = (Node) element; - - if (currNode.hasProperty(propertyName)) { - if (currNode.getProperty(propertyName).isMultiple()) { - StringBuilder builder = new StringBuilder(); - for (Value value : currNode.getProperty(propertyName) - .getValues()) { - String currStr = getSingleValueAsString(value); - if (notEmptyString(currStr)) - builder.append(currStr).append("; "); - } - if (builder.length() > 0) - builder.deleteCharAt(builder.length() - 2); - - return builder.toString(); - } else - return getSingleValueAsString(currNode.getProperty( - propertyName).getValue()); - } else - return ""; - } catch (RepositoryException re) { - throw new ArgeoException("Unable to get text from row", re); - } - } - - private String getSingleValueAsString(Value value) - throws RepositoryException { - switch (value.getType()) { - case PropertyType.STRING: - return value.getString(); - case PropertyType.BOOLEAN: - return "" + value.getBoolean(); - case PropertyType.DATE: - return dateFormat.format(value.getDate().getTime()); - case PropertyType.LONG: - return "" + value.getLong(); - case PropertyType.DECIMAL: - return numberFormat.format(value.getDecimal()); - case PropertyType.DOUBLE: - return numberFormat.format(value.getDouble()); - case PropertyType.NAME: - return value.getString(); - default: - throw new ArgeoException("Unimplemented label provider " - + "for property type " + value.getType() - + " while getting property " + propertyName + " - value: " - + value.getString()); - - } - } - - private boolean notEmptyString(String string) { - return string != null && !"".equals(string.trim()); - } - - public void setDateFormat(String dateFormatPattern) { - dateFormat = new SimpleDateFormat(dateFormatPattern); - } - - public void setNumberFormat(String numberFormatPattern) { - ((DecimalFormat) numberFormat).applyPattern(numberFormatPattern); - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java deleted file mode 100644 index bb55f187d..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.argeo.eclipse.ui.jcr.lists; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.query.Row; - -import org.argeo.ArgeoException; - -/** - * Base implementation of a label provider for widgets that display JCR Rows. - */ -public class SimpleJcrRowLabelProvider extends SimpleJcrNodeLabelProvider { - private static final long serialVersionUID = -3414654948197181740L; - - final private String selectorName; - - /** - * Default Label provider for a given property of a row. Using default - * pattern for date and number formating - */ - public SimpleJcrRowLabelProvider(String selectorName, String propertyName) { - super(propertyName); - this.selectorName = selectorName; - } - - /** - * Label provider for a given property of a node optionally precising date - * and/or number format patterns - */ - public SimpleJcrRowLabelProvider(String selectorName, String propertyName, - String dateFormatPattern, String numberFormatPattern) { - super(propertyName, dateFormatPattern, numberFormatPattern); - this.selectorName = selectorName; - } - - @Override - public String getText(Object element) { - try { - Row currRow = (Row) element; - Node currNode = currRow.getNode(selectorName); - return super.getText(currNode); - } catch (RepositoryException re) { - throw new ArgeoException("Unable to get Node " + selectorName - + " from row " + element, re); - } - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java deleted file mode 100644 index b2e6455c8..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.utils; - -import java.io.InputStream; - -import javax.jcr.Node; -import javax.jcr.Property; -import javax.jcr.RepositoryException; -import javax.jcr.nodetype.NodeType; - -import org.apache.commons.io.IOUtils; -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.FileProvider; - -/** - * Implements a FileProvider for UI purposes. Note that it might not be very - * reliable as long as we have not fixed login & multi repository issues that - * will be addressed in the next version. - * - * NOTE: id used here is the real id of the JCR Node, not the JCR Path - * - * Relies on common approach for JCR file handling implementation. - * - */ - -public class JcrFileProvider implements FileProvider { - - // private Object[] rootNodes; - private Node refNode; - - /** - * Must be set in order for the provider to be able to get current session - * and thus have the ability to get the file node corresponding to a given - * file ID - * - * FIXME : this introduces some concurrences ISSUES. - * - * @param repositoryNode - */ - public void setReferenceNode(Node refNode) { - this.refNode = refNode; - } - - /** - * Must be set in order for the provider to be able to search the repository - * Provided object might be either JCR Nodes or UI RepositoryNode for the - * time being. - * - * @param repositoryNode - */ - // public void setRootNodes(Object[] rootNodes) { - // List tmpNodes = new ArrayList(); - // for (int i = 0; i < rootNodes.length; i++) { - // Object obj = rootNodes[i]; - // if (obj instanceof Node) { - // tmpNodes.add(obj); - // } else if (obj instanceof RepositoryRegister) { - // RepositoryRegister repositoryRegister = (RepositoryRegister) obj; - // Map repositories = repositoryRegister - // .getRepositories(); - // for (String name : repositories.keySet()) { - // // tmpNodes.add(new RepositoryNode(name, repositories - // // .get(name))); - // } - // - // } - // } - // this.rootNodes = tmpNodes.toArray(); - // } - - public byte[] getByteArrayFileFromId(String fileId) { - InputStream fis = null; - byte[] ba = null; - Node child = getFileNodeFromId(fileId); - try { - fis = (InputStream) child.getProperty(Property.JCR_DATA) - .getBinary().getStream(); - ba = IOUtils.toByteArray(fis); - - } catch (Exception e) { - throw new ArgeoException("Stream error while opening file", e); - } finally { - IOUtils.closeQuietly(fis); - } - return ba; - } - - public InputStream getInputStreamFromFileId(String fileId) { - try { - InputStream fis = null; - - Node child = getFileNodeFromId(fileId); - fis = (InputStream) child.getProperty(Property.JCR_DATA) - .getBinary().getStream(); - return fis; - } catch (RepositoryException re) { - throw new ArgeoException("Cannot get stream from file node for Id " - + fileId, re); - } - } - - /** - * Throws an exception if the node is not found in the current repository (a - * bit like a FileNotFoundException) - * - * @param fileId - * @return Returns the child node of the nt:file node. It is the child node - * that have the jcr:data property where actual file is stored. - * never null - */ - private Node getFileNodeFromId(String fileId) { - try { - Node result = refNode.getSession().getNodeByIdentifier(fileId); - - // rootNodes: for (int j = 0; j < rootNodes.length; j++) { - // // in case we have a classic JCR Node - // if (rootNodes[j] instanceof Node) { - // Node curNode = (Node) rootNodes[j]; - // if (result != null) - // break rootNodes; - // } // Case of a repository Node - // else if (rootNodes[j] instanceof RepositoryNode) { - // Object[] nodes = ((RepositoryNode) rootNodes[j]) - // .getChildren(); - // for (int i = 0; i < nodes.length; i++) { - // Node node = (Node) nodes[i]; - // result = node.getSession().getNodeByIdentifier(fileId); - // if (result != null) - // break rootNodes; - // } - // } - // } - - // Sanity checks - if (result == null) - throw new ArgeoException("File node not found for ID" + fileId); - - Node child = null; - - boolean isValid = true; - if (!result.isNodeType(NodeType.NT_FILE)) - // useless: mandatory child node - // || !result.hasNode(Property.JCR_CONTENT)) - isValid = false; - else { - child = result.getNode(Property.JCR_CONTENT); - if (!(child.isNodeType(NodeType.NT_RESOURCE) || child - .hasProperty(Property.JCR_DATA))) - isValid = false; - } - - if (!isValid) - throw new ArgeoException( - "ERROR: In the current implemented model, '" - + NodeType.NT_FILE - + "' file node must have a child node named jcr:content " - + "that has a BINARY Property named jcr:data " - + "where the actual data is stored"); - return child; - - } catch (RepositoryException re) { - throw new ArgeoException("Erreur while getting file node of ID " - + fileId, re); - } - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java deleted file mode 100644 index 2d36bf28a..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.utils; - -import java.util.Comparator; - -import javax.jcr.Item; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; - -/** Compares two JCR items (node or properties) based on their names. */ -public class JcrItemsComparator implements Comparator { - public int compare(Item o1, Item o2) { - try { - // TODO: put folder before files - return o1.getName().compareTo(o2.getName()); - } catch (RepositoryException e) { - throw new ArgeoException("Cannot compare " + o1 + " and " + o2, e); - } - } - -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java deleted file mode 100644 index 5a94ee76a..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.utils; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; - -import org.argeo.ArgeoException; -import org.eclipse.jface.viewers.IElementComparer; - -/** Compare JCR nodes based on their JCR identifiers, for use in JFace viewers. */ -public class NodeViewerComparer implements IElementComparer { - - // force comparison on Node IDs only. - public boolean equals(Object elementA, Object elementB) { - if (!(elementA instanceof Node) || !(elementB instanceof Node)) { - return elementA == null ? elementB == null : elementA - .equals(elementB); - } else { - - boolean result = false; - try { - String idA = ((Node) elementA).getIdentifier(); - String idB = ((Node) elementB).getIdentifier(); - result = idA == null ? idB == null : idA.equals(idB); - } catch (RepositoryException re) { - throw new ArgeoException("cannot compare nodes", re); - } - - return result; - } - } - - public int hashCode(Object element) { - // TODO enhanced this method. - return element.getClass().toString().hashCode(); - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java deleted file mode 100644 index 40631cdde..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.utils; - -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 org.apache.commons.io.IOUtils; -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.FileProvider; - -/** - * Implements a FileProvider for UI purposes. Unlike the - * JcrFileProvider , it relies on a single session and manages - * nodes with path only. - * - * Note that considered id is the JCR path - * - * Relies on common approach for JCR file handling implementation. - * - * @author bsinou - * - */ - -public class SingleSessionFileProvider implements FileProvider { - - private Session session; - - public SingleSessionFileProvider(Session session) { - this.session = session; - } - - public byte[] getByteArrayFileFromId(String fileId) { - InputStream fis = null; - byte[] ba = null; - Node child = getFileNodeFromId(fileId); - try { - fis = (InputStream) child.getProperty(Property.JCR_DATA) - .getBinary().getStream(); - ba = IOUtils.toByteArray(fis); - - } catch (Exception e) { - throw new ArgeoException("Stream error while opening file", e); - } finally { - IOUtils.closeQuietly(fis); - } - return ba; - } - - public InputStream getInputStreamFromFileId(String fileId) { - try { - InputStream fis = null; - - Node child = getFileNodeFromId(fileId); - fis = (InputStream) child.getProperty(Property.JCR_DATA) - .getBinary().getStream(); - return fis; - } catch (RepositoryException re) { - throw new ArgeoException("Cannot get stream from file node for Id " - + fileId, re); - } - } - - /** - * - * @param fileId - * @return Returns the child node of the nt:file node. It is the child node - * that have the jcr:data property where actual file is stored. - * never null - */ - private Node getFileNodeFromId(String fileId) { - try { - Node result = null; - result = session.getNode(fileId); - - // Sanity checks - if (result == null) - throw new ArgeoException("File node not found for ID" + fileId); - - // Ensure that the node have the correct type. - if (!result.isNodeType(NodeType.NT_FILE)) - throw new ArgeoException( - "Cannot open file children Node that are not of " - + NodeType.NT_RESOURCE + " type."); - - Node child = result.getNodes().nextNode(); - if (child == null || !child.isNodeType(NodeType.NT_RESOURCE)) - throw new ArgeoException( - "ERROR: IN the current implemented model, " - + NodeType.NT_FILE - + " file node must have one and only one child of the nt:ressource, where actual data is stored"); - return child; - } catch (RepositoryException re) { - throw new ArgeoException("Erreur while getting file node of ID " - + fileId, re); - } - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java deleted file mode 100644 index 133a65fd1..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.jcr.views; - -import javax.jcr.Node; - -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.part.ViewPart; - -public abstract class AbstractJcrBrowser extends ViewPart { - - @Override - public abstract void createPartControl(Composite parent); - - /** - * To be overridden to adapt size of form and result frames. - */ - abstract protected int[] getWeights(); - - /** - * To be overridden to provide an adapted size nodeViewer - */ - abstract protected TreeViewer createNodeViewer(Composite parent, - ITreeContentProvider nodeContentProvider); - - /** - * To be overridden to retrieve the current nodeViewer - */ - abstract protected TreeViewer getNodeViewer(); - - /* - * Enables the refresh of the tree. - */ - @Override - public void setFocus() { - getNodeViewer().getTree().setFocus(); - } - - public void refresh(Object obj) { - // getNodeViewer().update(obj, null); - getNodeViewer().refresh(obj); - // getNodeViewer().expandToLevel(obj, 1); - } - - public void nodeAdded(Node parentNode, Node newNode) { - getNodeViewer().refresh(parentNode); - getNodeViewer().expandToLevel(newNode, 0); - } - - public void nodeRemoved(Node parentNode) { - IStructuredSelection newSel = new StructuredSelection(parentNode); - getNodeViewer().setSelection(newSel, true); - // Force refresh - IStructuredSelection tmpSel = (IStructuredSelection) getNodeViewer() - .getSelection(); - getNodeViewer().refresh(tmpSel.getFirstElement()); - } -} diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/CommandUtils.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/CommandUtils.java deleted file mode 100644 index 22a139f13..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/CommandUtils.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.utils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.argeo.ArgeoException; -import org.argeo.eclipse.ui.ArgeoUiPlugin; -import org.eclipse.core.commands.Command; -import org.eclipse.core.commands.IParameter; -import org.eclipse.core.commands.Parameterization; -import org.eclipse.core.commands.ParameterizedCommand; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.swt.SWT; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.commands.ICommandService; -import org.eclipse.ui.handlers.IHandlerService; -import org.eclipse.ui.menus.CommandContributionItem; -import org.eclipse.ui.menus.CommandContributionItemParameter; -import org.eclipse.ui.services.IServiceLocator; - -/** - * Centralises useful and generic methods when dealing with commands in an - * Eclipse Workbench context - */ -public class CommandUtils { - - /** - * Commodities the refresh of a single command with no parameter in a - * Menu.aboutToShow method to simplify further development - * - * Note: that this method should be called with a false show command flag to - * remove a contribution that have been previously contributed - * - * @param menuManager - * @param locator - * @param cmdId - * @param label - * @param icon - * @param showCommand - */ - public static void refreshCommand(IMenuManager menuManager, - IServiceLocator locator, String cmdId, String label, - ImageDescriptor icon, boolean showCommand) { - refreshParameterizedCommand(menuManager, locator, cmdId, label, icon, - showCommand, null); - } - - /** - * Commodities the refresh the contribution of a command with a map of - * parameters in a context menu - * - * The command ID is used has contribution item ID - * - * @param menuManager - * @param locator - * @param cmdId - * @param label - * @param iconPath - * @param showCommand - */ - public static void refreshParameterizedCommand(IMenuManager menuManager, - IServiceLocator locator, String cmdId, String label, - ImageDescriptor icon, boolean showCommand, - Map params) { - refreshParameterizedCommand(menuManager, locator, cmdId, cmdId, label, - icon, showCommand, params); - } - - /** - * Commodities the refresh the contribution of a command with a map of - * parameters in a context menu - * - * @param menuManager - * @param locator - * @param contributionId - * @param commandId - * @param label - * @param icon - * @param showCommand - * @param params - */ - public static void refreshParameterizedCommand(IMenuManager menuManager, - IServiceLocator locator, String contributionId, String commandId, - String label, ImageDescriptor icon, boolean showCommand, - Map params) { - IContributionItem ici = menuManager.find(contributionId); - if (ici != null) - menuManager.remove(ici); - if (showCommand) { - CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter( - locator, null, commandId, SWT.PUSH); - - // Set Params - contributionItemParameter.label = label; - contributionItemParameter.icon = icon; - - if (params != null) - contributionItemParameter.parameters = params; - - CommandContributionItem cci = new CommandContributionItem( - contributionItemParameter); - cci.setId(contributionId); - menuManager.add(cci); - } - } - - /** Helper to call a command without parameter easily */ - public static void callCommand(String commandID) { - callCommand(commandID, null); - } - - /** Helper to call a command with a single parameter easily */ - public static void callCommand(String commandID, String parameterID, - String parameterValue) { - Map params = new HashMap(); - params.put(parameterID, parameterValue); - callCommand(commandID, params); - } - - /** - * Helper to call a command with a map of parameters easily - * - * @param paramMap - * a map that links various command IDs with corresponding String - * values. - */ - public static void callCommand(String commandID, - Map paramMap) { - try { - IWorkbench iw = ArgeoUiPlugin.getDefault().getWorkbench(); - IHandlerService handlerService = (IHandlerService) iw - .getService(IHandlerService.class); - ICommandService cmdService = (ICommandService) iw - .getActiveWorkbenchWindow().getService( - ICommandService.class); - Command cmd = cmdService.getCommand(commandID); - - ArrayList parameters = null; - ParameterizedCommand pc; - - if (paramMap != null) { - // Set parameters of the command to launch : - parameters = new ArrayList(); - Parameterization parameterization; - - for (String id : paramMap.keySet()) { - parameterization = new Parameterization( - cmd.getParameter(id), paramMap.get(id)); - parameters.add(parameterization); - } - pc = new ParameterizedCommand(cmd, - parameters.toArray(new Parameterization[parameters - .size()])); - } else - pc = new ParameterizedCommand(cmd, null); - - // execute the command - handlerService.executeCommand(pc, null); - } catch (Exception e) { - throw new ArgeoException("Unexpected error while" - + " calling the command " + commandID, e); - } - } - - // legacy methods. Should be removed soon - - /** - * Shortcut to call a command with a single parameter. - * - * WARNING: none of the parameter can be null - * - * @deprecated rather use callCommand(commandID,parameterID, - parameterValue) - */ - public static void CallCommandWithOneParameter(String commandId, - String paramId, String paramValue) { - try { - IWorkbench iw = ArgeoUiPlugin.getDefault().getWorkbench(); - IHandlerService handlerService = (IHandlerService) iw - .getService(IHandlerService.class); - - // Gets a command that must have been previously registered - IWorkbenchWindow window = iw.getActiveWorkbenchWindow(); - ICommandService cmdService = (ICommandService) window - .getService(ICommandService.class); - Command cmd = cmdService.getCommand(commandId); - - // Manages the single parameter - ArrayList parameters = new ArrayList(); - IParameter iparam = cmd.getParameter(paramId); - Parameterization params = new Parameterization(iparam, paramValue); - parameters.add(params); - - // Create and execute the command - ParameterizedCommand pc = new ParameterizedCommand(cmd, - parameters.toArray(new Parameterization[parameters.size()])); - handlerService = (IHandlerService) window - .getService(IHandlerService.class); - handlerService.executeCommand(pc, null); - } catch (Exception e) { - throw new ArgeoException( - "Error calling command of id:" + commandId, e); - } - } - - /** - * Commodities the refresh of a single command with a map of parameters in a - * Menu.aboutToShow method to simplify further development Rather use - * {@link refreshParameterizedCommand()} - */ - @Deprecated - public static void refreshParametrizedCommand(IMenuManager menuManager, - IServiceLocator locator, String cmdId, String label, - ImageDescriptor icon, boolean showCommand, - Map params) { - refreshParameterizedCommand(menuManager, locator, cmdId, label, icon, - showCommand, params); - } -} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/ViewerUtils.java b/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/ViewerUtils.java deleted file mode 100644 index 42e9fab99..000000000 --- a/org.argeo.eclipse.ui/src/main/java/org/argeo/eclipse/ui/utils/ViewerUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2007-2012 Argeo GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.argeo.eclipse.ui.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 Jface Table, Tree and TreeColumn - * viewers. - */ -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; - } -} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/ApplicationContextTracker.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/ApplicationContextTracker.java new file mode 100644 index 000000000..070c70826 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/ApplicationContextTracker.java @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.spring; + +import static java.text.MessageFormat.format; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.core.runtime.Platform; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.util.tracker.ServiceTracker; +import org.springframework.context.ApplicationContext; + +/** + * Tracks Spring application context published as services. + * + * @author Heiko Seeberger + * @author Mathieu Baudier + */ +class ApplicationContextTracker { + private final static Log log = LogFactory + .getLog(ApplicationContextTracker.class); + + private static final String FILTER = "(&(objectClass=org.springframework.context.ApplicationContext)" //$NON-NLS-1$ + + "(org.springframework.context.service.name={0}))"; //$NON-NLS-1$ + + public final static String APPLICATION_CONTEXT_TRACKER_TIMEOUT = "org.argeo.eclipse.spring.applicationContextTrackerTimeout"; + + private static Long defaultTimeout = Long.parseLong(System.getProperty( + APPLICATION_CONTEXT_TRACKER_TIMEOUT, "30000")); + + private ServiceTracker applicationContextServiceTracker; + + /** + * @param contributorBundle + * OSGi bundle for which the Spring application context is to be + * tracked. Must not be null! + * @param factoryBundleContext + * BundleContext object which can be used to track services + * @throws IllegalArgumentException + * if the given bundle is null. + */ + public ApplicationContextTracker(final Bundle contributorBundle, + final BundleContext factoryBundleContext) { + final String filter = format(FILTER, + contributorBundle.getSymbolicName()); + try { + applicationContextServiceTracker = new ServiceTracker( + factoryBundleContext, FrameworkUtil.createFilter(filter), + null); + // applicationContextServiceTracker.open(); + } catch (final InvalidSyntaxException e) { + e.printStackTrace(); + } + } + + public void open() { + if (applicationContextServiceTracker != null) { + applicationContextServiceTracker.open(); + } + } + + public void close() { + if (applicationContextServiceTracker != null) { + applicationContextServiceTracker.close(); + } + } + + public ApplicationContext getApplicationContext() { + ApplicationContext applicationContext = null; + if (applicationContextServiceTracker != null) { + try { + applicationContext = (ApplicationContext) applicationContextServiceTracker + .waitForService(defaultTimeout); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return applicationContext; + } + + @Override + protected void finalize() throws Throwable { + close(); + super.finalize(); + } + + static ApplicationContext getApplicationContext(String bundleSymbolicName) { + Bundle contributorBundle = Platform.getBundle(bundleSymbolicName); + return getApplicationContext(contributorBundle); + } + + static ApplicationContext getApplicationContext( + final Bundle contributorBundle) { + if (log.isTraceEnabled()) + log.trace("Get application context for bundle " + contributorBundle); + + // Start if not yet started (also if in STARTING state, may be lazy) + if (contributorBundle.getState() != Bundle.ACTIVE) { + if (log.isTraceEnabled()) + log.trace("Starting bundle: " + + contributorBundle.getSymbolicName()); + // Thread startBundle = new Thread("Start bundle " + // + contributorBundle.getSymbolicName()) { + // public void run() { + try { + contributorBundle.start(); + } catch (BundleException e) { + log.error("Cannot start bundle " + contributorBundle, e); + } + // } + // }; + // startBundle.start(); + // try { + // startBundle.join(10 * 1000l); + // } catch (InterruptedException e) { + // // silent + // } + } + + final ApplicationContextTracker applicationContextTracker = new ApplicationContextTracker( + contributorBundle, contributorBundle.getBundleContext()); + ApplicationContext applicationContext = null; + try { + applicationContextTracker.open(); + applicationContext = applicationContextTracker + .getApplicationContext(); + } finally { + applicationContextTracker.close(); + } + return applicationContext; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringCommandHandler.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringCommandHandler.java new file mode 100644 index 000000000..4c7a152df --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringCommandHandler.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.spring; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.argeo.ArgeoException; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.commands.IHandler; +import org.eclipse.core.commands.IHandlerListener; +import org.springframework.context.ApplicationContext; + +/** Allows to declare Eclipse commands as Spring beans */ +public class SpringCommandHandler implements IHandler { + private final static Log log = LogFactory + .getLog(SpringCommandHandler.class); + + public void addHandlerListener(IHandlerListener handlerListener) { + } + + public void dispose() { + } + + public Object execute(ExecutionEvent event) throws ExecutionException { + String commandId = event.getCommand().getId(); + String bundleSymbolicName = commandId.substring(0, + commandId.lastIndexOf('.')); + try { + if (log.isTraceEnabled()) + log.trace("Execute " + event + " via spring command handler " + + this); + // TODO: make it more flexible and robust + ApplicationContext applicationContext = ApplicationContextTracker + .getApplicationContext(bundleSymbolicName); + if (applicationContext == null) + throw new ArgeoException("No application context found for " + + bundleSymbolicName); + + // retrieve the command via its id + String beanName = event.getCommand().getId(); + + if (!applicationContext.containsBean(beanName)) { + if (beanName.startsWith(bundleSymbolicName)) + beanName = beanName + .substring(bundleSymbolicName.length() + 1); + } + + if (!applicationContext.containsBean(beanName)) + throw new ExecutionException("No bean found with name " + + beanName + " in bundle " + bundleSymbolicName); + Object bean = applicationContext.getBean(beanName); + + if (!(bean instanceof IHandler)) + throw new ExecutionException("Bean with name " + beanName + + " and class " + bean.getClass() + + " does not implement the IHandler interface."); + + IHandler handler = (IHandler) bean; + return handler.execute(event); + } catch (Exception e) { + // TODO: use eclipse error management + // log.error(e); + throw new ExecutionException("Cannot execute Spring command " + + commandId + " in bundle " + bundleSymbolicName, e); + } + } + + public boolean isEnabled() { + return true; + } + + public boolean isHandled() { + return true; + } + + public void removeHandlerListener(IHandlerListener handlerListener) { + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringExtensionFactory.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringExtensionFactory.java new file mode 100644 index 000000000..7a0486fd2 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/spring/SpringExtensionFactory.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.spring; + +import org.argeo.ArgeoException; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExecutableExtension; +import org.eclipse.core.runtime.IExecutableExtensionFactory; +import org.eclipse.core.runtime.IExtension; +import org.springframework.context.ApplicationContext; + +/** + * The Spring Extension Factory builds a bridge between the Eclipse Extension + * Registry and the Spring Framework (especially Spring Dynamic Modules). + * + * It allows you to define your extension as a spring bean within the spring + * application context of your bundle. If you would like to use this bean as an + * instance of an extension (an Eclipse RCP view, for example) you define the + * extension with this spring extension factory as the class to be created. + * + * To let the spring extension factory pick the right bean from your application + * context you need to set the bean id to the same value as the id of the view + * within the view definition, for example. This is important if your extension + * definition contains more than one element, where each element has its own id. + * + * If the extension definition elements themselves have no id attribute the + * spring extension factory uses the id of the extension itself to identify the + * bean. + * + * original code from: Blog entry + * + * @author Martin Lippert + * @author mbaudier + */ +public class SpringExtensionFactory implements IExecutableExtensionFactory, + IExecutableExtension { + + private Object bean; + + public Object create() throws CoreException { + if (bean == null) + throw new ArgeoException("No underlying bean for extension"); + return bean; + } + + public void setInitializationData(IConfigurationElement config, + String propertyName, Object data) throws CoreException { + String bundleSymbolicName = config.getContributor().getName(); + ApplicationContext applicationContext = ApplicationContextTracker + .getApplicationContext(bundleSymbolicName); + if (applicationContext == null) + throw new ArgeoException( + "Cannot find application context for bundle " + + bundleSymbolicName); + + String beanName = getBeanName(data, config); + if (beanName == null) + throw new ArgeoException("Cannot find bean name for extension " + + config); + + if (!applicationContext.containsBean(beanName)) { + if (beanName.startsWith(bundleSymbolicName)) + beanName = beanName.substring(bundleSymbolicName.length() + 1); + } + + if (!applicationContext.containsBean(beanName)) + throw new ArgeoException("No bean with name '" + beanName + "'"); + + this.bean = applicationContext.getBean(beanName); + if (this.bean instanceof IExecutableExtension) { + ((IExecutableExtension) this.bean).setInitializationData(config, + propertyName, data); + } + } + + private String getBeanName(Object data, IConfigurationElement config) { + + // try the specific bean id the extension defines + if (data != null && data.toString().length() > 0) { + return data.toString(); + } + + // try the id of the config element + if (config.getAttribute("id") != null) { + return config.getAttribute("id"); + } + + // try the id of the extension element itself + if (config.getParent() != null + && config.getParent() instanceof IExtension) { + IExtension extensionDefinition = (IExtension) config.getParent(); + return extensionDefinition.getSimpleIdentifier(); + } + + return null; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/AbstractTreeContentProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/AbstractTreeContentProvider.java new file mode 100644 index 000000000..6b86676b4 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/AbstractTreeContentProvider.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.Viewer; + +/** + * Tree content provider dealing with tree objects and providing reasonable + * defaults. + */ +public abstract class AbstractTreeContentProvider implements + ITreeContentProvider { + private static final long serialVersionUID = 8246126401957763868L; + + /** Does nothing */ + public void dispose() { + } + + /** Does nothing */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + + public Object[] getChildren(Object element) { + if (element instanceof TreeParent) { + return ((TreeParent) element).getChildren(); + } + return new Object[0]; + } + + public Object getParent(Object element) { + if (element instanceof TreeParent) { + return ((TreeParent) element).getParent(); + } + return null; + } + + public boolean hasChildren(Object element) { + if (element instanceof TreeParent) { + return ((TreeParent) element).hasChildren(); + } + return false; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ArgeoUiPlugin.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ArgeoUiPlugin.java new file mode 100644 index 000000000..6befdf7d4 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ArgeoUiPlugin.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.core.runtime.ILogListener; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class ArgeoUiPlugin extends AbstractUIPlugin implements ILogListener { + public static final String PLUGIN_ID = "org.argeo.eclipse.ui"; + private final static Log log = LogFactory.getLog(ArgeoUiPlugin.class); + // The shared instance + private static ArgeoUiPlugin plugin; + + public void start(BundleContext context) throws Exception { + super.start(context); + // weirdly, the start method is called twice... + if (plugin == null) { + plugin = this; + Platform.addLogListener(this); + log.debug("Eclipse logging now directed to standard logging"); + } + } + + public void stop(BundleContext context) throws Exception { + try { + // weirdly, the stop method is called twice... + if (plugin != null) { + Platform.removeLogListener(this); + log.debug("Eclipse logging not directed anymore to standard logging"); + plugin = null; + } + } finally { + super.stop(context); + } + } + + /** Returns the shared instance */ + public static ArgeoUiPlugin getDefault() { + return plugin; + } + + public void logging(IStatus status, String plugin) { + Log pluginLog = LogFactory.getLog(plugin); + Integer severity = status.getSeverity(); + if (severity == IStatus.ERROR) + pluginLog.error(status.getMessage(), status.getException()); + else if (severity == IStatus.WARNING) + pluginLog.warn(status.getMessage(), status.getException()); + else if (severity == IStatus.INFO) + pluginLog.info(status.getMessage(), status.getException()); + else if (severity == IStatus.CANCEL) + if (pluginLog.isDebugEnabled()) + pluginLog.debug(status.getMessage(), status.getException()); + + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ColumnViewerComparator.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ColumnViewerComparator.java new file mode 100644 index 000000000..8db5d4fe8 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ColumnViewerComparator.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import java.util.Comparator; + +import org.eclipse.jface.viewers.ColumnViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerComparator; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; + +/** Generic column viewer sorter */ +public class ColumnViewerComparator extends ViewerComparator { + private static final long serialVersionUID = -2266218906355859909L; + + public static final int ASC = 1; + + public static final int NONE = 0; + + public static final int DESC = -1; + + private int direction = 0; + + private TableViewerColumn column; + + private ColumnViewer viewer; + + public ColumnViewerComparator(TableViewerColumn column, + Comparator comparator) { + super(comparator); + this.column = column; + this.viewer = column.getViewer(); + this.column.getColumn().addSelectionListener(new SelectionAdapter() { + private static final long serialVersionUID = 7586796298965472189L; + + public void widgetSelected(SelectionEvent e) { + if (ColumnViewerComparator.this.viewer.getComparator() != null) { + if (ColumnViewerComparator.this.viewer.getComparator() == ColumnViewerComparator.this) { + int tdirection = ColumnViewerComparator.this.direction; + + if (tdirection == ASC) { + setSortDirection(DESC); + } else if (tdirection == DESC) { + setSortDirection(NONE); + } + } else { + setSortDirection(ASC); + } + } else { + setSortDirection(ASC); + } + } + }); + } + + private void setSortDirection(int direction) { + if (direction == NONE) { + column.getColumn().getParent().setSortColumn(null); + column.getColumn().getParent().setSortDirection(SWT.NONE); + viewer.setComparator(null); + } else { + column.getColumn().getParent().setSortColumn(column.getColumn()); + this.direction = direction; + + if (direction == ASC) { + column.getColumn().getParent().setSortDirection(SWT.DOWN); + } else { + column.getColumn().getParent().setSortDirection(SWT.UP); + } + + if (viewer.getComparator() == this) { + viewer.refresh(); + } else { + viewer.setComparator(this); + } + + } + } + + @SuppressWarnings("unchecked") + public int compare(Viewer viewer, Object e1, Object e2) { + return direction * getComparator().compare((T) e1, (T) e2); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseArgeoMonitor.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseArgeoMonitor.java new file mode 100644 index 000000000..7c0b39884 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseArgeoMonitor.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.argeo.ArgeoMonitor; +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Wraps an Eclipse {@link IProgressMonitor} so that it can be passed to + * framework agnostic Argeo routines. + */ +public class EclipseArgeoMonitor implements ArgeoMonitor { + private final IProgressMonitor progressMonitor; + + public EclipseArgeoMonitor(IProgressMonitor progressMonitor) { + this.progressMonitor = progressMonitor; + } + + public void beginTask(String name, int totalWork) { + progressMonitor.beginTask(name, totalWork); + } + + public void done() { + progressMonitor.done(); + } + + public boolean isCanceled() { + return progressMonitor.isCanceled(); + } + + public void setCanceled(boolean value) { + progressMonitor.setCanceled(value); + } + + public void setTaskName(String name) { + progressMonitor.setTaskName(name); + } + + public void subTask(String name) { + progressMonitor.subTask(name); + } + + public void worked(int work) { + progressMonitor.worked(work); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseUiUtils.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseUiUtils.java new file mode 100644 index 000000000..8e1c7e632 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/EclipseUiUtils.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +/** Utilities to simplify UI development. */ +public class EclipseUiUtils { + /** + * Create a label and a text field for a grid layout, the text field grabing + * excess horizontal + * + * @param parent + * the parent composite + * @param label + * the lable to display + * @param modifyListener + * a {@link ModifyListener} to listen on events on the text, can + * be null + * @return the created text + * + */ + // FIXME why was this deprecated. + // * @ deprecated use { @ link #createGridLT(Composite, String)} instead + // @ Deprecated + public static Text createGridLT(Composite parent, String label, + ModifyListener modifyListener) { + Label lbl = new Label(parent, SWT.LEAD); + lbl.setText(label); + lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + Text txt = new Text(parent, SWT.LEAD | SWT.BORDER); + txt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (modifyListener != null) + txt.addModifyListener(modifyListener); + return txt; + } + + /** + * Create a label and a text field for a grid layout, the text field + * grabbing excess horizontal + */ + public static Text createGridLT(Composite parent, String label) { + return createGridLT(parent, label, null); + } + + /** + * Creates one label and a text field not editable with background color of + * the parent (like a label but with selectable text) + */ + public static Text createGridLL(Composite parent, String label, String text) { + Text txt = createGridLT(parent, label); + txt.setText(text); + txt.setEditable(false); + txt.setBackground(parent.getBackground()); + return txt; + } + + /** + * Create a label and a text field with password display for a grid layout, + * the text field grabbing excess horizontal + */ + public static Text createGridLP(Composite parent, String label, + ModifyListener modifyListener) { + Label lbl = new Label(parent, SWT.LEAD); + lbl.setText(label); + lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + Text txt = new Text(parent, SWT.LEAD | SWT.BORDER | SWT.PASSWORD); + txt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + if (txt != null) + txt.addModifyListener(modifyListener); + return txt; + } + + /** Shortcut to retrieve default italic font from display */ + public static Font getItalicFont(Composite parent) { + return JFaceResources.getFontRegistry().defaultFontDescriptor() + .setStyle(SWT.ITALIC).createFont(parent.getDisplay()); + } + + /** Shortcut to retrieve default bold font from display */ + public static Font getBoldFont(Composite parent) { + return JFaceResources.getFontRegistry().defaultFontDescriptor() + .setStyle(SWT.BOLD).createFont(parent.getDisplay()); + } + + /** Shortcut to retrieve default bold italic font from display */ + public static Font getBoldItalicFont(Composite parent) { + return JFaceResources.getFontRegistry().defaultFontDescriptor() + .setStyle(SWT.BOLD | SWT.ITALIC) + .createFont(parent.getDisplay()); + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/Error.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/Error.java new file mode 100644 index 000000000..03b047001 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/Error.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.eclipse.swt.widgets.Shell; + +/** + * @deprecated deprecated because of poor naming, use {@link ErrorFeedback} + * instead + */ +@SuppressWarnings("serial") +@Deprecated +public class Error extends ErrorFeedback { + + public Error(Shell parentShell, String message, Throwable e) { + super(parentShell, message, e); + // TODO Auto-generated constructor stub + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ErrorFeedback.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ErrorFeedback.java new file mode 100644 index 000000000..895e8b866 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/ErrorFeedback.java @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.jface.dialogs.IMessageProvider; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.PlatformUI; + +/** Generic error dialog to be used in try/catch blocks */ +@SuppressWarnings("serial") +public class ErrorFeedback extends TitleAreaDialog { + private final static Log log = LogFactory.getLog(ErrorFeedback.class); + + private final String message; + private final Throwable exception; + + public static void show(String message, Throwable e) { + // rethrow ThreaDeath in order to make sure that RAP will properly clean + // up the UI thread + if (e instanceof ThreadDeath) + throw (ThreadDeath) e; + + new ErrorFeedback(getDisplay().getActiveShell(), message, e).open(); + } + + public static void show(String message) { + new ErrorFeedback(getDisplay().getActiveShell(), message, null).open(); + } + + /** Tries to find a display */ + private static Display getDisplay() { + try { + Display display = PlatformUI.getWorkbench().getDisplay(); + if (display != null) + return display; + else + return Display.getDefault(); + } catch (Exception e) { + return Display.getCurrent(); + } + } + + public ErrorFeedback(Shell parentShell, String message, Throwable e) { + super(parentShell); + this.message = message; + this.exception = e; + log.error(message, e); + } + + protected Point getInitialSize() { + if (exception != null) + return new Point(800, 600); + else + return new Point(400, 300); + } + + @Override + 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, true)); + + setMessage(message != null ? message + + (exception != null ? ": " + exception.getMessage() : "") + : exception != null ? exception.getMessage() : "Unkown Error", + IMessageProvider.ERROR); + + if (exception != null) { + Text stack = new Text(composite, SWT.MULTI | SWT.LEAD | SWT.BORDER + | SWT.V_SCROLL | SWT.H_SCROLL); + stack.setEditable(false); + stack.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + StringWriter sw = new StringWriter(); + exception.printStackTrace(new PrintWriter(sw)); + stack.setText(sw.toString()); + } + + parent.pack(); + return composite; + } + + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText("Error"); + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/FileProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/FileProvider.java new file mode 100644 index 000000000..91ca71969 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/FileProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import java.io.InputStream; + +/** + * Used for file download : subclasses must implement model specific methods to + * get a byte array representing a file given is ID. + */ +@Deprecated +public interface FileProvider { + + public byte[] getByteArrayFileFromId(String fileId); + + public InputStream getInputStreamFromFileId(String fileId); + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/GenericTableComparator.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/GenericTableComparator.java new file mode 100644 index 000000000..a4179cbee --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/GenericTableComparator.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerComparator; + +public abstract class GenericTableComparator extends ViewerComparator { + private static final long serialVersionUID = -1175894935075325810L; + protected int propertyIndex; + public static final int ASCENDING = 0, DESCENDING = 1; + protected int direction = DESCENDING; + + /** + * Creates an instance of a sorter for TableViewer. + * + * @param defaultColumn + * the default sorter column + */ + + public GenericTableComparator(int defaultColumnIndex, int direction) { + propertyIndex = defaultColumnIndex; + this.direction = direction; + } + + 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; + direction = DESCENDING; + } + } + + /** + * Must be Overriden in each view. + */ + public abstract int compare(Viewer viewer, Object e1, Object e2); +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/TreeParent.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/TreeParent.java new file mode 100644 index 000000000..2dfd2e60c --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/TreeParent.java @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui; + +import java.util.ArrayList; +import java.util.List; + +/** Parent / children semantic to be used for simple UI Tree structure */ +public class TreeParent { + private String name; + private TreeParent parent; + + private List children; + + /** + * Unique id within the context of a tree display. If set, equals() and + * hashCode() methods will be based on it + */ + private String path = null; + + /** False until at least one child has been added, then true until cleared */ + private boolean loaded = false; + + public TreeParent(String name) { + this.name = name; + children = new ArrayList(); + } + + public synchronized void addChild(Object child) { + loaded = true; + children.add(child); + if (child instanceof TreeParent) + ((TreeParent) child).setParent(this); + } + + /** + * Remove this child. The child is disposed. + */ + public synchronized void removeChild(Object child) { + children.remove(child); + if (child instanceof TreeParent) { + ((TreeParent) child).dispose(); + } + } + + public synchronized void clearChildren() { + for (Object obj : children) { + if (obj instanceof TreeParent) + ((TreeParent) obj).dispose(); + } + loaded = false; + children.clear(); + } + + /** + * If overridden, super.dispose() must be called, typically + * after custom cleaning. + */ + public synchronized void dispose() { + clearChildren(); + parent = null; + children = null; + } + + public synchronized Object[] getChildren() { + return children.toArray(new Object[children.size()]); + } + + @SuppressWarnings("unchecked") + public synchronized List getChildrenOfType(Class clss) { + List lst = new ArrayList(); + for (Object obj : children) { + if (clss.isAssignableFrom(obj.getClass())) + lst.add((T) obj); + } + return lst; + } + + public synchronized boolean hasChildren() { + return children.size() > 0; + } + + public Object getChildByName(String name) { + for (Object child : children) { + if (child.toString().equals(name)) + return child; + } + return null; + } + + public synchronized Boolean isLoaded() { + return loaded; + } + + public String getName() { + return name; + } + + public void setParent(TreeParent parent) { + this.parent = parent; + if (parent != null && parent.path != null) + this.path = parent.path + '/' + name; + else + this.path = '/' + name; + } + + public TreeParent getParent() { + return parent; + } + + public String toString() { + return getName(); + } + + public int compareTo(TreeParent o) { + return name.compareTo(o.name); + } + + @Override + public int hashCode() { + if (path != null) + return path.hashCode(); + else + return name.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (path != null && obj instanceof TreeParent) + return path.equals(((TreeParent) obj).path); + else + return name.equals(obj.toString()); + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/Error.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/Error.java new file mode 100644 index 000000000..918bfd244 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/Error.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.dialogs; + +import org.eclipse.swt.widgets.Shell; + +/** + * Generic error dialog to be used in try/catch blocks + * + * @deprecated use {@link org.argeo.eclipse.ui.ErrorFeedback} instead. + */ +public class Error extends org.argeo.eclipse.ui.ErrorFeedback { + private static final long serialVersionUID = -93864960090248736L; + + public Error(Shell parentShell, String message, Throwable e) { + super(parentShell, message, e); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/SingleValue.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/SingleValue.java new file mode 100644 index 000000000..b58f44694 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/dialogs/SingleValue.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.dialogs; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IMessageProvider; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** Dialog retrieve a single value. */ +public class SingleValue extends TitleAreaDialog { + private static final long serialVersionUID = 2843538207460082349L; + + private Text valueT; + private String value; + private final String title, message, label; + private final Boolean multiline; + + public static String ask(String label, String message) { + SingleValue svd = new SingleValue(label, message); + if (svd.open() == Dialog.OK) + return svd.getString(); + else + return null; + } + + public static Long askLong(String label, String message) { + SingleValue svd = new SingleValue(label, message); + if (svd.open() == Dialog.OK) + return svd.getLong(); + else + return null; + } + + public static Double askDouble(String label, String message) { + SingleValue svd = new SingleValue(label, message); + if (svd.open() == Dialog.OK) + return svd.getDouble(); + else + return null; + } + + public SingleValue(String label, String message) { + this(Display.getDefault().getActiveShell(), label, message, label, + false); + } + + public SingleValue(Shell parentShell, String title, String message, + String label, Boolean multiline) { + super(parentShell); + this.title = title; + this.message = message; + this.label = label; + this.multiline = multiline; + } + + 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)); + valueT = createLT(composite, label); + + setMessage(message, IMessageProvider.NONE); + + parent.pack(); + return composite; + } + + @Override + protected void okPressed() { + value = valueT.getText(); + 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 + | (multiline ? SWT.MULTI : SWT.NONE)); + text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + return text; + } + + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(title); + } + + public String getString() { + return value; + } + + public Long getLong() { + return Long.valueOf(getString()); + } + + public Double getDouble() { + return Double.valueOf(getString()); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java new file mode 100644 index 000000000..ef2b8a845 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AbstractNodeContentProvider.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +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.ArgeoException; +import org.argeo.eclipse.ui.AbstractTreeContentProvider; + +/** Canonic implementation of tree content provider manipulating JCR nodes. */ +public abstract class AbstractNodeContentProvider extends + AbstractTreeContentProvider { + private final static Log log = LogFactory + .getLog(AbstractNodeContentProvider.class); + + private Session session; + + public AbstractNodeContentProvider(Session session) { + this.session = session; + } + + /** + * Whether this path is a base path (and thus has no parent). By default it + * returns true if path is '/' (root node) + */ + protected Boolean isBasePath(String path) { + // root node + return path.equals("/"); + } + + @Override + public Object[] getChildren(Object element) { + Object[] children; + if (element instanceof Node) { + try { + Node node = (Node) element; + children = getChildren(node); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get children of " + element, e); + } + } else if (element instanceof WrappedNode) { + WrappedNode wrappedNode = (WrappedNode) element; + try { + children = getChildren(wrappedNode.getNode()); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get children of " + + wrappedNode, e); + } + } else if (element instanceof NodesWrapper) { + NodesWrapper node = (NodesWrapper) element; + children = node.getChildren(); + } else { + children = super.getChildren(element); + } + + children = sort(element, children); + return children; + } + + /** Do not sort by default. To be overidden to provide custom sort. */ + protected Object[] sort(Object parent, Object[] children) { + return children; + } + + /** + * To be overridden in order to filter out some nodes. Does nothing by + * default. The provided list is a temporary one and can thus be modified + * directly . (e.g. via an iterator) + */ + protected List filterChildren(List children) + throws RepositoryException { + return children; + } + + protected Object[] getChildren(Node node) throws RepositoryException { + List nodes = new ArrayList(); + for (NodeIterator nit = node.getNodes(); nit.hasNext();) + nodes.add(nit.nextNode()); + nodes = filterChildren(nodes); + return nodes.toArray(); + } + + @Override + public Object getParent(Object element) { + if (element instanceof Node) { + Node node = (Node) element; + try { + String path = node.getPath(); + if (isBasePath(path)) + return null; + else + return node.getParent(); + } catch (RepositoryException e) { + log.warn("Cannot get parent of " + element + ": " + e); + return null; + } + } else if (element instanceof WrappedNode) { + WrappedNode wrappedNode = (WrappedNode) element; + return wrappedNode.getParent(); + } else if (element instanceof NodesWrapper) { + NodesWrapper nodesWrapper = (NodesWrapper) element; + return this.getParent(nodesWrapper.getNode()); + } + return super.getParent(element); + } + + @Override + public boolean hasChildren(Object element) { + try { + if (element instanceof Node) { + Node node = (Node) element; + return node.hasNodes(); + } else if (element instanceof WrappedNode) { + WrappedNode wrappedNode = (WrappedNode) element; + return wrappedNode.getNode().hasNodes(); + } else if (element instanceof NodesWrapper) { + NodesWrapper nodesWrapper = (NodesWrapper) element; + return nodesWrapper.hasChildren(); + } + + } catch (RepositoryException e) { + throw new ArgeoException("Cannot check whether " + element + + " has children", e); + } + return super.hasChildren(element); + } + + public Session getSession() { + return session; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java new file mode 100644 index 000000000..100ceb444 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/AsyncUiEventListener.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.RepositoryException; +import javax.jcr.observation.Event; +import javax.jcr.observation.EventIterator; +import javax.jcr.observation.EventListener; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.argeo.ArgeoException; +import org.eclipse.swt.widgets.Display; + +/** {@link EventListener} which simplifies running actions within the UI thread. */ +public abstract class AsyncUiEventListener implements EventListener { +// private final static Log logSuper = LogFactory +// .getLog(AsyncUiEventListener.class); + private final Log logThis = LogFactory.getLog(getClass()); + + private final Display display; + + public AsyncUiEventListener(Display display) { + super(); + this.display = display; + } + + /** Called asynchronously in the UI thread. */ + protected abstract void onEventInUiThread(List events) + throws RepositoryException; + + /** + * Whether these events should be processed in the UI or skipped with no UI + * job created. + */ + protected Boolean willProcessInUiThread(List events) + throws RepositoryException { + return true; + } + + protected Log getLog() { + return logThis; + } + + public final void onEvent(final EventIterator eventIterator) { + final List events = new ArrayList(); + while (eventIterator.hasNext()) + events.add(eventIterator.nextEvent()); + + if (logThis.isTraceEnabled()) + logThis.trace("Received " + events.size() + " events"); + + try { + if (!willProcessInUiThread(events)) + return; + } catch (RepositoryException e) { + throw new ArgeoException("Cannot test skip events " + events, e); + } + +// Job job = new Job("JCR Events") { +// protected IStatus run(IProgressMonitor monitor) { +// if (display.isDisposed()) { +// logSuper.warn("Display is disposed cannot update UI"); +// return Status.CANCEL_STATUS; +// } + + display.asyncExec(new Runnable() { + public void run() { + try { + onEventInUiThread(events); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot process events " + + events, e); + } + } + }); + +// return Status.OK_STATUS; +// } +// }; +// job.schedule(); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java new file mode 100644 index 000000000..76fac1256 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/DefaultNodeLabelProvider.java @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.RepositoryException; +import javax.jcr.nodetype.NodeType; + +import org.argeo.ArgeoException; +import org.argeo.jcr.ArgeoTypes; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.swt.graphics.Image; + +/** Provides reasonable overridable defaults for know JCR types. */ +public class DefaultNodeLabelProvider extends ColumnLabelProvider { + // Images + /** + * @deprecated Use {@link JcrImages#NODE} instead + */ + public final static Image NODE = JcrImages.NODE; + /** + * @deprecated Use {@link JcrImages#FOLDER} instead + */ + public final static Image FOLDER = JcrImages.FOLDER; + /** + * @deprecated Use {@link JcrImages#FILE} instead + */ + public final static Image FILE = JcrImages.FILE; + /** + * @deprecated Use {@link JcrImages#BINARY} instead + */ + public final static Image BINARY = JcrImages.BINARY; + /** + * @deprecated Use {@link JcrImages#HOME} instead + */ + public final static Image HOME = JcrImages.HOME; + + public String getText(Object element) { + try { + if (element instanceof Node) { + return getText((Node) element); + } else if (element instanceof WrappedNode) { + return getText(((WrappedNode) element).getNode()); + } else if (element instanceof NodesWrapper) { + return getText(((NodesWrapper) element).getNode()); + } + return super.getText(element); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get text for of " + element, e); + } + } + + 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 + return node.getName(); + } + + @Override + public Image getImage(Object element) { + try { + if (element instanceof Node) { + return getImage((Node) element); + } else if (element instanceof WrappedNode) { + return getImage(((WrappedNode) element).getNode()); + } else if (element instanceof NodesWrapper) { + return getImage(((NodesWrapper) element).getNode()); + } + } catch (RepositoryException e) { + throw new ArgeoException("Cannot retrieve image for " + element, e); + } + return super.getImage(element); + } + + protected Image getImage(Node node) throws RepositoryException { + // optimized order + if (node.getPrimaryNodeType().isNodeType(NodeType.NT_FILE)) + return JcrImages.FILE; + else if (node.getPrimaryNodeType().isNodeType(NodeType.NT_FOLDER)) + return JcrImages.FOLDER; + else if (node.getPrimaryNodeType().isNodeType(NodeType.NT_RESOURCE)) + return JcrImages.BINARY; + else if (node.isNodeType(ArgeoTypes.ARGEO_USER_HOME)) + return JcrImages.HOME; + else + return JcrImages.NODE; + } + + @Override + public String getToolTipText(Object element) { + try { + if (element instanceof Node) { + return getToolTipText((Node) element); + } else if (element instanceof WrappedNode) { + return getToolTipText(((WrappedNode) element).getNode()); + } else if (element instanceof NodesWrapper) { + return getToolTipText(((NodesWrapper) element).getNode()); + } + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get tooltip for " + element, e); + } + return super.getToolTipText(element); + } + + protected String getToolTipText(Node node) throws RepositoryException { + return null; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrImages.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrImages.java new file mode 100644 index 000000000..255ea7a25 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrImages.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import org.eclipse.swt.graphics.Image; + +/** Shared icons. */ +public class JcrImages { + public final static Image NODE = JcrUiPlugin.getImageDescriptor( + "icons/node.gif").createImage(); + public final static Image FOLDER = JcrUiPlugin.getImageDescriptor( + "icons/folder.gif").createImage(); + public final static Image FILE = JcrUiPlugin.getImageDescriptor( + "icons/file.gif").createImage(); + public final static Image BINARY = JcrUiPlugin.getImageDescriptor( + "icons/binary.png").createImage(); + public final static Image HOME = JcrUiPlugin.getImageDescriptor( + "icons/home.gif").createImage(); + public final static Image SORT = JcrUiPlugin.getImageDescriptor( + "icons/sort.gif").createImage(); + + public final static Image REPOSITORIES = JcrUiPlugin.getImageDescriptor( + "icons/repositories.gif").createImage(); + public final static Image REPOSITORY_DISCONNECTED = JcrUiPlugin + .getImageDescriptor("icons/repository_disconnected.gif") + .createImage(); + public final static Image REPOSITORY_CONNECTED = JcrUiPlugin + .getImageDescriptor("icons/repository_connected.gif").createImage(); + public final static Image REMOTE_DISCONNECTED = JcrUiPlugin + .getImageDescriptor("icons/remote_disconnected.gif").createImage(); + public final static Image REMOTE_CONNECTED = JcrUiPlugin + .getImageDescriptor("icons/remote_connected.gif").createImage(); + public final static Image WORKSPACE_DISCONNECTED = JcrUiPlugin + .getImageDescriptor("icons/workspace_disconnected.png") + .createImage(); + public final static Image WORKSPACE_CONNECTED = JcrUiPlugin + .getImageDescriptor("icons/workspace_connected.png").createImage(); + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java new file mode 100644 index 000000000..c9777cefd --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrPreferenceStore.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Properties; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyIterator; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.version.VersionManager; + +import org.apache.commons.io.IOUtils; +import org.argeo.ArgeoException; +import org.argeo.jcr.ArgeoNames; +import org.argeo.jcr.ArgeoTypes; +import org.argeo.jcr.JcrUtils; +import org.argeo.jcr.UserJcrUtils; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.ui.preferences.ScopedPreferenceStore; +import org.osgi.framework.BundleContext; + +/** + * Persist preferences as key/value pairs under ~/argeo:preferences.
+ * TODO: better integrate JCR and Eclipse:
+ * - typing
+ * - use eclipse preferences
+ * - better integrate with {@link ScopedPreferenceStore} provided by RAP + */ +public class JcrPreferenceStore extends PreferenceStore implements ArgeoNames { + private Session session; + private BundleContext bundleContext; + + /** Retrieves the preference node */ + protected Node getPreferenceNode() { + try { + if (session.hasPendingChanges()) + session.save(); + Node userHome = UserJcrUtils.getUserHome(session); + if (userHome == null) + throw new ArgeoException("No user home for " + + session.getUserID()); + Node preferences; + if (!userHome.hasNode(ARGEO_PREFERENCES)) { + preferences = userHome.addNode(ARGEO_PREFERENCES); + preferences.addMixin(ArgeoTypes.ARGEO_PREFERENCE_NODE); + session.save(); + } else + preferences = userHome.getNode(ARGEO_PREFERENCES); + + String pluginPreferencesName = bundleContext.getBundle() + .getSymbolicName(); + Node pluginPreferences; + if (!preferences.hasNode(pluginPreferencesName)) { + VersionManager vm = session.getWorkspace().getVersionManager(); + vm.checkout(preferences.getPath()); + pluginPreferences = preferences.addNode(pluginPreferencesName); + pluginPreferences.addMixin(ArgeoTypes.ARGEO_PREFERENCE_NODE); + session.save(); + vm.checkin(preferences.getPath()); + } else + pluginPreferences = preferences.getNode(pluginPreferencesName); + return pluginPreferences; + } catch (RepositoryException e) { + e.printStackTrace(); + JcrUtils.discardQuietly(session); + throw new ArgeoException("Cannot retrieve preferences", e); + } + + } + + @Override + public void load() throws IOException { + ByteArrayOutputStream out = null; + ByteArrayInputStream in = null; + try { + Properties props = new Properties(); + PropertyIterator it = getPreferenceNode().getProperties(); + while (it.hasNext()) { + Property p = it.nextProperty(); + if (!p.isMultiple() && !p.getDefinition().isProtected()) { + props.setProperty(p.getName(), p.getValue().getString()); + } + } + out = new ByteArrayOutputStream(); + props.store(out, ""); + in = new ByteArrayInputStream(out.toByteArray()); + load(in); + } catch (Exception e) { + e.printStackTrace(); + throw new ArgeoException("Cannot load preferences", e); + } finally { + IOUtils.closeQuietly(in); + IOUtils.closeQuietly(out); + } + } + + @Override + public void save() throws IOException { + ByteArrayOutputStream out = null; + ByteArrayInputStream in = null; + Node pluginPreferences = null; + try { + out = new ByteArrayOutputStream(); + save(out, ""); + in = new ByteArrayInputStream(out.toByteArray()); + Properties props = new Properties(); + props.load(in); + pluginPreferences = getPreferenceNode(); + VersionManager vm = pluginPreferences.getSession().getWorkspace() + .getVersionManager(); + vm.checkout(pluginPreferences.getPath()); + for (Object key : props.keySet()) { + String name = key.toString(); + String value = props.getProperty(name); + pluginPreferences.setProperty(name, value); + } + JcrUtils.updateLastModified(pluginPreferences); + pluginPreferences.getSession().save(); + vm.checkin(pluginPreferences.getPath()); + } catch (Exception e) { + JcrUtils.discardUnderlyingSessionQuietly(pluginPreferences); + throw new ArgeoException("Cannot save preferences", e); + } finally { + IOUtils.closeQuietly(in); + IOUtils.closeQuietly(out); + } + } + + public void init() { + try { + load(); + } catch (IOException e) { + throw new ArgeoException("Cannot initialize preference store", e); + } + } + + public void setSession(Session session) { + this.session = session; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java new file mode 100644 index 000000000..adfa1a4f4 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiPlugin.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import java.util.ResourceBundle; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +public class JcrUiPlugin extends AbstractUIPlugin { + private final static Log log = LogFactory.getLog(JcrUiPlugin.class); + + public final static String ID = "org.argeo.eclipse.ui.jcr"; + + private ResourceBundle messages; + + private static JcrUiPlugin plugin; + + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + messages = ResourceBundle.getBundle("org.argeo.eclipse.ui.jcr"); + } + + public static JcrUiPlugin getDefault() { + return plugin; + } + + public static ImageDescriptor getImageDescriptor(String path) { + return imageDescriptorFromPlugin(ID, path); + } + + /** Returns the internationalized label for the given key */ + public static String getMessage(String key) { + try { + return getDefault().messages.getString(key); + } catch (NullPointerException npe) { + log.warn(key + " not found."); + return key; + } + } + + /** + * Gives access to the internationalization message bundle. Returns null in + * case the ClientUiPlugin is not started (for JUnit tests, by instance) + */ + public static ResourceBundle getMessagesBundle() { + if (getDefault() != null) + // To avoid NPE + return getDefault().messages; + else + return null; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiUtils.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiUtils.java new file mode 100644 index 000000000..8ee13aab0 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/JcrUiUtils.java @@ -0,0 +1,146 @@ +package org.argeo.eclipse.ui.jcr; + +import java.util.Calendar; + +import javax.jcr.Node; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.jcr.lists.NodeViewerComparator; +import org.argeo.eclipse.ui.jcr.lists.RowViewerComparator; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.widgets.Table; + +/** Utility methods to simplify UI development using eclipse and JCR. */ +public class JcrUiUtils { + + /** + * Centralizes management of updating property value. Among other to avoid + * infinite loop when the new value is the same as the ones that is already + * stored in JCR. + * + * @return true if the value as changed + */ + public static boolean setJcrProperty(Node node, String propName, + int propertyType, Object value) { + try { + // int propertyType = getPic().getProperty(propName).getType(); + switch (propertyType) { + case PropertyType.STRING: + if ("".equals((String) value) + && (!node.hasProperty(propName) || node + .hasProperty(propName) + && "".equals(node.getProperty(propName) + .getString()))) + // workaround the fact that the Text widget value cannot be + // set to null + return false; + else if (node.hasProperty(propName) + && node.getProperty(propName).getString() + .equals((String) value)) + // nothing changed yet + return false; + else { + node.setProperty(propName, (String) value); + return true; + } + case PropertyType.BOOLEAN: + if (node.hasProperty(propName) + && node.getProperty(propName).getBoolean() == (Boolean) value) + // nothing changed yet + return false; + else { + node.setProperty(propName, (Boolean) value); + return true; + } + case PropertyType.DATE: + if (node.hasProperty(propName) + && node.getProperty(propName).getDate() + .equals((Calendar) value)) + // nothing changed yet + return false; + else { + node.setProperty(propName, (Calendar) value); + return true; + } + case PropertyType.LONG: + Long lgValue = (Long) value; + + if (lgValue == null) + lgValue = 0L; + + if (node.hasProperty(propName) + && node.getProperty(propName).getLong() == lgValue) + // nothing changed yet + return false; + else { + node.setProperty(propName, lgValue); + return true; + } + + default: + throw new ArgeoException("Unimplemented property save"); + } + } catch (RepositoryException re) { + throw new ArgeoException("Unexpected error while setting property", + re); + } + } + + /** + * Creates a new selection adapter in order to provide sorting abitily on a + * swt table that display a row list + **/ + public static SelectionAdapter getRowSelectionAdapter(final int index, + final int propertyType, final String selectorName, + final String propertyName, final RowViewerComparator comparator, + final TableViewer viewer) { + SelectionAdapter selectionAdapter = new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Table table = viewer.getTable(); + comparator.setColumn(propertyType, selectorName, propertyName); + 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; + } + + /** + * Creates a new selection adapter in order to provide sorting abitily on a + * swt table that display a row list + **/ + public static SelectionAdapter getNodeSelectionAdapter(final int index, + final int propertyType, final String propertyName, + final NodeViewerComparator comparator, final TableViewer viewer) { + SelectionAdapter selectionAdapter = new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Table table = viewer.getTable(); + comparator.setColumn(propertyType, propertyName); + 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; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodeElementComparer.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodeElementComparer.java new file mode 100644 index 000000000..f284b9c13 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodeElementComparer.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; +import org.eclipse.jface.viewers.IElementComparer; + +/** Element comparer for JCR node, to be used in JFace viewers. */ +public class NodeElementComparer implements IElementComparer { + + public boolean equals(Object a, Object b) { + try { + if ((a instanceof Node) && (b instanceof Node)) { + Node nodeA = (Node) a; + Node nodeB = (Node) b; + return nodeA.getIdentifier().equals(nodeB.getIdentifier()); + } else { + return a.equals(b); + } + } catch (RepositoryException e) { + throw new ArgeoException("Cannot compare nodes", e); + } + } + + public int hashCode(Object element) { + try { + if (element instanceof Node) + return ((Node) element).getIdentifier().hashCode(); + return element.hashCode(); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get hash code", e); + } + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodesWrapper.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodesWrapper.java new file mode 100644 index 000000000..dcd3b42f6 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/NodesWrapper.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; + +/** + * Element of tree which is based on a node, but whose children are not + * necessarily this node children. + */ +public class NodesWrapper { + private final Node node; + + public NodesWrapper(Node node) { + super(); + this.node = node; + } + + protected NodeIterator getNodeIterator() throws RepositoryException { + return node.getNodes(); + } + + protected List getWrappedNodes() throws RepositoryException { + List nodes = new ArrayList(); + for (NodeIterator nit = getNodeIterator(); nit.hasNext();) + nodes.add(new WrappedNode(this, nit.nextNode())); + return nodes; + } + + public Object[] getChildren() { + try { + return getWrappedNodes().toArray(); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get wrapped children", e); + } + } + + /** + * @return true by default because we don't want to compute the wrapped + * nodes twice + */ + public Boolean hasChildren() { + return true; + } + + public Node getNode() { + return node; + } + + @Override + public int hashCode() { + return node.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof NodesWrapper) + return node.equals(((NodesWrapper) obj).getNode()); + else + return false; + } + + public String toString() { + return "nodes wrapper based on " + node; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java new file mode 100644 index 000000000..0dad19cfe --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/SimpleNodeContentProvider.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.argeo.ArgeoException; +import org.argeo.jcr.JcrUtils; + +/** Simple JCR node content provider taking a list of String as base path. */ +public class SimpleNodeContentProvider extends AbstractNodeContentProvider { + private final List basePaths; + private Boolean mkdirs = false; + + public SimpleNodeContentProvider(Session session, String... basePaths) { + this(session, Arrays.asList(basePaths)); + } + + public SimpleNodeContentProvider(Session session, List basePaths) { + super(session); + this.basePaths = basePaths; + } + + @Override + protected Boolean isBasePath(String path) { + if (basePaths.contains(path)) + return true; + return super.isBasePath(path); + } + + public Object[] getElements(Object inputElement) { + try { + List baseNodes = new ArrayList(); + for (String basePath : basePaths) + if (mkdirs && !getSession().itemExists(basePath)) + baseNodes.add(JcrUtils.mkdirs(getSession(), basePath)); + else + baseNodes.add(getSession().getNode(basePath)); + return baseNodes.toArray(); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot get base nodes for " + basePaths, + e); + } + } + + public List getBasePaths() { + return basePaths; + } + + public void setMkdirs(Boolean mkdirs) { + this.mkdirs = mkdirs; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/WrappedNode.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/WrappedNode.java new file mode 100644 index 000000000..c0e197336 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/WrappedNode.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr; + +import javax.jcr.Node; + +/** Wraps a node (created from a {@link NodesWrapper}) */ +public class WrappedNode { + private final NodesWrapper parent; + private final Node node; + + public WrappedNode(NodesWrapper parent, Node node) { + super(); + this.parent = parent; + this.node = node; + } + + public NodesWrapper getParent() { + return parent; + } + + public Node getNode() { + return node; + } + + public String toString() { + return "wrapped " + node; + } + + @Override + public int hashCode() { + return node.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof WrappedNode) + return node.equals(((WrappedNode) obj).getNode()); + else + return false; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java new file mode 100644 index 000000000..5fc7db031 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/AddFileFolder.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.commands; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.nodetype.NodeType; + +import org.argeo.eclipse.ui.ErrorFeedback; +import org.argeo.eclipse.ui.dialogs.SingleValue; +import org.argeo.eclipse.ui.jcr.JcrUiPlugin; +import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.handlers.HandlerUtil; + +/** Adds a node of type nt:folder */ +public class AddFileFolder extends AbstractHandler { + + public Object execute(ExecutionEvent event) throws ExecutionException { + ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) + .getActivePage().getSelection(); + AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil + .getActiveWorkbenchWindow(event).getActivePage() + .findView(HandlerUtil.getActivePartId(event)); + if (selection != null && !selection.isEmpty() + && selection instanceof IStructuredSelection) { + Object obj = ((IStructuredSelection) selection).getFirstElement(); + + if (obj instanceof Node) { + String folderName = SingleValue.ask("Folder name", + "Enter folder name"); + if (folderName != null) { + Node parentNode = (Node) obj; + try { + Node newNode = parentNode.addNode(folderName, + NodeType.NT_FOLDER); + view.nodeAdded(parentNode, newNode); + parentNode.getSession().save(); + } catch (RepositoryException e) { + ErrorFeedback.show("Cannot create folder " + folderName + + " under " + parentNode, e); + } + } + } else { + ErrorFeedback.show(JcrUiPlugin + .getMessage("errorUnvalidNtFolderNodeType")); + } + } + return null; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java new file mode 100644 index 000000000..168674806 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/DeleteNodes.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.commands; + +import java.util.Iterator; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.ErrorFeedback; +import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.handlers.HandlerUtil; + +/** + * Deletes the selected nodes and refresh the corresponding AbstractJcrView. + * Note that no model specific check is done to see if the node can be removed + * or not. Extend or override to implement specific behaviour. + */ +public class DeleteNodes extends AbstractHandler { + public final static String ID = "org.argeo.eclipse.ui.jcr.deleteNodes"; + public final static String DEFAULT_LABEL = "Delete selected nodes"; + + public Object execute(ExecutionEvent event) throws ExecutionException { + ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) + .getActivePage().getSelection(); + AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil + .getActiveWorkbenchWindow(event).getActivePage() + .findView(HandlerUtil.getActivePartId(event)); + + if (selection != null && selection instanceof IStructuredSelection) { + Iterator it = ((IStructuredSelection) selection).iterator(); + Object obj = null; + Node ancestor = null; + try { + while (it.hasNext()) { + obj = it.next(); + if (obj instanceof Node) { + Node node = (Node) obj; + Node parentNode = node.getParent(); + node.remove(); + node.getSession().save(); + ancestor = getOlder(ancestor, parentNode); + } + } + if (ancestor != null) + view.nodeRemoved(ancestor); + } catch (Exception e) { + ErrorFeedback.show("Cannot delete node " + obj, e); + } + } + return null; + } + + protected Node getOlder(Node A, Node B) { + try { + + if (A == null) + return B == null ? null : B; + // Todo enhanced this method + else + return A.getDepth() <= B.getDepth() ? A : B; + } catch (RepositoryException re) { + throw new ArgeoException("Cannot find ancestor", re); + } + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java new file mode 100644 index 000000000..ce42266cc --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/OpenGenericJcrQueryEditor.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.commands; + +import org.argeo.eclipse.ui.jcr.editors.JcrQueryEditorInput; +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.handlers.HandlerUtil; + +/** Open a JCR query editor. */ +public class OpenGenericJcrQueryEditor extends AbstractHandler { + private String editorId; + + public Object execute(ExecutionEvent event) throws ExecutionException { + try { + JcrQueryEditorInput editorInput = new JcrQueryEditorInput("", null); + IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow( + event).getActivePage(); + activePage.openEditor(editorInput, editorId); + } catch (Exception e) { + throw new ExecutionException("Cannot open editor", e); + } + return null; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/Refresh.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/Refresh.java new file mode 100644 index 000000000..f62be37eb --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/commands/Refresh.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.commands; + +import java.util.Iterator; + +import org.argeo.eclipse.ui.jcr.views.AbstractJcrBrowser; +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.handlers.HandlerUtil; + +/** + * Call the refresh method of the active AbstractJcrBrowser instance. + * + * Warning: this method only refreshes the viewer, if the model is "stale", e.g. + * if some changes in the underlying data have not yet been propagated to the + * model, the view will not display up-to-date information. + */ +@Deprecated +public class Refresh extends AbstractHandler { + + public Object execute(ExecutionEvent event) throws ExecutionException { + ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) + .getActivePage().getSelection(); + AbstractJcrBrowser view = (AbstractJcrBrowser) HandlerUtil + .getActiveWorkbenchWindow(event).getActivePage() + .findView(HandlerUtil.getActivePartId(event)); + if (selection != null && selection instanceof IStructuredSelection) { + Iterator it = ((IStructuredSelection) selection).iterator(); + while (it.hasNext()) { + Object obj = it.next(); + view.refresh(obj); + } + } + return null; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java new file mode 100644 index 000000000..5e7d69644 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/AbstractJcrQueryEditor.java @@ -0,0 +1,354 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.editors; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.query.QueryResult; +import javax.jcr.query.Row; +import javax.jcr.query.RowIterator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.GenericTableComparator; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.IDoubleClickListener; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.part.EditorPart; + +/** Executes any JCR query. */ +public abstract class AbstractJcrQueryEditor extends EditorPart { + private final static Log log = LogFactory + .getLog(AbstractJcrQueryEditor.class); + + protected String initialQuery; + protected String initialQueryType; + + /* DEPENDENCY INJECTION */ + private Session session; + + // Widgets + private TableViewer viewer; + private List tableViewerColumns = new ArrayList(); + private GenericTableComparator comparator; + + /** Override to layout a form enabling the end user to build his query */ + protected abstract void createQueryForm(Composite parent); + + @Override + public void init(IEditorSite site, IEditorInput input) + throws PartInitException { + JcrQueryEditorInput editorInput = (JcrQueryEditorInput) input; + initialQuery = editorInput.getQuery(); + initialQueryType = editorInput.getQueryType(); + setSite(site); + setInput(editorInput); + } + + @Override + public final void createPartControl(final Composite parent) { + parent.setLayout(new FillLayout()); + + SashForm sashForm = new SashForm(parent, SWT.VERTICAL); + sashForm.setSashWidth(4); + sashForm.setLayout(new FillLayout()); + + Composite top = new Composite(sashForm, SWT.NONE); + GridLayout gl = new GridLayout(1, false); + top.setLayout(gl); + + createQueryForm(top); + + Composite bottom = new Composite(sashForm, SWT.NONE); + bottom.setLayout(new GridLayout(1, false)); + sashForm.setWeights(getWeights()); + + viewer = new TableViewer(bottom); + viewer.getTable().setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, true)); + viewer.getTable().setHeaderVisible(true); + viewer.setContentProvider(getQueryResultContentProvider()); + viewer.setInput(getEditorSite()); + + if (getComparator() != null) { + comparator = getComparator(); + viewer.setComparator(comparator); + } + if (getTableDoubleClickListener() != null) + viewer.addDoubleClickListener(getTableDoubleClickListener()); + + } + + protected void executeQuery(String statement) { + try { + if (log.isDebugEnabled()) + log.debug("Query : " + statement); + + QueryResult qr = session.getWorkspace().getQueryManager() + .createQuery(statement, initialQueryType).execute(); + + // remove previous columns + for (TableViewerColumn tvc : tableViewerColumns) + tvc.getColumn().dispose(); + + int i = 0; + for (final String columnName : qr.getColumnNames()) { + TableViewerColumn tvc = new TableViewerColumn(viewer, SWT.NONE); + configureColumn(columnName, tvc, i); + tvc.setLabelProvider(getLabelProvider(columnName)); + tableViewerColumns.add(tvc); + i++; + } + + // Must create a local list: QueryResults can only be read once. + try { + List rows = new ArrayList(); + 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())); + } + } + + /** + * To be overidden to adapt size of form and result frames. + * + * @return + */ + protected int[] getWeights() { + return new int[] { 30, 70 }; + } + + /** + * To be overidden to implement a doubleclick Listener on one of the rows of + * the table. + * + * @return + */ + protected IDoubleClickListener getTableDoubleClickListener() { + return null; + } + + /** + * To be overiden in order to implement a specific + * QueryResultContentProvider + */ + protected IStructuredContentProvider getQueryResultContentProvider() { + return new QueryResultContentProvider(); + } + + /** + * Enable specific implementation for columns + */ + protected List getTableViewerColumns() { + return tableViewerColumns; + } + + /** + * Enable specific implementation for columns + */ + protected TableViewer getTableViewer() { + return viewer; + } + + /** + * To be overridden in order to configure column label providers . + */ + protected ColumnLabelProvider getLabelProvider(final String columnName) { + return new ColumnLabelProvider() { + 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; + } + }; + } + + /** + * To be overridden in order to configure the columns. + * + * @deprecated use {@link + * org.argeo.eclipse.ui.jcr.editors.AbstractJcrQueryEditor. + * configureColumn(String jcrColumnName, TableViewerColumn + * column, int columnIndex)} instead + */ + protected void configureColumn(String jcrColumnName, + TableViewerColumn column) { + column.getColumn().setWidth(50); + column.getColumn().setText(jcrColumnName); + } + + /** To be overridden in order to configure the columns. */ + protected void configureColumn(String jcrColumnName, + TableViewerColumn column, int columnIndex) { + column.getColumn().setWidth(50); + column.getColumn().setText(jcrColumnName); + } + + private class QueryResultContentProvider implements + IStructuredContentProvider { + + public void dispose() { + } + + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } + + public Object[] getElements(Object inputElement) { + + if (inputElement instanceof List) + return ((List) inputElement).toArray(); + + // Never reached might be deleted in future release + if (!(inputElement instanceof QueryResult)) + return new String[] {}; + + try { + QueryResult queryResult = (QueryResult) inputElement; + List rows = new ArrayList(); + RowIterator rit = queryResult.getRows(); + while (rit.hasNext()) { + rows.add(rit.nextRow()); + } + + // List elems = new ArrayList(); + // NodeIterator nit = queryResult.getNodes(); + // while (nit.hasNext()) { + // elems.add(nit.nextNode()); + // } + return rows.toArray(); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot read query result", e); + } + } + + } + + /** + * Might be used by children classes to sort columns. + * + * @param column + * @param index + * @return + */ + protected SelectionAdapter getSelectionAdapter(final TableColumn column, + final int index) { + + // A comparator must be define + if (comparator == null) + return null; + + SelectionAdapter selectionAdapter = new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + try { + + comparator.setColumn(index); + int dir = viewer.getTable().getSortDirection(); + if (viewer.getTable().getSortColumn() == column) { + dir = dir == SWT.UP ? SWT.DOWN : SWT.UP; + } else { + + dir = SWT.DOWN; + } + viewer.getTable().setSortDirection(dir); + viewer.getTable().setSortColumn(column); + viewer.refresh(); + } catch (Exception exc) { + exc.printStackTrace(); + } + } + }; + return selectionAdapter; + } + + /** + * To be overridden to enable sorting. + */ + protected GenericTableComparator getComparator() { + return null; + } + + @Override + public boolean isDirty() { + return false; + } + + @Override + public void doSave(IProgressMonitor monitor) { + // TODO save the query in JCR? + } + + @Override + public void doSaveAs() { + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } + + /** Returns the injected current session */ + protected Session getSession() { + return session; + } + + /* DEPENDENCY INJECTION */ + public void setSession(Session session) { + this.session = session; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java new file mode 100644 index 000000000..eedccc85b --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/JcrQueryEditorInput.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.editors; + +import javax.jcr.query.Query; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IPersistableElement; + +public class JcrQueryEditorInput implements IEditorInput { + private final String query; + private final String queryType; + + public JcrQueryEditorInput(String query, String queryType) { + this.query = query; + if (queryType == null) + this.queryType = Query.JCR_SQL2; + else + this.queryType = queryType; + } + + public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { + return null; + } + + public boolean exists() { + return true; + } + + public ImageDescriptor getImageDescriptor() { + return null; + } + + public String getName() { + return query; + } + + public IPersistableElement getPersistable() { + return null; + } + + public String getToolTipText() { + return query; + } + + public String getQuery() { + return query; + } + + public String getQueryType() { + return queryType; + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java new file mode 100644 index 000000000..a55884f2e --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/editors/NodeEditorInput.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.editors; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IPersistableElement; + +/** + * A canonical editor input based on a path to a node. In a multirepository + * environment, path can be enriched with Repository Alias and workspace + */ + +public class NodeEditorInput implements IEditorInput { + private final String path; + + public NodeEditorInput(String path) { + this.path = path; + } + + public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { + return null; + } + + public boolean exists() { + return true; + } + + public ImageDescriptor getImageDescriptor() { + return null; + } + + public String getName() { + return path; + } + + public IPersistableElement getPersistable() { + return null; + } + + public String getToolTipText() { + return path; + } + + public String getPath() { + return path; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java new file mode 100644 index 000000000..9e338276a --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/ColumnDefinition.java @@ -0,0 +1,88 @@ +package org.argeo.eclipse.ui.jcr.lists; + +/** + * Utility object to manage column in various tables and extracts displaying + * data from JCR + */ +public class ColumnDefinition { + private final static int DEFAULT_COLUMN_SIZE = 120; + + private String selectorName; + private String propertyName; + private String headerLabel; + private int propertyType; + private int columnSize = DEFAULT_COLUMN_SIZE; + + /** + * new column using default width + * + * @param selectorName + * @param propertyName + * @param propertyType + * @param headerLabel + */ + public ColumnDefinition(String selectorName, String propertyName, + int propertyType, String headerLabel) { + this.selectorName = selectorName; + this.propertyName = propertyName; + this.propertyType = propertyType; + this.headerLabel = headerLabel; + } + + /** + * + * @param selectorName + * @param propertyName + * @param propertyType + * @param headerLabel + * @param columnSize + */ + public ColumnDefinition(String selectorName, String propertyName, + int propertyType, String headerLabel, int columnSize) { + this.selectorName = selectorName; + this.propertyName = propertyName; + this.propertyType = propertyType; + this.headerLabel = headerLabel; + this.columnSize = columnSize; + } + + public String getSelectorName() { + return selectorName; + } + + public void setSelectorName(String selectorName) { + this.selectorName = selectorName; + } + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + public String getHeaderLabel() { + return headerLabel; + } + + public void setHeaderLabel(String headerLabel) { + this.headerLabel = headerLabel; + } + + public int getPropertyType() { + return propertyType; + } + + public void setPropertyType(int propertyType) { + this.propertyType = propertyType; + } + + public int getColumnSize() { + return columnSize; + } + + public void setColumnSize(int columnSize) { + this.columnSize = columnSize; + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/IListProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/IListProvider.java new file mode 100644 index 000000000..622e2e259 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/IListProvider.java @@ -0,0 +1,20 @@ +package org.argeo.eclipse.ui.jcr.lists; + +import java.util.List; + +/** + * Views and editors can implement this interface so that one of the row list + * that is displayed in the part (For instance in a Table or a Tree Viewer) can + * be rebuilt externally. typically to generate csv or calc extract. + */ +public interface IListProvider { + /** + * Returns an array of current and relevant elements + */ + public Object[] getElements(String extractId); + + /** + * Returns the column definition for passed ID + */ + public List getColumnDefinition(String extractId); +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java new file mode 100644 index 000000000..11f12e6f5 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/NodeViewerComparator.java @@ -0,0 +1,192 @@ +package org.argeo.eclipse.ui.jcr.lists; + +import java.math.BigDecimal; +import java.util.Calendar; + +import javax.jcr.Node; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFormatException; + +import org.argeo.ArgeoException; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerComparator; + +/** + * Base comparator to enable ordering on Table or Tree viewer that display Jcr + * Nodes. + * + * Note that the following snippet must be added before setting the comparator + * to the corresponding control: + * // IMPORTANT: initialize comparator before setting it + * ColumnDefinition firstCol = colDefs.get(0); + * comparator.setColumn(firstCol.getPropertyType(), + * firstCol.getPropertyName()); + * viewer.setComparator(comparator); + */ +public class NodeViewerComparator extends ViewerComparator { + + protected String propertyName; + + protected int propertyType; + public static final int ASCENDING = 0, DESCENDING = 1; + protected int direction = DESCENDING; + + public NodeViewerComparator() { + } + + /** + * e1 and e2 must both be Jcr nodes. + * + * @param viewer + * @param e1 + * @param e2 + * @return + */ + @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(propertyName)) + v1 = n1.getProperty(propertyName).getValue(); + if (n2.hasProperty(propertyName)) + v2 = n2.getProperty(propertyName).getValue(); + + if (v2 == null && v1 == null) + return 0; + else if (v2 == null) + return -1; + else if (v1 == null) + return 1; + + switch (propertyType) { + 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 a long + 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 = -1; + else if (lc > 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; + case PropertyType.DOUBLE: + Double d1 = v1.getDouble(); + Double d2 = v2.getDouble(); + rc = d1.compareTo(d2); + 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; + } + + /** + * @param propertyType + * Corresponding JCR type + * @param propertyName + * name of the property to use. + */ + public void setColumn(int propertyType, String propertyName) { + if (this.propertyName != null && this.propertyName.equals(propertyName)) { + // Same column as last sort; toggle the direction + direction = 1 - direction; + } else { + // New column; do an ascending sort + this.propertyType = propertyType; + this.propertyName = propertyName; + direction = ASCENDING; + } + } + + // Getters and setters + protected String getPropertyName() { + return propertyName; + } + + protected void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + protected int getPropertyType() { + return propertyType; + } + + protected void setPropertyType(int propertyType) { + this.propertyType = propertyType; + } + + protected int getDirection() { + return direction; + } + + protected void setDirection(int direction) { + this.direction = direction; + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java new file mode 100644 index 000000000..509f72324 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/RowViewerComparator.java @@ -0,0 +1,62 @@ +package org.argeo.eclipse.ui.jcr.lists; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.query.Row; + +import org.argeo.ArgeoException; +import org.eclipse.jface.viewers.Viewer; + +/** + * Base comparator to enable ordering on Table or Tree viewer that display Jcr + * rows + */ +public class RowViewerComparator extends NodeViewerComparator { + + protected String selectorName; + + public RowViewerComparator() { + } + + /** + * e1 and e2 must both be Jcr rows. + * + * @param viewer + * @param e1 + * @param e2 + * @return + */ + @Override + public int compare(Viewer viewer, Object e1, Object e2) { + try { + Node n1 = ((Row) e1).getNode(selectorName); + Node n2 = ((Row) e2).getNode(selectorName); + return super.compare(viewer, n1, n2); + } catch (RepositoryException re) { + throw new ArgeoException("Unexpected error " + + "while comparing nodes", re); + } + } + + /** + * @param propertyType + * Corresponding JCR type + * @param propertyName + * name of the property to use. + */ + public void setColumn(int propertyType, String selectorName, + String propertyName) { + if (this.selectorName != null && getPropertyName() != null + && this.selectorName.equals(selectorName) + && this.getPropertyName().equals(propertyName)) { + // Same column as last sort; toggle the direction + setDirection(1 - getDirection()); + } else { + // New column; do a descending sort + setPropertyType(propertyType); + setPropertyName(propertyName); + this.selectorName = selectorName; + setDirection(NodeViewerComparator.ASCENDING); + } + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java new file mode 100644 index 000000000..88585c343 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrNodeLabelProvider.java @@ -0,0 +1,122 @@ +package org.argeo.eclipse.ui.jcr.lists; + +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; + +import javax.jcr.Node; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; + +import org.argeo.ArgeoException; +import org.eclipse.jface.viewers.ColumnLabelProvider; + +/** + * Base implementation of a label provider for widgets that display JCR Rows. + */ +public class SimpleJcrNodeLabelProvider extends ColumnLabelProvider { + private static final long serialVersionUID = -5215787695436221993L; + + private final static String DEFAULT_DATE_FORMAT = "EEE, dd MMM yyyy"; + private final static String DEFAULT_NUMBER_FORMAT = "#,##0.0"; + + private DateFormat dateFormat; + private NumberFormat numberFormat; + + final private String propertyName; + + /** + * Default Label provider for a given property of a node. Using default + * pattern for date and number formating + */ + public SimpleJcrNodeLabelProvider(String propertyName) { + this.propertyName = propertyName; + dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT); + numberFormat = DecimalFormat.getInstance(); + ((DecimalFormat) numberFormat).applyPattern(DEFAULT_NUMBER_FORMAT); + } + + /** + * Label provider for a given property of a node optionally precising date + * and/or number format patterns + */ + public SimpleJcrNodeLabelProvider(String propertyName, + String dateFormatPattern, String numberFormatPattern) { + this.propertyName = propertyName; + dateFormat = new SimpleDateFormat( + dateFormatPattern == null ? DEFAULT_DATE_FORMAT + : dateFormatPattern); + numberFormat = DecimalFormat.getInstance(); + ((DecimalFormat) numberFormat) + .applyPattern(numberFormatPattern == null ? DEFAULT_NUMBER_FORMAT + : numberFormatPattern); + } + + @Override + public String getText(Object element) { + try { + Node currNode = (Node) element; + + if (currNode.hasProperty(propertyName)) { + if (currNode.getProperty(propertyName).isMultiple()) { + StringBuilder builder = new StringBuilder(); + for (Value value : currNode.getProperty(propertyName) + .getValues()) { + String currStr = getSingleValueAsString(value); + if (notEmptyString(currStr)) + builder.append(currStr).append("; "); + } + if (builder.length() > 0) + builder.deleteCharAt(builder.length() - 2); + + return builder.toString(); + } else + return getSingleValueAsString(currNode.getProperty( + propertyName).getValue()); + } else + return ""; + } catch (RepositoryException re) { + throw new ArgeoException("Unable to get text from row", re); + } + } + + private String getSingleValueAsString(Value value) + throws RepositoryException { + switch (value.getType()) { + case PropertyType.STRING: + return value.getString(); + case PropertyType.BOOLEAN: + return "" + value.getBoolean(); + case PropertyType.DATE: + return dateFormat.format(value.getDate().getTime()); + case PropertyType.LONG: + return "" + value.getLong(); + case PropertyType.DECIMAL: + return numberFormat.format(value.getDecimal()); + case PropertyType.DOUBLE: + return numberFormat.format(value.getDouble()); + case PropertyType.NAME: + return value.getString(); + default: + throw new ArgeoException("Unimplemented label provider " + + "for property type " + value.getType() + + " while getting property " + propertyName + " - value: " + + value.getString()); + + } + } + + private boolean notEmptyString(String string) { + return string != null && !"".equals(string.trim()); + } + + public void setDateFormat(String dateFormatPattern) { + dateFormat = new SimpleDateFormat(dateFormatPattern); + } + + public void setNumberFormat(String numberFormatPattern) { + ((DecimalFormat) numberFormat).applyPattern(numberFormatPattern); + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java new file mode 100644 index 000000000..bb55f187d --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/lists/SimpleJcrRowLabelProvider.java @@ -0,0 +1,47 @@ +package org.argeo.eclipse.ui.jcr.lists; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.query.Row; + +import org.argeo.ArgeoException; + +/** + * Base implementation of a label provider for widgets that display JCR Rows. + */ +public class SimpleJcrRowLabelProvider extends SimpleJcrNodeLabelProvider { + private static final long serialVersionUID = -3414654948197181740L; + + final private String selectorName; + + /** + * Default Label provider for a given property of a row. Using default + * pattern for date and number formating + */ + public SimpleJcrRowLabelProvider(String selectorName, String propertyName) { + super(propertyName); + this.selectorName = selectorName; + } + + /** + * Label provider for a given property of a node optionally precising date + * and/or number format patterns + */ + public SimpleJcrRowLabelProvider(String selectorName, String propertyName, + String dateFormatPattern, String numberFormatPattern) { + super(propertyName, dateFormatPattern, numberFormatPattern); + this.selectorName = selectorName; + } + + @Override + public String getText(Object element) { + try { + Row currRow = (Row) element; + Node currNode = currRow.getNode(selectorName); + return super.getText(currNode); + } catch (RepositoryException re) { + throw new ArgeoException("Unable to get Node " + selectorName + + " from row " + element, re); + } + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java new file mode 100644 index 000000000..b2e6455c8 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrFileProvider.java @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.utils; + +import java.io.InputStream; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.RepositoryException; +import javax.jcr.nodetype.NodeType; + +import org.apache.commons.io.IOUtils; +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.FileProvider; + +/** + * Implements a FileProvider for UI purposes. Note that it might not be very + * reliable as long as we have not fixed login & multi repository issues that + * will be addressed in the next version. + * + * NOTE: id used here is the real id of the JCR Node, not the JCR Path + * + * Relies on common approach for JCR file handling implementation. + * + */ + +public class JcrFileProvider implements FileProvider { + + // private Object[] rootNodes; + private Node refNode; + + /** + * Must be set in order for the provider to be able to get current session + * and thus have the ability to get the file node corresponding to a given + * file ID + * + * FIXME : this introduces some concurrences ISSUES. + * + * @param repositoryNode + */ + public void setReferenceNode(Node refNode) { + this.refNode = refNode; + } + + /** + * Must be set in order for the provider to be able to search the repository + * Provided object might be either JCR Nodes or UI RepositoryNode for the + * time being. + * + * @param repositoryNode + */ + // public void setRootNodes(Object[] rootNodes) { + // List tmpNodes = new ArrayList(); + // for (int i = 0; i < rootNodes.length; i++) { + // Object obj = rootNodes[i]; + // if (obj instanceof Node) { + // tmpNodes.add(obj); + // } else if (obj instanceof RepositoryRegister) { + // RepositoryRegister repositoryRegister = (RepositoryRegister) obj; + // Map repositories = repositoryRegister + // .getRepositories(); + // for (String name : repositories.keySet()) { + // // tmpNodes.add(new RepositoryNode(name, repositories + // // .get(name))); + // } + // + // } + // } + // this.rootNodes = tmpNodes.toArray(); + // } + + public byte[] getByteArrayFileFromId(String fileId) { + InputStream fis = null; + byte[] ba = null; + Node child = getFileNodeFromId(fileId); + try { + fis = (InputStream) child.getProperty(Property.JCR_DATA) + .getBinary().getStream(); + ba = IOUtils.toByteArray(fis); + + } catch (Exception e) { + throw new ArgeoException("Stream error while opening file", e); + } finally { + IOUtils.closeQuietly(fis); + } + return ba; + } + + public InputStream getInputStreamFromFileId(String fileId) { + try { + InputStream fis = null; + + Node child = getFileNodeFromId(fileId); + fis = (InputStream) child.getProperty(Property.JCR_DATA) + .getBinary().getStream(); + return fis; + } catch (RepositoryException re) { + throw new ArgeoException("Cannot get stream from file node for Id " + + fileId, re); + } + } + + /** + * Throws an exception if the node is not found in the current repository (a + * bit like a FileNotFoundException) + * + * @param fileId + * @return Returns the child node of the nt:file node. It is the child node + * that have the jcr:data property where actual file is stored. + * never null + */ + private Node getFileNodeFromId(String fileId) { + try { + Node result = refNode.getSession().getNodeByIdentifier(fileId); + + // rootNodes: for (int j = 0; j < rootNodes.length; j++) { + // // in case we have a classic JCR Node + // if (rootNodes[j] instanceof Node) { + // Node curNode = (Node) rootNodes[j]; + // if (result != null) + // break rootNodes; + // } // Case of a repository Node + // else if (rootNodes[j] instanceof RepositoryNode) { + // Object[] nodes = ((RepositoryNode) rootNodes[j]) + // .getChildren(); + // for (int i = 0; i < nodes.length; i++) { + // Node node = (Node) nodes[i]; + // result = node.getSession().getNodeByIdentifier(fileId); + // if (result != null) + // break rootNodes; + // } + // } + // } + + // Sanity checks + if (result == null) + throw new ArgeoException("File node not found for ID" + fileId); + + Node child = null; + + boolean isValid = true; + if (!result.isNodeType(NodeType.NT_FILE)) + // useless: mandatory child node + // || !result.hasNode(Property.JCR_CONTENT)) + isValid = false; + else { + child = result.getNode(Property.JCR_CONTENT); + if (!(child.isNodeType(NodeType.NT_RESOURCE) || child + .hasProperty(Property.JCR_DATA))) + isValid = false; + } + + if (!isValid) + throw new ArgeoException( + "ERROR: In the current implemented model, '" + + NodeType.NT_FILE + + "' file node must have a child node named jcr:content " + + "that has a BINARY Property named jcr:data " + + "where the actual data is stored"); + return child; + + } catch (RepositoryException re) { + throw new ArgeoException("Erreur while getting file node of ID " + + fileId, re); + } + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java new file mode 100644 index 000000000..2d36bf28a --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/JcrItemsComparator.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.utils; + +import java.util.Comparator; + +import javax.jcr.Item; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; + +/** Compares two JCR items (node or properties) based on their names. */ +public class JcrItemsComparator implements Comparator { + public int compare(Item o1, Item o2) { + try { + // TODO: put folder before files + return o1.getName().compareTo(o2.getName()); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot compare " + o1 + " and " + o2, e); + } + } + +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java new file mode 100644 index 000000000..5a94ee76a --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/NodeViewerComparer.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.utils; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; + +import org.argeo.ArgeoException; +import org.eclipse.jface.viewers.IElementComparer; + +/** Compare JCR nodes based on their JCR identifiers, for use in JFace viewers. */ +public class NodeViewerComparer implements IElementComparer { + + // force comparison on Node IDs only. + public boolean equals(Object elementA, Object elementB) { + if (!(elementA instanceof Node) || !(elementB instanceof Node)) { + return elementA == null ? elementB == null : elementA + .equals(elementB); + } else { + + boolean result = false; + try { + String idA = ((Node) elementA).getIdentifier(); + String idB = ((Node) elementB).getIdentifier(); + result = idA == null ? idB == null : idA.equals(idB); + } catch (RepositoryException re) { + throw new ArgeoException("cannot compare nodes", re); + } + + return result; + } + } + + public int hashCode(Object element) { + // TODO enhanced this method. + return element.getClass().toString().hashCode(); + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java new file mode 100644 index 000000000..40631cdde --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/utils/SingleSessionFileProvider.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.utils; + +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 org.apache.commons.io.IOUtils; +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.FileProvider; + +/** + * Implements a FileProvider for UI purposes. Unlike the + * JcrFileProvider , it relies on a single session and manages + * nodes with path only. + * + * Note that considered id is the JCR path + * + * Relies on common approach for JCR file handling implementation. + * + * @author bsinou + * + */ + +public class SingleSessionFileProvider implements FileProvider { + + private Session session; + + public SingleSessionFileProvider(Session session) { + this.session = session; + } + + public byte[] getByteArrayFileFromId(String fileId) { + InputStream fis = null; + byte[] ba = null; + Node child = getFileNodeFromId(fileId); + try { + fis = (InputStream) child.getProperty(Property.JCR_DATA) + .getBinary().getStream(); + ba = IOUtils.toByteArray(fis); + + } catch (Exception e) { + throw new ArgeoException("Stream error while opening file", e); + } finally { + IOUtils.closeQuietly(fis); + } + return ba; + } + + public InputStream getInputStreamFromFileId(String fileId) { + try { + InputStream fis = null; + + Node child = getFileNodeFromId(fileId); + fis = (InputStream) child.getProperty(Property.JCR_DATA) + .getBinary().getStream(); + return fis; + } catch (RepositoryException re) { + throw new ArgeoException("Cannot get stream from file node for Id " + + fileId, re); + } + } + + /** + * + * @param fileId + * @return Returns the child node of the nt:file node. It is the child node + * that have the jcr:data property where actual file is stored. + * never null + */ + private Node getFileNodeFromId(String fileId) { + try { + Node result = null; + result = session.getNode(fileId); + + // Sanity checks + if (result == null) + throw new ArgeoException("File node not found for ID" + fileId); + + // Ensure that the node have the correct type. + if (!result.isNodeType(NodeType.NT_FILE)) + throw new ArgeoException( + "Cannot open file children Node that are not of " + + NodeType.NT_RESOURCE + " type."); + + Node child = result.getNodes().nextNode(); + if (child == null || !child.isNodeType(NodeType.NT_RESOURCE)) + throw new ArgeoException( + "ERROR: IN the current implemented model, " + + NodeType.NT_FILE + + " file node must have one and only one child of the nt:ressource, where actual data is stored"); + return child; + } catch (RepositoryException re) { + throw new ArgeoException("Erreur while getting file node of ID " + + fileId, re); + } + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java new file mode 100644 index 000000000..133a65fd1 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/jcr/views/AbstractJcrBrowser.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.jcr.views; + +import javax.jcr.Node; + +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.part.ViewPart; + +public abstract class AbstractJcrBrowser extends ViewPart { + + @Override + public abstract void createPartControl(Composite parent); + + /** + * To be overridden to adapt size of form and result frames. + */ + abstract protected int[] getWeights(); + + /** + * To be overridden to provide an adapted size nodeViewer + */ + abstract protected TreeViewer createNodeViewer(Composite parent, + ITreeContentProvider nodeContentProvider); + + /** + * To be overridden to retrieve the current nodeViewer + */ + abstract protected TreeViewer getNodeViewer(); + + /* + * Enables the refresh of the tree. + */ + @Override + public void setFocus() { + getNodeViewer().getTree().setFocus(); + } + + public void refresh(Object obj) { + // getNodeViewer().update(obj, null); + getNodeViewer().refresh(obj); + // getNodeViewer().expandToLevel(obj, 1); + } + + public void nodeAdded(Node parentNode, Node newNode) { + getNodeViewer().refresh(parentNode); + getNodeViewer().expandToLevel(newNode, 0); + } + + public void nodeRemoved(Node parentNode) { + IStructuredSelection newSel = new StructuredSelection(parentNode); + getNodeViewer().setSelection(newSel, true); + // Force refresh + IStructuredSelection tmpSel = (IStructuredSelection) getNodeViewer() + .getSelection(); + getNodeViewer().refresh(tmpSel.getFirstElement()); + } +} diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/CommandUtils.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/CommandUtils.java new file mode 100644 index 000000000..22a139f13 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/CommandUtils.java @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.argeo.ArgeoException; +import org.argeo.eclipse.ui.ArgeoUiPlugin; +import org.eclipse.core.commands.Command; +import org.eclipse.core.commands.IParameter; +import org.eclipse.core.commands.Parameterization; +import org.eclipse.core.commands.ParameterizedCommand; +import org.eclipse.jface.action.IContributionItem; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.commands.ICommandService; +import org.eclipse.ui.handlers.IHandlerService; +import org.eclipse.ui.menus.CommandContributionItem; +import org.eclipse.ui.menus.CommandContributionItemParameter; +import org.eclipse.ui.services.IServiceLocator; + +/** + * Centralises useful and generic methods when dealing with commands in an + * Eclipse Workbench context + */ +public class CommandUtils { + + /** + * Commodities the refresh of a single command with no parameter in a + * Menu.aboutToShow method to simplify further development + * + * Note: that this method should be called with a false show command flag to + * remove a contribution that have been previously contributed + * + * @param menuManager + * @param locator + * @param cmdId + * @param label + * @param icon + * @param showCommand + */ + public static void refreshCommand(IMenuManager menuManager, + IServiceLocator locator, String cmdId, String label, + ImageDescriptor icon, boolean showCommand) { + refreshParameterizedCommand(menuManager, locator, cmdId, label, icon, + showCommand, null); + } + + /** + * Commodities the refresh the contribution of a command with a map of + * parameters in a context menu + * + * The command ID is used has contribution item ID + * + * @param menuManager + * @param locator + * @param cmdId + * @param label + * @param iconPath + * @param showCommand + */ + public static void refreshParameterizedCommand(IMenuManager menuManager, + IServiceLocator locator, String cmdId, String label, + ImageDescriptor icon, boolean showCommand, + Map params) { + refreshParameterizedCommand(menuManager, locator, cmdId, cmdId, label, + icon, showCommand, params); + } + + /** + * Commodities the refresh the contribution of a command with a map of + * parameters in a context menu + * + * @param menuManager + * @param locator + * @param contributionId + * @param commandId + * @param label + * @param icon + * @param showCommand + * @param params + */ + public static void refreshParameterizedCommand(IMenuManager menuManager, + IServiceLocator locator, String contributionId, String commandId, + String label, ImageDescriptor icon, boolean showCommand, + Map params) { + IContributionItem ici = menuManager.find(contributionId); + if (ici != null) + menuManager.remove(ici); + if (showCommand) { + CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter( + locator, null, commandId, SWT.PUSH); + + // Set Params + contributionItemParameter.label = label; + contributionItemParameter.icon = icon; + + if (params != null) + contributionItemParameter.parameters = params; + + CommandContributionItem cci = new CommandContributionItem( + contributionItemParameter); + cci.setId(contributionId); + menuManager.add(cci); + } + } + + /** Helper to call a command without parameter easily */ + public static void callCommand(String commandID) { + callCommand(commandID, null); + } + + /** Helper to call a command with a single parameter easily */ + public static void callCommand(String commandID, String parameterID, + String parameterValue) { + Map params = new HashMap(); + params.put(parameterID, parameterValue); + callCommand(commandID, params); + } + + /** + * Helper to call a command with a map of parameters easily + * + * @param paramMap + * a map that links various command IDs with corresponding String + * values. + */ + public static void callCommand(String commandID, + Map paramMap) { + try { + IWorkbench iw = ArgeoUiPlugin.getDefault().getWorkbench(); + IHandlerService handlerService = (IHandlerService) iw + .getService(IHandlerService.class); + ICommandService cmdService = (ICommandService) iw + .getActiveWorkbenchWindow().getService( + ICommandService.class); + Command cmd = cmdService.getCommand(commandID); + + ArrayList parameters = null; + ParameterizedCommand pc; + + if (paramMap != null) { + // Set parameters of the command to launch : + parameters = new ArrayList(); + Parameterization parameterization; + + for (String id : paramMap.keySet()) { + parameterization = new Parameterization( + cmd.getParameter(id), paramMap.get(id)); + parameters.add(parameterization); + } + pc = new ParameterizedCommand(cmd, + parameters.toArray(new Parameterization[parameters + .size()])); + } else + pc = new ParameterizedCommand(cmd, null); + + // execute the command + handlerService.executeCommand(pc, null); + } catch (Exception e) { + throw new ArgeoException("Unexpected error while" + + " calling the command " + commandID, e); + } + } + + // legacy methods. Should be removed soon + + /** + * Shortcut to call a command with a single parameter. + * + * WARNING: none of the parameter can be null + * + * @deprecated rather use callCommand(commandID,parameterID, + parameterValue) + */ + public static void CallCommandWithOneParameter(String commandId, + String paramId, String paramValue) { + try { + IWorkbench iw = ArgeoUiPlugin.getDefault().getWorkbench(); + IHandlerService handlerService = (IHandlerService) iw + .getService(IHandlerService.class); + + // Gets a command that must have been previously registered + IWorkbenchWindow window = iw.getActiveWorkbenchWindow(); + ICommandService cmdService = (ICommandService) window + .getService(ICommandService.class); + Command cmd = cmdService.getCommand(commandId); + + // Manages the single parameter + ArrayList parameters = new ArrayList(); + IParameter iparam = cmd.getParameter(paramId); + Parameterization params = new Parameterization(iparam, paramValue); + parameters.add(params); + + // Create and execute the command + ParameterizedCommand pc = new ParameterizedCommand(cmd, + parameters.toArray(new Parameterization[parameters.size()])); + handlerService = (IHandlerService) window + .getService(IHandlerService.class); + handlerService.executeCommand(pc, null); + } catch (Exception e) { + throw new ArgeoException( + "Error calling command of id:" + commandId, e); + } + } + + /** + * Commodities the refresh of a single command with a map of parameters in a + * Menu.aboutToShow method to simplify further development Rather use + * {@link refreshParameterizedCommand()} + */ + @Deprecated + public static void refreshParametrizedCommand(IMenuManager menuManager, + IServiceLocator locator, String cmdId, String label, + ImageDescriptor icon, boolean showCommand, + Map params) { + refreshParameterizedCommand(menuManager, locator, cmdId, label, icon, + showCommand, params); + } +} \ No newline at end of file diff --git a/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/ViewerUtils.java b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/ViewerUtils.java new file mode 100644 index 000000000..42e9fab99 --- /dev/null +++ b/org.argeo.eclipse.ui/src/org/argeo/eclipse/ui/utils/ViewerUtils.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2012 Argeo GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.argeo.eclipse.ui.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 Jface Table, Tree and TreeColumn + * viewers. + */ +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; + } +}